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 <cassert>
92 #include <cstddef>
93 #include <cstdint>
94 #include <functional>
95 #include <limits>
96 #include <string>
97 #include <tuple>
98 #include <utility>
99 
100 using namespace clang;
101 using namespace sema;
102 
103 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
104                                                     unsigned ByteNo) const {
105   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
106                                Context.getTargetInfo());
107 }
108 
109 /// Checks that a call expression's argument count is the desired number.
110 /// This is useful when doing custom type-checking.  Returns true on error.
111 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
112   unsigned argCount = call->getNumArgs();
113   if (argCount == desiredArgCount) return false;
114 
115   if (argCount < desiredArgCount)
116     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
117            << 0 /*function call*/ << desiredArgCount << argCount
118            << call->getSourceRange();
119 
120   // Highlight all the excess arguments.
121   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
122                     call->getArg(argCount - 1)->getEndLoc());
123 
124   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
125     << 0 /*function call*/ << desiredArgCount << argCount
126     << call->getArg(1)->getSourceRange();
127 }
128 
129 /// Check that the first argument to __builtin_annotation is an integer
130 /// and the second argument is a non-wide string literal.
131 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
132   if (checkArgCount(S, TheCall, 2))
133     return true;
134 
135   // First argument should be an integer.
136   Expr *ValArg = TheCall->getArg(0);
137   QualType Ty = ValArg->getType();
138   if (!Ty->isIntegerType()) {
139     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
140         << ValArg->getSourceRange();
141     return true;
142   }
143 
144   // Second argument should be a constant string.
145   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
146   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
147   if (!Literal || !Literal->isAscii()) {
148     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
149         << StrArg->getSourceRange();
150     return true;
151   }
152 
153   TheCall->setType(Ty);
154   return false;
155 }
156 
157 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
158   // We need at least one argument.
159   if (TheCall->getNumArgs() < 1) {
160     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
161         << 0 << 1 << TheCall->getNumArgs()
162         << TheCall->getCallee()->getSourceRange();
163     return true;
164   }
165 
166   // All arguments should be wide string literals.
167   for (Expr *Arg : TheCall->arguments()) {
168     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
169     if (!Literal || !Literal->isWide()) {
170       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
171           << Arg->getSourceRange();
172       return true;
173     }
174   }
175 
176   return false;
177 }
178 
179 /// Check that the argument to __builtin_addressof is a glvalue, and set the
180 /// result type to the corresponding pointer type.
181 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
182   if (checkArgCount(S, TheCall, 1))
183     return true;
184 
185   ExprResult Arg(TheCall->getArg(0));
186   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
187   if (ResultType.isNull())
188     return true;
189 
190   TheCall->setArg(0, Arg.get());
191   TheCall->setType(ResultType);
192   return false;
193 }
194 
195 /// Check the number of arguments and set the result type to
196 /// the argument type.
197 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
198   if (checkArgCount(S, TheCall, 1))
199     return true;
200 
201   TheCall->setType(TheCall->getArg(0)->getType());
202   return false;
203 }
204 
205 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
206 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
207 /// type (but not a function pointer) and that the alignment is a power-of-two.
208 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
209   if (checkArgCount(S, TheCall, 2))
210     return true;
211 
212   clang::Expr *Source = TheCall->getArg(0);
213   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
214 
215   auto IsValidIntegerType = [](QualType Ty) {
216     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
217   };
218   QualType SrcTy = Source->getType();
219   // We should also be able to use it with arrays (but not functions!).
220   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
221     SrcTy = S.Context.getDecayedType(SrcTy);
222   }
223   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
224       SrcTy->isFunctionPointerType()) {
225     // FIXME: this is not quite the right error message since we don't allow
226     // floating point types, or member pointers.
227     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
228         << SrcTy;
229     return true;
230   }
231 
232   clang::Expr *AlignOp = TheCall->getArg(1);
233   if (!IsValidIntegerType(AlignOp->getType())) {
234     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
235         << AlignOp->getType();
236     return true;
237   }
238   Expr::EvalResult AlignResult;
239   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
240   // We can't check validity of alignment if it is type dependent.
241   if (!AlignOp->isInstantiationDependent() &&
242       AlignOp->EvaluateAsInt(AlignResult, S.Context,
243                              Expr::SE_AllowSideEffects)) {
244     llvm::APSInt AlignValue = AlignResult.Val.getInt();
245     llvm::APSInt MaxValue(
246         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
247     if (AlignValue < 1) {
248       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
249       return true;
250     }
251     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
252       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
253           << MaxValue.toString(10);
254       return true;
255     }
256     if (!AlignValue.isPowerOf2()) {
257       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
258       return true;
259     }
260     if (AlignValue == 1) {
261       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
262           << IsBooleanAlignBuiltin;
263     }
264   }
265 
266   ExprResult SrcArg = S.PerformCopyInitialization(
267       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
268       SourceLocation(), Source);
269   if (SrcArg.isInvalid())
270     return true;
271   TheCall->setArg(0, SrcArg.get());
272   ExprResult AlignArg =
273       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
274                                       S.Context, AlignOp->getType(), false),
275                                   SourceLocation(), AlignOp);
276   if (AlignArg.isInvalid())
277     return true;
278   TheCall->setArg(1, AlignArg.get());
279   // For align_up/align_down, the return type is the same as the (potentially
280   // decayed) argument type including qualifiers. For is_aligned(), the result
281   // is always bool.
282   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
283   return false;
284 }
285 
286 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
287                                 unsigned BuiltinID) {
288   if (checkArgCount(S, TheCall, 3))
289     return true;
290 
291   // First two arguments should be integers.
292   for (unsigned I = 0; I < 2; ++I) {
293     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
294     if (Arg.isInvalid()) return true;
295     TheCall->setArg(I, Arg.get());
296 
297     QualType Ty = Arg.get()->getType();
298     if (!Ty->isIntegerType()) {
299       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
300           << Ty << Arg.get()->getSourceRange();
301       return true;
302     }
303   }
304 
305   // Third argument should be a pointer to a non-const integer.
306   // IRGen correctly handles volatile, restrict, and address spaces, and
307   // the other qualifiers aren't possible.
308   {
309     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
310     if (Arg.isInvalid()) return true;
311     TheCall->setArg(2, Arg.get());
312 
313     QualType Ty = Arg.get()->getType();
314     const auto *PtrTy = Ty->getAs<PointerType>();
315     if (!PtrTy ||
316         !PtrTy->getPointeeType()->isIntegerType() ||
317         PtrTy->getPointeeType().isConstQualified()) {
318       S.Diag(Arg.get()->getBeginLoc(),
319              diag::err_overflow_builtin_must_be_ptr_int)
320         << Ty << Arg.get()->getSourceRange();
321       return true;
322     }
323   }
324 
325   // Disallow signed ExtIntType args larger than 128 bits to mul function until
326   // we improve backend support.
327   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
328     for (unsigned I = 0; I < 3; ++I) {
329       const auto Arg = TheCall->getArg(I);
330       // Third argument will be a pointer.
331       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
332       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
333           S.getASTContext().getIntWidth(Ty) > 128)
334         return S.Diag(Arg->getBeginLoc(),
335                       diag::err_overflow_builtin_ext_int_max_size)
336                << 128;
337     }
338   }
339 
340   return false;
341 }
342 
343 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
344   if (checkArgCount(S, BuiltinCall, 2))
345     return true;
346 
347   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
348   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
349   Expr *Call = BuiltinCall->getArg(0);
350   Expr *Chain = BuiltinCall->getArg(1);
351 
352   if (Call->getStmtClass() != Stmt::CallExprClass) {
353     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
354         << Call->getSourceRange();
355     return true;
356   }
357 
358   auto CE = cast<CallExpr>(Call);
359   if (CE->getCallee()->getType()->isBlockPointerType()) {
360     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
361         << Call->getSourceRange();
362     return true;
363   }
364 
365   const Decl *TargetDecl = CE->getCalleeDecl();
366   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
367     if (FD->getBuiltinID()) {
368       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
369           << Call->getSourceRange();
370       return true;
371     }
372 
373   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
374     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
375         << Call->getSourceRange();
376     return true;
377   }
378 
379   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
380   if (ChainResult.isInvalid())
381     return true;
382   if (!ChainResult.get()->getType()->isPointerType()) {
383     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
384         << Chain->getSourceRange();
385     return true;
386   }
387 
388   QualType ReturnTy = CE->getCallReturnType(S.Context);
389   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
390   QualType BuiltinTy = S.Context.getFunctionType(
391       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
392   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
393 
394   Builtin =
395       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
396 
397   BuiltinCall->setType(CE->getType());
398   BuiltinCall->setValueKind(CE->getValueKind());
399   BuiltinCall->setObjectKind(CE->getObjectKind());
400   BuiltinCall->setCallee(Builtin);
401   BuiltinCall->setArg(1, ChainResult.get());
402 
403   return false;
404 }
405 
406 namespace {
407 
408 class EstimateSizeFormatHandler
409     : public analyze_format_string::FormatStringHandler {
410   size_t Size;
411 
412 public:
413   EstimateSizeFormatHandler(StringRef Format)
414       : Size(std::min(Format.find(0), Format.size()) +
415              1 /* null byte always written by sprintf */) {}
416 
417   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
418                              const char *, unsigned SpecifierLen) override {
419 
420     const size_t FieldWidth = computeFieldWidth(FS);
421     const size_t Precision = computePrecision(FS);
422 
423     // The actual format.
424     switch (FS.getConversionSpecifier().getKind()) {
425     // Just a char.
426     case analyze_format_string::ConversionSpecifier::cArg:
427     case analyze_format_string::ConversionSpecifier::CArg:
428       Size += std::max(FieldWidth, (size_t)1);
429       break;
430     // Just an integer.
431     case analyze_format_string::ConversionSpecifier::dArg:
432     case analyze_format_string::ConversionSpecifier::DArg:
433     case analyze_format_string::ConversionSpecifier::iArg:
434     case analyze_format_string::ConversionSpecifier::oArg:
435     case analyze_format_string::ConversionSpecifier::OArg:
436     case analyze_format_string::ConversionSpecifier::uArg:
437     case analyze_format_string::ConversionSpecifier::UArg:
438     case analyze_format_string::ConversionSpecifier::xArg:
439     case analyze_format_string::ConversionSpecifier::XArg:
440       Size += std::max(FieldWidth, Precision);
441       break;
442 
443     // %g style conversion switches between %f or %e style dynamically.
444     // %f always takes less space, so default to it.
445     case analyze_format_string::ConversionSpecifier::gArg:
446     case analyze_format_string::ConversionSpecifier::GArg:
447 
448     // Floating point number in the form '[+]ddd.ddd'.
449     case analyze_format_string::ConversionSpecifier::fArg:
450     case analyze_format_string::ConversionSpecifier::FArg:
451       Size += std::max(FieldWidth, 1 /* integer part */ +
452                                        (Precision ? 1 + Precision
453                                                   : 0) /* period + decimal */);
454       break;
455 
456     // Floating point number in the form '[-]d.ddde[+-]dd'.
457     case analyze_format_string::ConversionSpecifier::eArg:
458     case analyze_format_string::ConversionSpecifier::EArg:
459       Size +=
460           std::max(FieldWidth,
461                    1 /* integer part */ +
462                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
463                        1 /* e or E letter */ + 2 /* exponent */);
464       break;
465 
466     // Floating point number in the form '[-]0xh.hhhhp±dd'.
467     case analyze_format_string::ConversionSpecifier::aArg:
468     case analyze_format_string::ConversionSpecifier::AArg:
469       Size +=
470           std::max(FieldWidth,
471                    2 /* 0x */ + 1 /* integer part */ +
472                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
473                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
474       break;
475 
476     // Just a string.
477     case analyze_format_string::ConversionSpecifier::sArg:
478     case analyze_format_string::ConversionSpecifier::SArg:
479       Size += FieldWidth;
480       break;
481 
482     // Just a pointer in the form '0xddd'.
483     case analyze_format_string::ConversionSpecifier::pArg:
484       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
485       break;
486 
487     // A plain percent.
488     case analyze_format_string::ConversionSpecifier::PercentArg:
489       Size += 1;
490       break;
491 
492     default:
493       break;
494     }
495 
496     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
497 
498     if (FS.hasAlternativeForm()) {
499       switch (FS.getConversionSpecifier().getKind()) {
500       default:
501         break;
502       // Force a leading '0'.
503       case analyze_format_string::ConversionSpecifier::oArg:
504         Size += 1;
505         break;
506       // Force a leading '0x'.
507       case analyze_format_string::ConversionSpecifier::xArg:
508       case analyze_format_string::ConversionSpecifier::XArg:
509         Size += 2;
510         break;
511       // Force a period '.' before decimal, even if precision is 0.
512       case analyze_format_string::ConversionSpecifier::aArg:
513       case analyze_format_string::ConversionSpecifier::AArg:
514       case analyze_format_string::ConversionSpecifier::eArg:
515       case analyze_format_string::ConversionSpecifier::EArg:
516       case analyze_format_string::ConversionSpecifier::fArg:
517       case analyze_format_string::ConversionSpecifier::FArg:
518       case analyze_format_string::ConversionSpecifier::gArg:
519       case analyze_format_string::ConversionSpecifier::GArg:
520         Size += (Precision ? 0 : 1);
521         break;
522       }
523     }
524     assert(SpecifierLen <= Size && "no underflow");
525     Size -= SpecifierLen;
526     return true;
527   }
528 
529   size_t getSizeLowerBound() const { return Size; }
530 
531 private:
532   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
533     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
534     size_t FieldWidth = 0;
535     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
536       FieldWidth = FW.getConstantAmount();
537     return FieldWidth;
538   }
539 
540   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
541     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
542     size_t Precision = 0;
543 
544     // See man 3 printf for default precision value based on the specifier.
545     switch (FW.getHowSpecified()) {
546     case analyze_format_string::OptionalAmount::NotSpecified:
547       switch (FS.getConversionSpecifier().getKind()) {
548       default:
549         break;
550       case analyze_format_string::ConversionSpecifier::dArg: // %d
551       case analyze_format_string::ConversionSpecifier::DArg: // %D
552       case analyze_format_string::ConversionSpecifier::iArg: // %i
553         Precision = 1;
554         break;
555       case analyze_format_string::ConversionSpecifier::oArg: // %d
556       case analyze_format_string::ConversionSpecifier::OArg: // %D
557       case analyze_format_string::ConversionSpecifier::uArg: // %d
558       case analyze_format_string::ConversionSpecifier::UArg: // %D
559       case analyze_format_string::ConversionSpecifier::xArg: // %d
560       case analyze_format_string::ConversionSpecifier::XArg: // %D
561         Precision = 1;
562         break;
563       case analyze_format_string::ConversionSpecifier::fArg: // %f
564       case analyze_format_string::ConversionSpecifier::FArg: // %F
565       case analyze_format_string::ConversionSpecifier::eArg: // %e
566       case analyze_format_string::ConversionSpecifier::EArg: // %E
567       case analyze_format_string::ConversionSpecifier::gArg: // %g
568       case analyze_format_string::ConversionSpecifier::GArg: // %G
569         Precision = 6;
570         break;
571       case analyze_format_string::ConversionSpecifier::pArg: // %d
572         Precision = 1;
573         break;
574       }
575       break;
576     case analyze_format_string::OptionalAmount::Constant:
577       Precision = FW.getConstantAmount();
578       break;
579     default:
580       break;
581     }
582     return Precision;
583   }
584 };
585 
586 } // namespace
587 
588 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
589 /// __builtin_*_chk function, then use the object size argument specified in the
590 /// source. Otherwise, infer the object size using __builtin_object_size.
591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
592                                                CallExpr *TheCall) {
593   // FIXME: There are some more useful checks we could be doing here:
594   //  - Evaluate strlen of strcpy arguments, use as object size.
595 
596   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
597       isConstantEvaluated())
598     return;
599 
600   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
601   if (!BuiltinID)
602     return;
603 
604   const TargetInfo &TI = getASTContext().getTargetInfo();
605   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
606 
607   unsigned DiagID = 0;
608   bool IsChkVariant = false;
609   Optional<llvm::APSInt> UsedSize;
610   unsigned SizeIndex, ObjectIndex;
611   switch (BuiltinID) {
612   default:
613     return;
614   case Builtin::BIsprintf:
615   case Builtin::BI__builtin___sprintf_chk: {
616     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
617     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
618 
619     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
620 
621       if (!Format->isAscii() && !Format->isUTF8())
622         return;
623 
624       StringRef FormatStrRef = Format->getString();
625       EstimateSizeFormatHandler H(FormatStrRef);
626       const char *FormatBytes = FormatStrRef.data();
627       const ConstantArrayType *T =
628           Context.getAsConstantArrayType(Format->getType());
629       assert(T && "String literal not of constant array type!");
630       size_t TypeSize = T->getSize().getZExtValue();
631 
632       // In case there's a null byte somewhere.
633       size_t StrLen =
634           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
635       if (!analyze_format_string::ParsePrintfString(
636               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
637               Context.getTargetInfo(), false)) {
638         DiagID = diag::warn_fortify_source_format_overflow;
639         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
640                        .extOrTrunc(SizeTypeWidth);
641         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
642           IsChkVariant = true;
643           ObjectIndex = 2;
644         } else {
645           IsChkVariant = false;
646           ObjectIndex = 0;
647         }
648         break;
649       }
650     }
651     return;
652   }
653   case Builtin::BI__builtin___memcpy_chk:
654   case Builtin::BI__builtin___memmove_chk:
655   case Builtin::BI__builtin___memset_chk:
656   case Builtin::BI__builtin___strlcat_chk:
657   case Builtin::BI__builtin___strlcpy_chk:
658   case Builtin::BI__builtin___strncat_chk:
659   case Builtin::BI__builtin___strncpy_chk:
660   case Builtin::BI__builtin___stpncpy_chk:
661   case Builtin::BI__builtin___memccpy_chk:
662   case Builtin::BI__builtin___mempcpy_chk: {
663     DiagID = diag::warn_builtin_chk_overflow;
664     IsChkVariant = true;
665     SizeIndex = TheCall->getNumArgs() - 2;
666     ObjectIndex = TheCall->getNumArgs() - 1;
667     break;
668   }
669 
670   case Builtin::BI__builtin___snprintf_chk:
671   case Builtin::BI__builtin___vsnprintf_chk: {
672     DiagID = diag::warn_builtin_chk_overflow;
673     IsChkVariant = true;
674     SizeIndex = 1;
675     ObjectIndex = 3;
676     break;
677   }
678 
679   case Builtin::BIstrncat:
680   case Builtin::BI__builtin_strncat:
681   case Builtin::BIstrncpy:
682   case Builtin::BI__builtin_strncpy:
683   case Builtin::BIstpncpy:
684   case Builtin::BI__builtin_stpncpy: {
685     // Whether these functions overflow depends on the runtime strlen of the
686     // string, not just the buffer size, so emitting the "always overflow"
687     // diagnostic isn't quite right. We should still diagnose passing a buffer
688     // size larger than the destination buffer though; this is a runtime abort
689     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
690     DiagID = diag::warn_fortify_source_size_mismatch;
691     SizeIndex = TheCall->getNumArgs() - 1;
692     ObjectIndex = 0;
693     break;
694   }
695 
696   case Builtin::BImemcpy:
697   case Builtin::BI__builtin_memcpy:
698   case Builtin::BImemmove:
699   case Builtin::BI__builtin_memmove:
700   case Builtin::BImemset:
701   case Builtin::BI__builtin_memset:
702   case Builtin::BImempcpy:
703   case Builtin::BI__builtin_mempcpy: {
704     DiagID = diag::warn_fortify_source_overflow;
705     SizeIndex = TheCall->getNumArgs() - 1;
706     ObjectIndex = 0;
707     break;
708   }
709   case Builtin::BIsnprintf:
710   case Builtin::BI__builtin_snprintf:
711   case Builtin::BIvsnprintf:
712   case Builtin::BI__builtin_vsnprintf: {
713     DiagID = diag::warn_fortify_source_size_mismatch;
714     SizeIndex = 1;
715     ObjectIndex = 0;
716     break;
717   }
718   }
719 
720   llvm::APSInt ObjectSize;
721   // For __builtin___*_chk, the object size is explicitly provided by the caller
722   // (usually using __builtin_object_size). Use that value to check this call.
723   if (IsChkVariant) {
724     Expr::EvalResult Result;
725     Expr *SizeArg = TheCall->getArg(ObjectIndex);
726     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
727       return;
728     ObjectSize = Result.Val.getInt();
729 
730   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
731   } else {
732     // If the parameter has a pass_object_size attribute, then we should use its
733     // (potentially) more strict checking mode. Otherwise, conservatively assume
734     // type 0.
735     int BOSType = 0;
736     if (const auto *POS =
737             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
738       BOSType = POS->getType();
739 
740     Expr *ObjArg = TheCall->getArg(ObjectIndex);
741     uint64_t Result;
742     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
743       return;
744     // Get the object size in the target's size_t width.
745     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
746   }
747 
748   // Evaluate the number of bytes of the object that this call will use.
749   if (!UsedSize) {
750     Expr::EvalResult Result;
751     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
752     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
753       return;
754     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
755   }
756 
757   if (UsedSize.getValue().ule(ObjectSize))
758     return;
759 
760   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
761   // Skim off the details of whichever builtin was called to produce a better
762   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
763   if (IsChkVariant) {
764     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
765     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
766   } else if (FunctionName.startswith("__builtin_")) {
767     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
768   }
769 
770   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
771                       PDiag(DiagID)
772                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
773                           << UsedSize.getValue().toString(/*Radix=*/10));
774 }
775 
776 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
777                                      Scope::ScopeFlags NeededScopeFlags,
778                                      unsigned DiagID) {
779   // Scopes aren't available during instantiation. Fortunately, builtin
780   // functions cannot be template args so they cannot be formed through template
781   // instantiation. Therefore checking once during the parse is sufficient.
782   if (SemaRef.inTemplateInstantiation())
783     return false;
784 
785   Scope *S = SemaRef.getCurScope();
786   while (S && !S->isSEHExceptScope())
787     S = S->getParent();
788   if (!S || !(S->getFlags() & NeededScopeFlags)) {
789     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
790     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
791         << DRE->getDecl()->getIdentifier();
792     return true;
793   }
794 
795   return false;
796 }
797 
798 static inline bool isBlockPointer(Expr *Arg) {
799   return Arg->getType()->isBlockPointerType();
800 }
801 
802 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
803 /// void*, which is a requirement of device side enqueue.
804 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
805   const BlockPointerType *BPT =
806       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
807   ArrayRef<QualType> Params =
808       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
809   unsigned ArgCounter = 0;
810   bool IllegalParams = false;
811   // Iterate through the block parameters until either one is found that is not
812   // a local void*, or the block is valid.
813   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
814        I != E; ++I, ++ArgCounter) {
815     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
816         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
817             LangAS::opencl_local) {
818       // Get the location of the error. If a block literal has been passed
819       // (BlockExpr) then we can point straight to the offending argument,
820       // else we just point to the variable reference.
821       SourceLocation ErrorLoc;
822       if (isa<BlockExpr>(BlockArg)) {
823         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
824         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
825       } else if (isa<DeclRefExpr>(BlockArg)) {
826         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
827       }
828       S.Diag(ErrorLoc,
829              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
830       IllegalParams = true;
831     }
832   }
833 
834   return IllegalParams;
835 }
836 
837 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
838   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
839     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
840         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
841     return true;
842   }
843   return false;
844 }
845 
846 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
847   if (checkArgCount(S, TheCall, 2))
848     return true;
849 
850   if (checkOpenCLSubgroupExt(S, TheCall))
851     return true;
852 
853   // First argument is an ndrange_t type.
854   Expr *NDRangeArg = TheCall->getArg(0);
855   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
856     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
857         << TheCall->getDirectCallee() << "'ndrange_t'";
858     return true;
859   }
860 
861   Expr *BlockArg = TheCall->getArg(1);
862   if (!isBlockPointer(BlockArg)) {
863     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
864         << TheCall->getDirectCallee() << "block";
865     return true;
866   }
867   return checkOpenCLBlockArgs(S, BlockArg);
868 }
869 
870 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
871 /// get_kernel_work_group_size
872 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
873 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
874   if (checkArgCount(S, TheCall, 1))
875     return true;
876 
877   Expr *BlockArg = TheCall->getArg(0);
878   if (!isBlockPointer(BlockArg)) {
879     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
880         << TheCall->getDirectCallee() << "block";
881     return true;
882   }
883   return checkOpenCLBlockArgs(S, BlockArg);
884 }
885 
886 /// Diagnose integer type and any valid implicit conversion to it.
887 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
888                                       const QualType &IntType);
889 
890 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
891                                             unsigned Start, unsigned End) {
892   bool IllegalParams = false;
893   for (unsigned I = Start; I <= End; ++I)
894     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
895                                               S.Context.getSizeType());
896   return IllegalParams;
897 }
898 
899 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
900 /// 'local void*' parameter of passed block.
901 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
902                                            Expr *BlockArg,
903                                            unsigned NumNonVarArgs) {
904   const BlockPointerType *BPT =
905       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
906   unsigned NumBlockParams =
907       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
908   unsigned TotalNumArgs = TheCall->getNumArgs();
909 
910   // For each argument passed to the block, a corresponding uint needs to
911   // be passed to describe the size of the local memory.
912   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
913     S.Diag(TheCall->getBeginLoc(),
914            diag::err_opencl_enqueue_kernel_local_size_args);
915     return true;
916   }
917 
918   // Check that the sizes of the local memory are specified by integers.
919   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
920                                          TotalNumArgs - 1);
921 }
922 
923 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
924 /// overload formats specified in Table 6.13.17.1.
925 /// int enqueue_kernel(queue_t queue,
926 ///                    kernel_enqueue_flags_t flags,
927 ///                    const ndrange_t ndrange,
928 ///                    void (^block)(void))
929 /// int enqueue_kernel(queue_t queue,
930 ///                    kernel_enqueue_flags_t flags,
931 ///                    const ndrange_t ndrange,
932 ///                    uint num_events_in_wait_list,
933 ///                    clk_event_t *event_wait_list,
934 ///                    clk_event_t *event_ret,
935 ///                    void (^block)(void))
936 /// int enqueue_kernel(queue_t queue,
937 ///                    kernel_enqueue_flags_t flags,
938 ///                    const ndrange_t ndrange,
939 ///                    void (^block)(local void*, ...),
940 ///                    uint size0, ...)
941 /// int enqueue_kernel(queue_t queue,
942 ///                    kernel_enqueue_flags_t flags,
943 ///                    const ndrange_t ndrange,
944 ///                    uint num_events_in_wait_list,
945 ///                    clk_event_t *event_wait_list,
946 ///                    clk_event_t *event_ret,
947 ///                    void (^block)(local void*, ...),
948 ///                    uint size0, ...)
949 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
950   unsigned NumArgs = TheCall->getNumArgs();
951 
952   if (NumArgs < 4) {
953     S.Diag(TheCall->getBeginLoc(),
954            diag::err_typecheck_call_too_few_args_at_least)
955         << 0 << 4 << NumArgs;
956     return true;
957   }
958 
959   Expr *Arg0 = TheCall->getArg(0);
960   Expr *Arg1 = TheCall->getArg(1);
961   Expr *Arg2 = TheCall->getArg(2);
962   Expr *Arg3 = TheCall->getArg(3);
963 
964   // First argument always needs to be a queue_t type.
965   if (!Arg0->getType()->isQueueT()) {
966     S.Diag(TheCall->getArg(0)->getBeginLoc(),
967            diag::err_opencl_builtin_expected_type)
968         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
969     return true;
970   }
971 
972   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
973   if (!Arg1->getType()->isIntegerType()) {
974     S.Diag(TheCall->getArg(1)->getBeginLoc(),
975            diag::err_opencl_builtin_expected_type)
976         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
977     return true;
978   }
979 
980   // Third argument is always an ndrange_t type.
981   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
982     S.Diag(TheCall->getArg(2)->getBeginLoc(),
983            diag::err_opencl_builtin_expected_type)
984         << TheCall->getDirectCallee() << "'ndrange_t'";
985     return true;
986   }
987 
988   // With four arguments, there is only one form that the function could be
989   // called in: no events and no variable arguments.
990   if (NumArgs == 4) {
991     // check that the last argument is the right block type.
992     if (!isBlockPointer(Arg3)) {
993       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
994           << TheCall->getDirectCallee() << "block";
995       return true;
996     }
997     // we have a block type, check the prototype
998     const BlockPointerType *BPT =
999         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1000     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1001       S.Diag(Arg3->getBeginLoc(),
1002              diag::err_opencl_enqueue_kernel_blocks_no_args);
1003       return true;
1004     }
1005     return false;
1006   }
1007   // we can have block + varargs.
1008   if (isBlockPointer(Arg3))
1009     return (checkOpenCLBlockArgs(S, Arg3) ||
1010             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1011   // last two cases with either exactly 7 args or 7 args and varargs.
1012   if (NumArgs >= 7) {
1013     // check common block argument.
1014     Expr *Arg6 = TheCall->getArg(6);
1015     if (!isBlockPointer(Arg6)) {
1016       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1017           << TheCall->getDirectCallee() << "block";
1018       return true;
1019     }
1020     if (checkOpenCLBlockArgs(S, Arg6))
1021       return true;
1022 
1023     // Forth argument has to be any integer type.
1024     if (!Arg3->getType()->isIntegerType()) {
1025       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1026              diag::err_opencl_builtin_expected_type)
1027           << TheCall->getDirectCallee() << "integer";
1028       return true;
1029     }
1030     // check remaining common arguments.
1031     Expr *Arg4 = TheCall->getArg(4);
1032     Expr *Arg5 = TheCall->getArg(5);
1033 
1034     // Fifth argument is always passed as a pointer to clk_event_t.
1035     if (!Arg4->isNullPointerConstant(S.Context,
1036                                      Expr::NPC_ValueDependentIsNotNull) &&
1037         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1038       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1039              diag::err_opencl_builtin_expected_type)
1040           << TheCall->getDirectCallee()
1041           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1042       return true;
1043     }
1044 
1045     // Sixth argument is always passed as a pointer to clk_event_t.
1046     if (!Arg5->isNullPointerConstant(S.Context,
1047                                      Expr::NPC_ValueDependentIsNotNull) &&
1048         !(Arg5->getType()->isPointerType() &&
1049           Arg5->getType()->getPointeeType()->isClkEventT())) {
1050       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1051              diag::err_opencl_builtin_expected_type)
1052           << TheCall->getDirectCallee()
1053           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1054       return true;
1055     }
1056 
1057     if (NumArgs == 7)
1058       return false;
1059 
1060     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1061   }
1062 
1063   // None of the specific case has been detected, give generic error
1064   S.Diag(TheCall->getBeginLoc(),
1065          diag::err_opencl_enqueue_kernel_incorrect_args);
1066   return true;
1067 }
1068 
1069 /// Returns OpenCL access qual.
1070 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1071     return D->getAttr<OpenCLAccessAttr>();
1072 }
1073 
1074 /// Returns true if pipe element type is different from the pointer.
1075 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1076   const Expr *Arg0 = Call->getArg(0);
1077   // First argument type should always be pipe.
1078   if (!Arg0->getType()->isPipeType()) {
1079     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1080         << Call->getDirectCallee() << Arg0->getSourceRange();
1081     return true;
1082   }
1083   OpenCLAccessAttr *AccessQual =
1084       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1085   // Validates the access qualifier is compatible with the call.
1086   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1087   // read_only and write_only, and assumed to be read_only if no qualifier is
1088   // specified.
1089   switch (Call->getDirectCallee()->getBuiltinID()) {
1090   case Builtin::BIread_pipe:
1091   case Builtin::BIreserve_read_pipe:
1092   case Builtin::BIcommit_read_pipe:
1093   case Builtin::BIwork_group_reserve_read_pipe:
1094   case Builtin::BIsub_group_reserve_read_pipe:
1095   case Builtin::BIwork_group_commit_read_pipe:
1096   case Builtin::BIsub_group_commit_read_pipe:
1097     if (!(!AccessQual || AccessQual->isReadOnly())) {
1098       S.Diag(Arg0->getBeginLoc(),
1099              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1100           << "read_only" << Arg0->getSourceRange();
1101       return true;
1102     }
1103     break;
1104   case Builtin::BIwrite_pipe:
1105   case Builtin::BIreserve_write_pipe:
1106   case Builtin::BIcommit_write_pipe:
1107   case Builtin::BIwork_group_reserve_write_pipe:
1108   case Builtin::BIsub_group_reserve_write_pipe:
1109   case Builtin::BIwork_group_commit_write_pipe:
1110   case Builtin::BIsub_group_commit_write_pipe:
1111     if (!(AccessQual && AccessQual->isWriteOnly())) {
1112       S.Diag(Arg0->getBeginLoc(),
1113              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1114           << "write_only" << Arg0->getSourceRange();
1115       return true;
1116     }
1117     break;
1118   default:
1119     break;
1120   }
1121   return false;
1122 }
1123 
1124 /// Returns true if pipe element type is different from the pointer.
1125 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1126   const Expr *Arg0 = Call->getArg(0);
1127   const Expr *ArgIdx = Call->getArg(Idx);
1128   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1129   const QualType EltTy = PipeTy->getElementType();
1130   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1131   // The Idx argument should be a pointer and the type of the pointer and
1132   // the type of pipe element should also be the same.
1133   if (!ArgTy ||
1134       !S.Context.hasSameType(
1135           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1136     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1137         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1138         << ArgIdx->getType() << ArgIdx->getSourceRange();
1139     return true;
1140   }
1141   return false;
1142 }
1143 
1144 // Performs semantic analysis for the read/write_pipe call.
1145 // \param S Reference to the semantic analyzer.
1146 // \param Call A pointer to the builtin call.
1147 // \return True if a semantic error has been found, false otherwise.
1148 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1149   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1150   // functions have two forms.
1151   switch (Call->getNumArgs()) {
1152   case 2:
1153     if (checkOpenCLPipeArg(S, Call))
1154       return true;
1155     // The call with 2 arguments should be
1156     // read/write_pipe(pipe T, T*).
1157     // Check packet type T.
1158     if (checkOpenCLPipePacketType(S, Call, 1))
1159       return true;
1160     break;
1161 
1162   case 4: {
1163     if (checkOpenCLPipeArg(S, Call))
1164       return true;
1165     // The call with 4 arguments should be
1166     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1167     // Check reserve_id_t.
1168     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1169       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1170           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1171           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1172       return true;
1173     }
1174 
1175     // Check the index.
1176     const Expr *Arg2 = Call->getArg(2);
1177     if (!Arg2->getType()->isIntegerType() &&
1178         !Arg2->getType()->isUnsignedIntegerType()) {
1179       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1180           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1181           << Arg2->getType() << Arg2->getSourceRange();
1182       return true;
1183     }
1184 
1185     // Check packet type T.
1186     if (checkOpenCLPipePacketType(S, Call, 3))
1187       return true;
1188   } break;
1189   default:
1190     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1191         << Call->getDirectCallee() << Call->getSourceRange();
1192     return true;
1193   }
1194 
1195   return false;
1196 }
1197 
1198 // Performs a semantic analysis on the {work_group_/sub_group_
1199 //        /_}reserve_{read/write}_pipe
1200 // \param S Reference to the semantic analyzer.
1201 // \param Call The call to the builtin function to be analyzed.
1202 // \return True if a semantic error was found, false otherwise.
1203 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1204   if (checkArgCount(S, Call, 2))
1205     return true;
1206 
1207   if (checkOpenCLPipeArg(S, Call))
1208     return true;
1209 
1210   // Check the reserve size.
1211   if (!Call->getArg(1)->getType()->isIntegerType() &&
1212       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1213     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1214         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1215         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1216     return true;
1217   }
1218 
1219   // Since return type of reserve_read/write_pipe built-in function is
1220   // reserve_id_t, which is not defined in the builtin def file , we used int
1221   // as return type and need to override the return type of these functions.
1222   Call->setType(S.Context.OCLReserveIDTy);
1223 
1224   return false;
1225 }
1226 
1227 // Performs a semantic analysis on {work_group_/sub_group_
1228 //        /_}commit_{read/write}_pipe
1229 // \param S Reference to the semantic analyzer.
1230 // \param Call The call to the builtin function to be analyzed.
1231 // \return True if a semantic error was found, false otherwise.
1232 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1233   if (checkArgCount(S, Call, 2))
1234     return true;
1235 
1236   if (checkOpenCLPipeArg(S, Call))
1237     return true;
1238 
1239   // Check reserve_id_t.
1240   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1241     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1242         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1243         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1244     return true;
1245   }
1246 
1247   return false;
1248 }
1249 
1250 // Performs a semantic analysis on the call to built-in Pipe
1251 //        Query Functions.
1252 // \param S Reference to the semantic analyzer.
1253 // \param Call The call to the builtin function to be analyzed.
1254 // \return True if a semantic error was found, false otherwise.
1255 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1256   if (checkArgCount(S, Call, 1))
1257     return true;
1258 
1259   if (!Call->getArg(0)->getType()->isPipeType()) {
1260     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1261         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1262     return true;
1263   }
1264 
1265   return false;
1266 }
1267 
1268 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1269 // Performs semantic analysis for the to_global/local/private call.
1270 // \param S Reference to the semantic analyzer.
1271 // \param BuiltinID ID of the builtin function.
1272 // \param Call A pointer to the builtin call.
1273 // \return True if a semantic error has been found, false otherwise.
1274 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1275                                     CallExpr *Call) {
1276   if (Call->getNumArgs() != 1) {
1277     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
1278         << Call->getDirectCallee() << Call->getSourceRange();
1279     return true;
1280   }
1281 
1282   auto RT = Call->getArg(0)->getType();
1283   if (!RT->isPointerType() || RT->getPointeeType()
1284       .getAddressSpace() == LangAS::opencl_constant) {
1285     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1286         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1287     return true;
1288   }
1289 
1290   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1291     S.Diag(Call->getArg(0)->getBeginLoc(),
1292            diag::warn_opencl_generic_address_space_arg)
1293         << Call->getDirectCallee()->getNameInfo().getAsString()
1294         << Call->getArg(0)->getSourceRange();
1295   }
1296 
1297   RT = RT->getPointeeType();
1298   auto Qual = RT.getQualifiers();
1299   switch (BuiltinID) {
1300   case Builtin::BIto_global:
1301     Qual.setAddressSpace(LangAS::opencl_global);
1302     break;
1303   case Builtin::BIto_local:
1304     Qual.setAddressSpace(LangAS::opencl_local);
1305     break;
1306   case Builtin::BIto_private:
1307     Qual.setAddressSpace(LangAS::opencl_private);
1308     break;
1309   default:
1310     llvm_unreachable("Invalid builtin function");
1311   }
1312   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1313       RT.getUnqualifiedType(), Qual)));
1314 
1315   return false;
1316 }
1317 
1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1319   if (checkArgCount(S, TheCall, 1))
1320     return ExprError();
1321 
1322   // Compute __builtin_launder's parameter type from the argument.
1323   // The parameter type is:
1324   //  * The type of the argument if it's not an array or function type,
1325   //  Otherwise,
1326   //  * The decayed argument type.
1327   QualType ParamTy = [&]() {
1328     QualType ArgTy = TheCall->getArg(0)->getType();
1329     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1330       return S.Context.getPointerType(Ty->getElementType());
1331     if (ArgTy->isFunctionType()) {
1332       return S.Context.getPointerType(ArgTy);
1333     }
1334     return ArgTy;
1335   }();
1336 
1337   TheCall->setType(ParamTy);
1338 
1339   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1340     if (!ParamTy->isPointerType())
1341       return 0;
1342     if (ParamTy->isFunctionPointerType())
1343       return 1;
1344     if (ParamTy->isVoidPointerType())
1345       return 2;
1346     return llvm::Optional<unsigned>{};
1347   }();
1348   if (DiagSelect.hasValue()) {
1349     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1350         << DiagSelect.getValue() << TheCall->getSourceRange();
1351     return ExprError();
1352   }
1353 
1354   // We either have an incomplete class type, or we have a class template
1355   // whose instantiation has not been forced. Example:
1356   //
1357   //   template <class T> struct Foo { T value; };
1358   //   Foo<int> *p = nullptr;
1359   //   auto *d = __builtin_launder(p);
1360   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1361                             diag::err_incomplete_type))
1362     return ExprError();
1363 
1364   assert(ParamTy->getPointeeType()->isObjectType() &&
1365          "Unhandled non-object pointer case");
1366 
1367   InitializedEntity Entity =
1368       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1369   ExprResult Arg =
1370       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1371   if (Arg.isInvalid())
1372     return ExprError();
1373   TheCall->setArg(0, Arg.get());
1374 
1375   return TheCall;
1376 }
1377 
1378 // Emit an error and return true if the current architecture is not in the list
1379 // of supported architectures.
1380 static bool
1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1382                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1383   llvm::Triple::ArchType CurArch =
1384       S.getASTContext().getTargetInfo().getTriple().getArch();
1385   if (llvm::is_contained(SupportedArchs, CurArch))
1386     return false;
1387   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1388       << TheCall->getSourceRange();
1389   return true;
1390 }
1391 
1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1393                                  SourceLocation CallSiteLoc);
1394 
1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1396                                       CallExpr *TheCall) {
1397   switch (TI.getTriple().getArch()) {
1398   default:
1399     // Some builtins don't require additional checking, so just consider these
1400     // acceptable.
1401     return false;
1402   case llvm::Triple::arm:
1403   case llvm::Triple::armeb:
1404   case llvm::Triple::thumb:
1405   case llvm::Triple::thumbeb:
1406     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1407   case llvm::Triple::aarch64:
1408   case llvm::Triple::aarch64_32:
1409   case llvm::Triple::aarch64_be:
1410     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1411   case llvm::Triple::bpfeb:
1412   case llvm::Triple::bpfel:
1413     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1414   case llvm::Triple::hexagon:
1415     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1416   case llvm::Triple::mips:
1417   case llvm::Triple::mipsel:
1418   case llvm::Triple::mips64:
1419   case llvm::Triple::mips64el:
1420     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::systemz:
1422     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1423   case llvm::Triple::x86:
1424   case llvm::Triple::x86_64:
1425     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1426   case llvm::Triple::ppc:
1427   case llvm::Triple::ppc64:
1428   case llvm::Triple::ppc64le:
1429     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1430   case llvm::Triple::amdgcn:
1431     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1432   }
1433 }
1434 
1435 ExprResult
1436 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1437                                CallExpr *TheCall) {
1438   ExprResult TheCallResult(TheCall);
1439 
1440   // Find out if any arguments are required to be integer constant expressions.
1441   unsigned ICEArguments = 0;
1442   ASTContext::GetBuiltinTypeError Error;
1443   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1444   if (Error != ASTContext::GE_None)
1445     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1446 
1447   // If any arguments are required to be ICE's, check and diagnose.
1448   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1449     // Skip arguments not required to be ICE's.
1450     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1451 
1452     llvm::APSInt Result;
1453     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1454       return true;
1455     ICEArguments &= ~(1 << ArgNo);
1456   }
1457 
1458   switch (BuiltinID) {
1459   case Builtin::BI__builtin___CFStringMakeConstantString:
1460     assert(TheCall->getNumArgs() == 1 &&
1461            "Wrong # arguments to builtin CFStringMakeConstantString");
1462     if (CheckObjCString(TheCall->getArg(0)))
1463       return ExprError();
1464     break;
1465   case Builtin::BI__builtin_ms_va_start:
1466   case Builtin::BI__builtin_stdarg_start:
1467   case Builtin::BI__builtin_va_start:
1468     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1469       return ExprError();
1470     break;
1471   case Builtin::BI__va_start: {
1472     switch (Context.getTargetInfo().getTriple().getArch()) {
1473     case llvm::Triple::aarch64:
1474     case llvm::Triple::arm:
1475     case llvm::Triple::thumb:
1476       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1477         return ExprError();
1478       break;
1479     default:
1480       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1481         return ExprError();
1482       break;
1483     }
1484     break;
1485   }
1486 
1487   // The acquire, release, and no fence variants are ARM and AArch64 only.
1488   case Builtin::BI_interlockedbittestandset_acq:
1489   case Builtin::BI_interlockedbittestandset_rel:
1490   case Builtin::BI_interlockedbittestandset_nf:
1491   case Builtin::BI_interlockedbittestandreset_acq:
1492   case Builtin::BI_interlockedbittestandreset_rel:
1493   case Builtin::BI_interlockedbittestandreset_nf:
1494     if (CheckBuiltinTargetSupport(
1495             *this, BuiltinID, TheCall,
1496             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1497       return ExprError();
1498     break;
1499 
1500   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1501   case Builtin::BI_bittest64:
1502   case Builtin::BI_bittestandcomplement64:
1503   case Builtin::BI_bittestandreset64:
1504   case Builtin::BI_bittestandset64:
1505   case Builtin::BI_interlockedbittestandreset64:
1506   case Builtin::BI_interlockedbittestandset64:
1507     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1508                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1509                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1510       return ExprError();
1511     break;
1512 
1513   case Builtin::BI__builtin_isgreater:
1514   case Builtin::BI__builtin_isgreaterequal:
1515   case Builtin::BI__builtin_isless:
1516   case Builtin::BI__builtin_islessequal:
1517   case Builtin::BI__builtin_islessgreater:
1518   case Builtin::BI__builtin_isunordered:
1519     if (SemaBuiltinUnorderedCompare(TheCall))
1520       return ExprError();
1521     break;
1522   case Builtin::BI__builtin_fpclassify:
1523     if (SemaBuiltinFPClassification(TheCall, 6))
1524       return ExprError();
1525     break;
1526   case Builtin::BI__builtin_isfinite:
1527   case Builtin::BI__builtin_isinf:
1528   case Builtin::BI__builtin_isinf_sign:
1529   case Builtin::BI__builtin_isnan:
1530   case Builtin::BI__builtin_isnormal:
1531   case Builtin::BI__builtin_signbit:
1532   case Builtin::BI__builtin_signbitf:
1533   case Builtin::BI__builtin_signbitl:
1534     if (SemaBuiltinFPClassification(TheCall, 1))
1535       return ExprError();
1536     break;
1537   case Builtin::BI__builtin_shufflevector:
1538     return SemaBuiltinShuffleVector(TheCall);
1539     // TheCall will be freed by the smart pointer here, but that's fine, since
1540     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1541   case Builtin::BI__builtin_prefetch:
1542     if (SemaBuiltinPrefetch(TheCall))
1543       return ExprError();
1544     break;
1545   case Builtin::BI__builtin_alloca_with_align:
1546     if (SemaBuiltinAllocaWithAlign(TheCall))
1547       return ExprError();
1548     LLVM_FALLTHROUGH;
1549   case Builtin::BI__builtin_alloca:
1550     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1551         << TheCall->getDirectCallee();
1552     break;
1553   case Builtin::BI__assume:
1554   case Builtin::BI__builtin_assume:
1555     if (SemaBuiltinAssume(TheCall))
1556       return ExprError();
1557     break;
1558   case Builtin::BI__builtin_assume_aligned:
1559     if (SemaBuiltinAssumeAligned(TheCall))
1560       return ExprError();
1561     break;
1562   case Builtin::BI__builtin_dynamic_object_size:
1563   case Builtin::BI__builtin_object_size:
1564     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1565       return ExprError();
1566     break;
1567   case Builtin::BI__builtin_longjmp:
1568     if (SemaBuiltinLongjmp(TheCall))
1569       return ExprError();
1570     break;
1571   case Builtin::BI__builtin_setjmp:
1572     if (SemaBuiltinSetjmp(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI_setjmp:
1576   case Builtin::BI_setjmpex:
1577     if (checkArgCount(*this, TheCall, 1))
1578       return true;
1579     break;
1580   case Builtin::BI__builtin_classify_type:
1581     if (checkArgCount(*this, TheCall, 1)) return true;
1582     TheCall->setType(Context.IntTy);
1583     break;
1584   case Builtin::BI__builtin_constant_p: {
1585     if (checkArgCount(*this, TheCall, 1)) return true;
1586     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1587     if (Arg.isInvalid()) return true;
1588     TheCall->setArg(0, Arg.get());
1589     TheCall->setType(Context.IntTy);
1590     break;
1591   }
1592   case Builtin::BI__builtin_launder:
1593     return SemaBuiltinLaunder(*this, TheCall);
1594   case Builtin::BI__sync_fetch_and_add:
1595   case Builtin::BI__sync_fetch_and_add_1:
1596   case Builtin::BI__sync_fetch_and_add_2:
1597   case Builtin::BI__sync_fetch_and_add_4:
1598   case Builtin::BI__sync_fetch_and_add_8:
1599   case Builtin::BI__sync_fetch_and_add_16:
1600   case Builtin::BI__sync_fetch_and_sub:
1601   case Builtin::BI__sync_fetch_and_sub_1:
1602   case Builtin::BI__sync_fetch_and_sub_2:
1603   case Builtin::BI__sync_fetch_and_sub_4:
1604   case Builtin::BI__sync_fetch_and_sub_8:
1605   case Builtin::BI__sync_fetch_and_sub_16:
1606   case Builtin::BI__sync_fetch_and_or:
1607   case Builtin::BI__sync_fetch_and_or_1:
1608   case Builtin::BI__sync_fetch_and_or_2:
1609   case Builtin::BI__sync_fetch_and_or_4:
1610   case Builtin::BI__sync_fetch_and_or_8:
1611   case Builtin::BI__sync_fetch_and_or_16:
1612   case Builtin::BI__sync_fetch_and_and:
1613   case Builtin::BI__sync_fetch_and_and_1:
1614   case Builtin::BI__sync_fetch_and_and_2:
1615   case Builtin::BI__sync_fetch_and_and_4:
1616   case Builtin::BI__sync_fetch_and_and_8:
1617   case Builtin::BI__sync_fetch_and_and_16:
1618   case Builtin::BI__sync_fetch_and_xor:
1619   case Builtin::BI__sync_fetch_and_xor_1:
1620   case Builtin::BI__sync_fetch_and_xor_2:
1621   case Builtin::BI__sync_fetch_and_xor_4:
1622   case Builtin::BI__sync_fetch_and_xor_8:
1623   case Builtin::BI__sync_fetch_and_xor_16:
1624   case Builtin::BI__sync_fetch_and_nand:
1625   case Builtin::BI__sync_fetch_and_nand_1:
1626   case Builtin::BI__sync_fetch_and_nand_2:
1627   case Builtin::BI__sync_fetch_and_nand_4:
1628   case Builtin::BI__sync_fetch_and_nand_8:
1629   case Builtin::BI__sync_fetch_and_nand_16:
1630   case Builtin::BI__sync_add_and_fetch:
1631   case Builtin::BI__sync_add_and_fetch_1:
1632   case Builtin::BI__sync_add_and_fetch_2:
1633   case Builtin::BI__sync_add_and_fetch_4:
1634   case Builtin::BI__sync_add_and_fetch_8:
1635   case Builtin::BI__sync_add_and_fetch_16:
1636   case Builtin::BI__sync_sub_and_fetch:
1637   case Builtin::BI__sync_sub_and_fetch_1:
1638   case Builtin::BI__sync_sub_and_fetch_2:
1639   case Builtin::BI__sync_sub_and_fetch_4:
1640   case Builtin::BI__sync_sub_and_fetch_8:
1641   case Builtin::BI__sync_sub_and_fetch_16:
1642   case Builtin::BI__sync_and_and_fetch:
1643   case Builtin::BI__sync_and_and_fetch_1:
1644   case Builtin::BI__sync_and_and_fetch_2:
1645   case Builtin::BI__sync_and_and_fetch_4:
1646   case Builtin::BI__sync_and_and_fetch_8:
1647   case Builtin::BI__sync_and_and_fetch_16:
1648   case Builtin::BI__sync_or_and_fetch:
1649   case Builtin::BI__sync_or_and_fetch_1:
1650   case Builtin::BI__sync_or_and_fetch_2:
1651   case Builtin::BI__sync_or_and_fetch_4:
1652   case Builtin::BI__sync_or_and_fetch_8:
1653   case Builtin::BI__sync_or_and_fetch_16:
1654   case Builtin::BI__sync_xor_and_fetch:
1655   case Builtin::BI__sync_xor_and_fetch_1:
1656   case Builtin::BI__sync_xor_and_fetch_2:
1657   case Builtin::BI__sync_xor_and_fetch_4:
1658   case Builtin::BI__sync_xor_and_fetch_8:
1659   case Builtin::BI__sync_xor_and_fetch_16:
1660   case Builtin::BI__sync_nand_and_fetch:
1661   case Builtin::BI__sync_nand_and_fetch_1:
1662   case Builtin::BI__sync_nand_and_fetch_2:
1663   case Builtin::BI__sync_nand_and_fetch_4:
1664   case Builtin::BI__sync_nand_and_fetch_8:
1665   case Builtin::BI__sync_nand_and_fetch_16:
1666   case Builtin::BI__sync_val_compare_and_swap:
1667   case Builtin::BI__sync_val_compare_and_swap_1:
1668   case Builtin::BI__sync_val_compare_and_swap_2:
1669   case Builtin::BI__sync_val_compare_and_swap_4:
1670   case Builtin::BI__sync_val_compare_and_swap_8:
1671   case Builtin::BI__sync_val_compare_and_swap_16:
1672   case Builtin::BI__sync_bool_compare_and_swap:
1673   case Builtin::BI__sync_bool_compare_and_swap_1:
1674   case Builtin::BI__sync_bool_compare_and_swap_2:
1675   case Builtin::BI__sync_bool_compare_and_swap_4:
1676   case Builtin::BI__sync_bool_compare_and_swap_8:
1677   case Builtin::BI__sync_bool_compare_and_swap_16:
1678   case Builtin::BI__sync_lock_test_and_set:
1679   case Builtin::BI__sync_lock_test_and_set_1:
1680   case Builtin::BI__sync_lock_test_and_set_2:
1681   case Builtin::BI__sync_lock_test_and_set_4:
1682   case Builtin::BI__sync_lock_test_and_set_8:
1683   case Builtin::BI__sync_lock_test_and_set_16:
1684   case Builtin::BI__sync_lock_release:
1685   case Builtin::BI__sync_lock_release_1:
1686   case Builtin::BI__sync_lock_release_2:
1687   case Builtin::BI__sync_lock_release_4:
1688   case Builtin::BI__sync_lock_release_8:
1689   case Builtin::BI__sync_lock_release_16:
1690   case Builtin::BI__sync_swap:
1691   case Builtin::BI__sync_swap_1:
1692   case Builtin::BI__sync_swap_2:
1693   case Builtin::BI__sync_swap_4:
1694   case Builtin::BI__sync_swap_8:
1695   case Builtin::BI__sync_swap_16:
1696     return SemaBuiltinAtomicOverloaded(TheCallResult);
1697   case Builtin::BI__sync_synchronize:
1698     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1699         << TheCall->getCallee()->getSourceRange();
1700     break;
1701   case Builtin::BI__builtin_nontemporal_load:
1702   case Builtin::BI__builtin_nontemporal_store:
1703     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1704   case Builtin::BI__builtin_memcpy_inline: {
1705     clang::Expr *SizeOp = TheCall->getArg(2);
1706     // We warn about copying to or from `nullptr` pointers when `size` is
1707     // greater than 0. When `size` is value dependent we cannot evaluate its
1708     // value so we bail out.
1709     if (SizeOp->isValueDependent())
1710       break;
1711     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1712       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1713       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1714     }
1715     break;
1716   }
1717 #define BUILTIN(ID, TYPE, ATTRS)
1718 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1719   case Builtin::BI##ID: \
1720     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1721 #include "clang/Basic/Builtins.def"
1722   case Builtin::BI__annotation:
1723     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1724       return ExprError();
1725     break;
1726   case Builtin::BI__builtin_annotation:
1727     if (SemaBuiltinAnnotation(*this, TheCall))
1728       return ExprError();
1729     break;
1730   case Builtin::BI__builtin_addressof:
1731     if (SemaBuiltinAddressof(*this, TheCall))
1732       return ExprError();
1733     break;
1734   case Builtin::BI__builtin_is_aligned:
1735   case Builtin::BI__builtin_align_up:
1736   case Builtin::BI__builtin_align_down:
1737     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1738       return ExprError();
1739     break;
1740   case Builtin::BI__builtin_add_overflow:
1741   case Builtin::BI__builtin_sub_overflow:
1742   case Builtin::BI__builtin_mul_overflow:
1743     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1744       return ExprError();
1745     break;
1746   case Builtin::BI__builtin_operator_new:
1747   case Builtin::BI__builtin_operator_delete: {
1748     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1749     ExprResult Res =
1750         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1751     if (Res.isInvalid())
1752       CorrectDelayedTyposInExpr(TheCallResult.get());
1753     return Res;
1754   }
1755   case Builtin::BI__builtin_dump_struct: {
1756     // We first want to ensure we are called with 2 arguments
1757     if (checkArgCount(*this, TheCall, 2))
1758       return ExprError();
1759     // Ensure that the first argument is of type 'struct XX *'
1760     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1761     const QualType PtrArgType = PtrArg->getType();
1762     if (!PtrArgType->isPointerType() ||
1763         !PtrArgType->getPointeeType()->isRecordType()) {
1764       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1765           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1766           << "structure pointer";
1767       return ExprError();
1768     }
1769 
1770     // Ensure that the second argument is of type 'FunctionType'
1771     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1772     const QualType FnPtrArgType = FnPtrArg->getType();
1773     if (!FnPtrArgType->isPointerType()) {
1774       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1775           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1776           << FnPtrArgType << "'int (*)(const char *, ...)'";
1777       return ExprError();
1778     }
1779 
1780     const auto *FuncType =
1781         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1782 
1783     if (!FuncType) {
1784       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1785           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1786           << FnPtrArgType << "'int (*)(const char *, ...)'";
1787       return ExprError();
1788     }
1789 
1790     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1791       if (!FT->getNumParams()) {
1792         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1793             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1794             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1795         return ExprError();
1796       }
1797       QualType PT = FT->getParamType(0);
1798       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1799           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1800           !PT->getPointeeType().isConstQualified()) {
1801         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1802             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1803             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1804         return ExprError();
1805       }
1806     }
1807 
1808     TheCall->setType(Context.IntTy);
1809     break;
1810   }
1811   case Builtin::BI__builtin_expect_with_probability: {
1812     // We first want to ensure we are called with 3 arguments
1813     if (checkArgCount(*this, TheCall, 3))
1814       return ExprError();
1815     // then check probability is constant float in range [0.0, 1.0]
1816     const Expr *ProbArg = TheCall->getArg(2);
1817     SmallVector<PartialDiagnosticAt, 8> Notes;
1818     Expr::EvalResult Eval;
1819     Eval.Diag = &Notes;
1820     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
1821                                           Context)) ||
1822         !Eval.Val.isFloat()) {
1823       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1824           << ProbArg->getSourceRange();
1825       for (const PartialDiagnosticAt &PDiag : Notes)
1826         Diag(PDiag.first, PDiag.second);
1827       return ExprError();
1828     }
1829     llvm::APFloat Probability = Eval.Val.getFloat();
1830     bool LoseInfo = false;
1831     Probability.convert(llvm::APFloat::IEEEdouble(),
1832                         llvm::RoundingMode::Dynamic, &LoseInfo);
1833     if (!(Probability >= llvm::APFloat(0.0) &&
1834           Probability <= llvm::APFloat(1.0))) {
1835       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1836           << ProbArg->getSourceRange();
1837       return ExprError();
1838     }
1839     break;
1840   }
1841   case Builtin::BI__builtin_preserve_access_index:
1842     if (SemaBuiltinPreserveAI(*this, TheCall))
1843       return ExprError();
1844     break;
1845   case Builtin::BI__builtin_call_with_static_chain:
1846     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1847       return ExprError();
1848     break;
1849   case Builtin::BI__exception_code:
1850   case Builtin::BI_exception_code:
1851     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1852                                  diag::err_seh___except_block))
1853       return ExprError();
1854     break;
1855   case Builtin::BI__exception_info:
1856   case Builtin::BI_exception_info:
1857     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1858                                  diag::err_seh___except_filter))
1859       return ExprError();
1860     break;
1861   case Builtin::BI__GetExceptionInfo:
1862     if (checkArgCount(*this, TheCall, 1))
1863       return ExprError();
1864 
1865     if (CheckCXXThrowOperand(
1866             TheCall->getBeginLoc(),
1867             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1868             TheCall))
1869       return ExprError();
1870 
1871     TheCall->setType(Context.VoidPtrTy);
1872     break;
1873   // OpenCL v2.0, s6.13.16 - Pipe functions
1874   case Builtin::BIread_pipe:
1875   case Builtin::BIwrite_pipe:
1876     // Since those two functions are declared with var args, we need a semantic
1877     // check for the argument.
1878     if (SemaBuiltinRWPipe(*this, TheCall))
1879       return ExprError();
1880     break;
1881   case Builtin::BIreserve_read_pipe:
1882   case Builtin::BIreserve_write_pipe:
1883   case Builtin::BIwork_group_reserve_read_pipe:
1884   case Builtin::BIwork_group_reserve_write_pipe:
1885     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1886       return ExprError();
1887     break;
1888   case Builtin::BIsub_group_reserve_read_pipe:
1889   case Builtin::BIsub_group_reserve_write_pipe:
1890     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1891         SemaBuiltinReserveRWPipe(*this, TheCall))
1892       return ExprError();
1893     break;
1894   case Builtin::BIcommit_read_pipe:
1895   case Builtin::BIcommit_write_pipe:
1896   case Builtin::BIwork_group_commit_read_pipe:
1897   case Builtin::BIwork_group_commit_write_pipe:
1898     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1899       return ExprError();
1900     break;
1901   case Builtin::BIsub_group_commit_read_pipe:
1902   case Builtin::BIsub_group_commit_write_pipe:
1903     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1904         SemaBuiltinCommitRWPipe(*this, TheCall))
1905       return ExprError();
1906     break;
1907   case Builtin::BIget_pipe_num_packets:
1908   case Builtin::BIget_pipe_max_packets:
1909     if (SemaBuiltinPipePackets(*this, TheCall))
1910       return ExprError();
1911     break;
1912   case Builtin::BIto_global:
1913   case Builtin::BIto_local:
1914   case Builtin::BIto_private:
1915     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1916       return ExprError();
1917     break;
1918   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1919   case Builtin::BIenqueue_kernel:
1920     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1921       return ExprError();
1922     break;
1923   case Builtin::BIget_kernel_work_group_size:
1924   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1925     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1926       return ExprError();
1927     break;
1928   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1929   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1930     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1931       return ExprError();
1932     break;
1933   case Builtin::BI__builtin_os_log_format:
1934     Cleanup.setExprNeedsCleanups(true);
1935     LLVM_FALLTHROUGH;
1936   case Builtin::BI__builtin_os_log_format_buffer_size:
1937     if (SemaBuiltinOSLogFormat(TheCall))
1938       return ExprError();
1939     break;
1940   case Builtin::BI__builtin_frame_address:
1941   case Builtin::BI__builtin_return_address: {
1942     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1943       return ExprError();
1944 
1945     // -Wframe-address warning if non-zero passed to builtin
1946     // return/frame address.
1947     Expr::EvalResult Result;
1948     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1949         Result.Val.getInt() != 0)
1950       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1951           << ((BuiltinID == Builtin::BI__builtin_return_address)
1952                   ? "__builtin_return_address"
1953                   : "__builtin_frame_address")
1954           << TheCall->getSourceRange();
1955     break;
1956   }
1957 
1958   case Builtin::BI__builtin_matrix_transpose:
1959     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1960 
1961   case Builtin::BI__builtin_matrix_column_major_load:
1962     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1963 
1964   case Builtin::BI__builtin_matrix_column_major_store:
1965     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1966   }
1967 
1968   // Since the target specific builtins for each arch overlap, only check those
1969   // of the arch we are compiling for.
1970   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1971     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1972       assert(Context.getAuxTargetInfo() &&
1973              "Aux Target Builtin, but not an aux target?");
1974 
1975       if (CheckTSBuiltinFunctionCall(
1976               *Context.getAuxTargetInfo(),
1977               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1978         return ExprError();
1979     } else {
1980       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1981                                      TheCall))
1982         return ExprError();
1983     }
1984   }
1985 
1986   return TheCallResult;
1987 }
1988 
1989 // Get the valid immediate range for the specified NEON type code.
1990 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1991   NeonTypeFlags Type(t);
1992   int IsQuad = ForceQuad ? true : Type.isQuad();
1993   switch (Type.getEltType()) {
1994   case NeonTypeFlags::Int8:
1995   case NeonTypeFlags::Poly8:
1996     return shift ? 7 : (8 << IsQuad) - 1;
1997   case NeonTypeFlags::Int16:
1998   case NeonTypeFlags::Poly16:
1999     return shift ? 15 : (4 << IsQuad) - 1;
2000   case NeonTypeFlags::Int32:
2001     return shift ? 31 : (2 << IsQuad) - 1;
2002   case NeonTypeFlags::Int64:
2003   case NeonTypeFlags::Poly64:
2004     return shift ? 63 : (1 << IsQuad) - 1;
2005   case NeonTypeFlags::Poly128:
2006     return shift ? 127 : (1 << IsQuad) - 1;
2007   case NeonTypeFlags::Float16:
2008     assert(!shift && "cannot shift float types!");
2009     return (4 << IsQuad) - 1;
2010   case NeonTypeFlags::Float32:
2011     assert(!shift && "cannot shift float types!");
2012     return (2 << IsQuad) - 1;
2013   case NeonTypeFlags::Float64:
2014     assert(!shift && "cannot shift float types!");
2015     return (1 << IsQuad) - 1;
2016   case NeonTypeFlags::BFloat16:
2017     assert(!shift && "cannot shift float types!");
2018     return (4 << IsQuad) - 1;
2019   }
2020   llvm_unreachable("Invalid NeonTypeFlag!");
2021 }
2022 
2023 /// getNeonEltType - Return the QualType corresponding to the elements of
2024 /// the vector type specified by the NeonTypeFlags.  This is used to check
2025 /// the pointer arguments for Neon load/store intrinsics.
2026 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2027                                bool IsPolyUnsigned, bool IsInt64Long) {
2028   switch (Flags.getEltType()) {
2029   case NeonTypeFlags::Int8:
2030     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2031   case NeonTypeFlags::Int16:
2032     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2033   case NeonTypeFlags::Int32:
2034     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2035   case NeonTypeFlags::Int64:
2036     if (IsInt64Long)
2037       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2038     else
2039       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2040                                 : Context.LongLongTy;
2041   case NeonTypeFlags::Poly8:
2042     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2043   case NeonTypeFlags::Poly16:
2044     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2045   case NeonTypeFlags::Poly64:
2046     if (IsInt64Long)
2047       return Context.UnsignedLongTy;
2048     else
2049       return Context.UnsignedLongLongTy;
2050   case NeonTypeFlags::Poly128:
2051     break;
2052   case NeonTypeFlags::Float16:
2053     return Context.HalfTy;
2054   case NeonTypeFlags::Float32:
2055     return Context.FloatTy;
2056   case NeonTypeFlags::Float64:
2057     return Context.DoubleTy;
2058   case NeonTypeFlags::BFloat16:
2059     return Context.BFloat16Ty;
2060   }
2061   llvm_unreachable("Invalid NeonTypeFlag!");
2062 }
2063 
2064 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2065   // Range check SVE intrinsics that take immediate values.
2066   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2067 
2068   switch (BuiltinID) {
2069   default:
2070     return false;
2071 #define GET_SVE_IMMEDIATE_CHECK
2072 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2073 #undef GET_SVE_IMMEDIATE_CHECK
2074   }
2075 
2076   // Perform all the immediate checks for this builtin call.
2077   bool HasError = false;
2078   for (auto &I : ImmChecks) {
2079     int ArgNum, CheckTy, ElementSizeInBits;
2080     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2081 
2082     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2083 
2084     // Function that checks whether the operand (ArgNum) is an immediate
2085     // that is one of the predefined values.
2086     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2087                                    int ErrDiag) -> bool {
2088       // We can't check the value of a dependent argument.
2089       Expr *Arg = TheCall->getArg(ArgNum);
2090       if (Arg->isTypeDependent() || Arg->isValueDependent())
2091         return false;
2092 
2093       // Check constant-ness first.
2094       llvm::APSInt Imm;
2095       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2096         return true;
2097 
2098       if (!CheckImm(Imm.getSExtValue()))
2099         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2100       return false;
2101     };
2102 
2103     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2104     case SVETypeFlags::ImmCheck0_31:
2105       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2106         HasError = true;
2107       break;
2108     case SVETypeFlags::ImmCheck0_13:
2109       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2110         HasError = true;
2111       break;
2112     case SVETypeFlags::ImmCheck1_16:
2113       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2114         HasError = true;
2115       break;
2116     case SVETypeFlags::ImmCheck0_7:
2117       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2118         HasError = true;
2119       break;
2120     case SVETypeFlags::ImmCheckExtract:
2121       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2122                                       (2048 / ElementSizeInBits) - 1))
2123         HasError = true;
2124       break;
2125     case SVETypeFlags::ImmCheckShiftRight:
2126       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2127         HasError = true;
2128       break;
2129     case SVETypeFlags::ImmCheckShiftRightNarrow:
2130       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2131                                       ElementSizeInBits / 2))
2132         HasError = true;
2133       break;
2134     case SVETypeFlags::ImmCheckShiftLeft:
2135       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2136                                       ElementSizeInBits - 1))
2137         HasError = true;
2138       break;
2139     case SVETypeFlags::ImmCheckLaneIndex:
2140       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2141                                       (128 / (1 * ElementSizeInBits)) - 1))
2142         HasError = true;
2143       break;
2144     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2145       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2146                                       (128 / (2 * ElementSizeInBits)) - 1))
2147         HasError = true;
2148       break;
2149     case SVETypeFlags::ImmCheckLaneIndexDot:
2150       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2151                                       (128 / (4 * ElementSizeInBits)) - 1))
2152         HasError = true;
2153       break;
2154     case SVETypeFlags::ImmCheckComplexRot90_270:
2155       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2156                               diag::err_rotation_argument_to_cadd))
2157         HasError = true;
2158       break;
2159     case SVETypeFlags::ImmCheckComplexRotAll90:
2160       if (CheckImmediateInSet(
2161               [](int64_t V) {
2162                 return V == 0 || V == 90 || V == 180 || V == 270;
2163               },
2164               diag::err_rotation_argument_to_cmla))
2165         HasError = true;
2166       break;
2167     case SVETypeFlags::ImmCheck0_1:
2168       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2169         HasError = true;
2170       break;
2171     case SVETypeFlags::ImmCheck0_2:
2172       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2173         HasError = true;
2174       break;
2175     case SVETypeFlags::ImmCheck0_3:
2176       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2177         HasError = true;
2178       break;
2179     }
2180   }
2181 
2182   return HasError;
2183 }
2184 
2185 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2186                                         unsigned BuiltinID, CallExpr *TheCall) {
2187   llvm::APSInt Result;
2188   uint64_t mask = 0;
2189   unsigned TV = 0;
2190   int PtrArgNum = -1;
2191   bool HasConstPtr = false;
2192   switch (BuiltinID) {
2193 #define GET_NEON_OVERLOAD_CHECK
2194 #include "clang/Basic/arm_neon.inc"
2195 #include "clang/Basic/arm_fp16.inc"
2196 #undef GET_NEON_OVERLOAD_CHECK
2197   }
2198 
2199   // For NEON intrinsics which are overloaded on vector element type, validate
2200   // the immediate which specifies which variant to emit.
2201   unsigned ImmArg = TheCall->getNumArgs()-1;
2202   if (mask) {
2203     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2204       return true;
2205 
2206     TV = Result.getLimitedValue(64);
2207     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2208       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2209              << TheCall->getArg(ImmArg)->getSourceRange();
2210   }
2211 
2212   if (PtrArgNum >= 0) {
2213     // Check that pointer arguments have the specified type.
2214     Expr *Arg = TheCall->getArg(PtrArgNum);
2215     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2216       Arg = ICE->getSubExpr();
2217     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2218     QualType RHSTy = RHS.get()->getType();
2219 
2220     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2221     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2222                           Arch == llvm::Triple::aarch64_32 ||
2223                           Arch == llvm::Triple::aarch64_be;
2224     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2225     QualType EltTy =
2226         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2227     if (HasConstPtr)
2228       EltTy = EltTy.withConst();
2229     QualType LHSTy = Context.getPointerType(EltTy);
2230     AssignConvertType ConvTy;
2231     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2232     if (RHS.isInvalid())
2233       return true;
2234     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2235                                  RHS.get(), AA_Assigning))
2236       return true;
2237   }
2238 
2239   // For NEON intrinsics which take an immediate value as part of the
2240   // instruction, range check them here.
2241   unsigned i = 0, l = 0, u = 0;
2242   switch (BuiltinID) {
2243   default:
2244     return false;
2245   #define GET_NEON_IMMEDIATE_CHECK
2246   #include "clang/Basic/arm_neon.inc"
2247   #include "clang/Basic/arm_fp16.inc"
2248   #undef GET_NEON_IMMEDIATE_CHECK
2249   }
2250 
2251   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2252 }
2253 
2254 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2255   switch (BuiltinID) {
2256   default:
2257     return false;
2258   #include "clang/Basic/arm_mve_builtin_sema.inc"
2259   }
2260 }
2261 
2262 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2263                                        CallExpr *TheCall) {
2264   bool Err = false;
2265   switch (BuiltinID) {
2266   default:
2267     return false;
2268 #include "clang/Basic/arm_cde_builtin_sema.inc"
2269   }
2270 
2271   if (Err)
2272     return true;
2273 
2274   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2275 }
2276 
2277 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2278                                         const Expr *CoprocArg, bool WantCDE) {
2279   if (isConstantEvaluated())
2280     return false;
2281 
2282   // We can't check the value of a dependent argument.
2283   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2284     return false;
2285 
2286   llvm::APSInt CoprocNoAP;
2287   bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context);
2288   (void)IsICE;
2289   assert(IsICE && "Coprocossor immediate is not a constant expression");
2290   int64_t CoprocNo = CoprocNoAP.getExtValue();
2291   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2292 
2293   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2294   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2295 
2296   if (IsCDECoproc != WantCDE)
2297     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2298            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2299 
2300   return false;
2301 }
2302 
2303 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2304                                         unsigned MaxWidth) {
2305   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2306           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2307           BuiltinID == ARM::BI__builtin_arm_strex ||
2308           BuiltinID == ARM::BI__builtin_arm_stlex ||
2309           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2310           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2311           BuiltinID == AArch64::BI__builtin_arm_strex ||
2312           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2313          "unexpected ARM builtin");
2314   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2315                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2316                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2317                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2318 
2319   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2320 
2321   // Ensure that we have the proper number of arguments.
2322   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2323     return true;
2324 
2325   // Inspect the pointer argument of the atomic builtin.  This should always be
2326   // a pointer type, whose element is an integral scalar or pointer type.
2327   // Because it is a pointer type, we don't have to worry about any implicit
2328   // casts here.
2329   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2330   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2331   if (PointerArgRes.isInvalid())
2332     return true;
2333   PointerArg = PointerArgRes.get();
2334 
2335   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2336   if (!pointerType) {
2337     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2338         << PointerArg->getType() << PointerArg->getSourceRange();
2339     return true;
2340   }
2341 
2342   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2343   // task is to insert the appropriate casts into the AST. First work out just
2344   // what the appropriate type is.
2345   QualType ValType = pointerType->getPointeeType();
2346   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2347   if (IsLdrex)
2348     AddrType.addConst();
2349 
2350   // Issue a warning if the cast is dodgy.
2351   CastKind CastNeeded = CK_NoOp;
2352   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2353     CastNeeded = CK_BitCast;
2354     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2355         << PointerArg->getType() << Context.getPointerType(AddrType)
2356         << AA_Passing << PointerArg->getSourceRange();
2357   }
2358 
2359   // Finally, do the cast and replace the argument with the corrected version.
2360   AddrType = Context.getPointerType(AddrType);
2361   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2362   if (PointerArgRes.isInvalid())
2363     return true;
2364   PointerArg = PointerArgRes.get();
2365 
2366   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2367 
2368   // In general, we allow ints, floats and pointers to be loaded and stored.
2369   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2370       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2371     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2372         << PointerArg->getType() << PointerArg->getSourceRange();
2373     return true;
2374   }
2375 
2376   // But ARM doesn't have instructions to deal with 128-bit versions.
2377   if (Context.getTypeSize(ValType) > MaxWidth) {
2378     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2379     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2380         << PointerArg->getType() << PointerArg->getSourceRange();
2381     return true;
2382   }
2383 
2384   switch (ValType.getObjCLifetime()) {
2385   case Qualifiers::OCL_None:
2386   case Qualifiers::OCL_ExplicitNone:
2387     // okay
2388     break;
2389 
2390   case Qualifiers::OCL_Weak:
2391   case Qualifiers::OCL_Strong:
2392   case Qualifiers::OCL_Autoreleasing:
2393     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2394         << ValType << PointerArg->getSourceRange();
2395     return true;
2396   }
2397 
2398   if (IsLdrex) {
2399     TheCall->setType(ValType);
2400     return false;
2401   }
2402 
2403   // Initialize the argument to be stored.
2404   ExprResult ValArg = TheCall->getArg(0);
2405   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2406       Context, ValType, /*consume*/ false);
2407   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2408   if (ValArg.isInvalid())
2409     return true;
2410   TheCall->setArg(0, ValArg.get());
2411 
2412   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2413   // but the custom checker bypasses all default analysis.
2414   TheCall->setType(Context.IntTy);
2415   return false;
2416 }
2417 
2418 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2419                                        CallExpr *TheCall) {
2420   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2421       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2422       BuiltinID == ARM::BI__builtin_arm_strex ||
2423       BuiltinID == ARM::BI__builtin_arm_stlex) {
2424     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2425   }
2426 
2427   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2428     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2429       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2430   }
2431 
2432   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2433       BuiltinID == ARM::BI__builtin_arm_wsr64)
2434     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2435 
2436   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2437       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2438       BuiltinID == ARM::BI__builtin_arm_wsr ||
2439       BuiltinID == ARM::BI__builtin_arm_wsrp)
2440     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2441 
2442   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2443     return true;
2444   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2445     return true;
2446   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2447     return true;
2448 
2449   // For intrinsics which take an immediate value as part of the instruction,
2450   // range check them here.
2451   // FIXME: VFP Intrinsics should error if VFP not present.
2452   switch (BuiltinID) {
2453   default: return false;
2454   case ARM::BI__builtin_arm_ssat:
2455     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2456   case ARM::BI__builtin_arm_usat:
2457     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2458   case ARM::BI__builtin_arm_ssat16:
2459     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2460   case ARM::BI__builtin_arm_usat16:
2461     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2462   case ARM::BI__builtin_arm_vcvtr_f:
2463   case ARM::BI__builtin_arm_vcvtr_d:
2464     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2465   case ARM::BI__builtin_arm_dmb:
2466   case ARM::BI__builtin_arm_dsb:
2467   case ARM::BI__builtin_arm_isb:
2468   case ARM::BI__builtin_arm_dbg:
2469     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2470   case ARM::BI__builtin_arm_cdp:
2471   case ARM::BI__builtin_arm_cdp2:
2472   case ARM::BI__builtin_arm_mcr:
2473   case ARM::BI__builtin_arm_mcr2:
2474   case ARM::BI__builtin_arm_mrc:
2475   case ARM::BI__builtin_arm_mrc2:
2476   case ARM::BI__builtin_arm_mcrr:
2477   case ARM::BI__builtin_arm_mcrr2:
2478   case ARM::BI__builtin_arm_mrrc:
2479   case ARM::BI__builtin_arm_mrrc2:
2480   case ARM::BI__builtin_arm_ldc:
2481   case ARM::BI__builtin_arm_ldcl:
2482   case ARM::BI__builtin_arm_ldc2:
2483   case ARM::BI__builtin_arm_ldc2l:
2484   case ARM::BI__builtin_arm_stc:
2485   case ARM::BI__builtin_arm_stcl:
2486   case ARM::BI__builtin_arm_stc2:
2487   case ARM::BI__builtin_arm_stc2l:
2488     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2489            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2490                                         /*WantCDE*/ false);
2491   }
2492 }
2493 
2494 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2495                                            unsigned BuiltinID,
2496                                            CallExpr *TheCall) {
2497   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2498       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2499       BuiltinID == AArch64::BI__builtin_arm_strex ||
2500       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2501     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2502   }
2503 
2504   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2505     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2506       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2507       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2508       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2509   }
2510 
2511   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2512       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2513     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2514 
2515   // Memory Tagging Extensions (MTE) Intrinsics
2516   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2517       BuiltinID == AArch64::BI__builtin_arm_addg ||
2518       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2519       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2520       BuiltinID == AArch64::BI__builtin_arm_stg ||
2521       BuiltinID == AArch64::BI__builtin_arm_subp) {
2522     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2523   }
2524 
2525   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2526       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2527       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2528       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2529     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2530 
2531   // Only check the valid encoding range. Any constant in this range would be
2532   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2533   // an exception for incorrect registers. This matches MSVC behavior.
2534   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2535       BuiltinID == AArch64::BI_WriteStatusReg)
2536     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2537 
2538   if (BuiltinID == AArch64::BI__getReg)
2539     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2540 
2541   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2542     return true;
2543 
2544   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2545     return true;
2546 
2547   // For intrinsics which take an immediate value as part of the instruction,
2548   // range check them here.
2549   unsigned i = 0, l = 0, u = 0;
2550   switch (BuiltinID) {
2551   default: return false;
2552   case AArch64::BI__builtin_arm_dmb:
2553   case AArch64::BI__builtin_arm_dsb:
2554   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2555   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2556   }
2557 
2558   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2559 }
2560 
2561 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2562                                        CallExpr *TheCall) {
2563   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2564           BuiltinID == BPF::BI__builtin_btf_type_id) &&
2565          "unexpected ARM builtin");
2566 
2567   if (checkArgCount(*this, TheCall, 2))
2568     return true;
2569 
2570   Expr *Arg;
2571   if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2572     // The second argument needs to be a constant int
2573     llvm::APSInt Value;
2574     Arg = TheCall->getArg(1);
2575     if (!Arg->isIntegerConstantExpr(Value, Context)) {
2576       Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const)
2577           << 2 << Arg->getSourceRange();
2578       return true;
2579     }
2580 
2581     TheCall->setType(Context.UnsignedIntTy);
2582     return false;
2583   }
2584 
2585   // The first argument needs to be a record field access.
2586   // If it is an array element access, we delay decision
2587   // to BPF backend to check whether the access is a
2588   // field access or not.
2589   Arg = TheCall->getArg(0);
2590   if (Arg->getType()->getAsPlaceholderType() ||
2591       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2592        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2593        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2594     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2595         << 1 << Arg->getSourceRange();
2596     return true;
2597   }
2598 
2599   // The second argument needs to be a constant int
2600   Arg = TheCall->getArg(1);
2601   llvm::APSInt Value;
2602   if (!Arg->isIntegerConstantExpr(Value, Context)) {
2603     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2604         << 2 << Arg->getSourceRange();
2605     return true;
2606   }
2607 
2608   TheCall->setType(Context.UnsignedIntTy);
2609   return false;
2610 }
2611 
2612 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2613   struct ArgInfo {
2614     uint8_t OpNum;
2615     bool IsSigned;
2616     uint8_t BitWidth;
2617     uint8_t Align;
2618   };
2619   struct BuiltinInfo {
2620     unsigned BuiltinID;
2621     ArgInfo Infos[2];
2622   };
2623 
2624   static BuiltinInfo Infos[] = {
2625     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2626     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2627     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2628     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2629     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2630     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2631     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2632     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2633     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2634     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2635     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2636 
2637     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2638     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2639     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2640     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2641     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2642     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2643     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2644     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2645     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2646     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2647     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2648 
2649     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2650     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2651     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2652     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2653     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2654     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2655     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2656     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2657     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2658     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2659     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2660     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2661     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2662     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2663     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2664     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2665     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2666     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2667     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2668     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2669     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2670     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2671     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2672     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2673     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2674     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2675     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2676     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2677     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2678     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2679     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2680     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2681     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2682     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2683     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2684     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2685     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2686     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2687     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2688     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2690     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2691     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2692     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2693     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2695     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2696     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2697     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2698     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2699     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2700     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2701                                                       {{ 1, false, 6,  0 }} },
2702     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2703     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2706     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2709                                                       {{ 1, false, 5,  0 }} },
2710     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2711     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2712     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2713     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2714     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2715     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2716                                                        { 2, false, 5,  0 }} },
2717     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2718                                                        { 2, false, 6,  0 }} },
2719     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2720                                                        { 3, false, 5,  0 }} },
2721     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2722                                                        { 3, false, 6,  0 }} },
2723     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2724     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2725     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2726     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2727     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2728     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2729     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2730     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2731     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2732     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2733     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2734     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2735     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2736     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2737     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2738     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2739                                                       {{ 2, false, 4,  0 },
2740                                                        { 3, false, 5,  0 }} },
2741     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2742                                                       {{ 2, false, 4,  0 },
2743                                                        { 3, false, 5,  0 }} },
2744     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2745                                                       {{ 2, false, 4,  0 },
2746                                                        { 3, false, 5,  0 }} },
2747     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2748                                                       {{ 2, false, 4,  0 },
2749                                                        { 3, false, 5,  0 }} },
2750     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2751     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2752     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2753     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2754     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2755     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2756     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2757     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2759     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2760     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2761                                                        { 2, false, 5,  0 }} },
2762     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2763                                                        { 2, false, 6,  0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2773                                                       {{ 1, false, 4,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2776                                                       {{ 1, false, 4,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2797                                                       {{ 3, false, 1,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2802                                                       {{ 3, false, 1,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2807                                                       {{ 3, false, 1,  0 }} },
2808   };
2809 
2810   // Use a dynamically initialized static to sort the table exactly once on
2811   // first run.
2812   static const bool SortOnce =
2813       (llvm::sort(Infos,
2814                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2815                    return LHS.BuiltinID < RHS.BuiltinID;
2816                  }),
2817        true);
2818   (void)SortOnce;
2819 
2820   const BuiltinInfo *F = llvm::partition_point(
2821       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2822   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2823     return false;
2824 
2825   bool Error = false;
2826 
2827   for (const ArgInfo &A : F->Infos) {
2828     // Ignore empty ArgInfo elements.
2829     if (A.BitWidth == 0)
2830       continue;
2831 
2832     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2833     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2834     if (!A.Align) {
2835       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2836     } else {
2837       unsigned M = 1 << A.Align;
2838       Min *= M;
2839       Max *= M;
2840       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2841                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2842     }
2843   }
2844   return Error;
2845 }
2846 
2847 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2848                                            CallExpr *TheCall) {
2849   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2850 }
2851 
2852 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2853                                         unsigned BuiltinID, CallExpr *TheCall) {
2854   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2855          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2856 }
2857 
2858 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2859                                CallExpr *TheCall) {
2860 
2861   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2862       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2863     if (!TI.hasFeature("dsp"))
2864       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2865   }
2866 
2867   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2868       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2869     if (!TI.hasFeature("dspr2"))
2870       return Diag(TheCall->getBeginLoc(),
2871                   diag::err_mips_builtin_requires_dspr2);
2872   }
2873 
2874   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2875       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2876     if (!TI.hasFeature("msa"))
2877       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2878   }
2879 
2880   return false;
2881 }
2882 
2883 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2884 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2885 // ordering for DSP is unspecified. MSA is ordered by the data format used
2886 // by the underlying instruction i.e., df/m, df/n and then by size.
2887 //
2888 // FIXME: The size tests here should instead be tablegen'd along with the
2889 //        definitions from include/clang/Basic/BuiltinsMips.def.
2890 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2891 //        be too.
2892 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2893   unsigned i = 0, l = 0, u = 0, m = 0;
2894   switch (BuiltinID) {
2895   default: return false;
2896   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2897   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2898   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2899   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2900   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2901   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2902   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2903   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2904   // df/m field.
2905   // These intrinsics take an unsigned 3 bit immediate.
2906   case Mips::BI__builtin_msa_bclri_b:
2907   case Mips::BI__builtin_msa_bnegi_b:
2908   case Mips::BI__builtin_msa_bseti_b:
2909   case Mips::BI__builtin_msa_sat_s_b:
2910   case Mips::BI__builtin_msa_sat_u_b:
2911   case Mips::BI__builtin_msa_slli_b:
2912   case Mips::BI__builtin_msa_srai_b:
2913   case Mips::BI__builtin_msa_srari_b:
2914   case Mips::BI__builtin_msa_srli_b:
2915   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2916   case Mips::BI__builtin_msa_binsli_b:
2917   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2918   // These intrinsics take an unsigned 4 bit immediate.
2919   case Mips::BI__builtin_msa_bclri_h:
2920   case Mips::BI__builtin_msa_bnegi_h:
2921   case Mips::BI__builtin_msa_bseti_h:
2922   case Mips::BI__builtin_msa_sat_s_h:
2923   case Mips::BI__builtin_msa_sat_u_h:
2924   case Mips::BI__builtin_msa_slli_h:
2925   case Mips::BI__builtin_msa_srai_h:
2926   case Mips::BI__builtin_msa_srari_h:
2927   case Mips::BI__builtin_msa_srli_h:
2928   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2929   case Mips::BI__builtin_msa_binsli_h:
2930   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2931   // These intrinsics take an unsigned 5 bit immediate.
2932   // The first block of intrinsics actually have an unsigned 5 bit field,
2933   // not a df/n field.
2934   case Mips::BI__builtin_msa_cfcmsa:
2935   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2936   case Mips::BI__builtin_msa_clei_u_b:
2937   case Mips::BI__builtin_msa_clei_u_h:
2938   case Mips::BI__builtin_msa_clei_u_w:
2939   case Mips::BI__builtin_msa_clei_u_d:
2940   case Mips::BI__builtin_msa_clti_u_b:
2941   case Mips::BI__builtin_msa_clti_u_h:
2942   case Mips::BI__builtin_msa_clti_u_w:
2943   case Mips::BI__builtin_msa_clti_u_d:
2944   case Mips::BI__builtin_msa_maxi_u_b:
2945   case Mips::BI__builtin_msa_maxi_u_h:
2946   case Mips::BI__builtin_msa_maxi_u_w:
2947   case Mips::BI__builtin_msa_maxi_u_d:
2948   case Mips::BI__builtin_msa_mini_u_b:
2949   case Mips::BI__builtin_msa_mini_u_h:
2950   case Mips::BI__builtin_msa_mini_u_w:
2951   case Mips::BI__builtin_msa_mini_u_d:
2952   case Mips::BI__builtin_msa_addvi_b:
2953   case Mips::BI__builtin_msa_addvi_h:
2954   case Mips::BI__builtin_msa_addvi_w:
2955   case Mips::BI__builtin_msa_addvi_d:
2956   case Mips::BI__builtin_msa_bclri_w:
2957   case Mips::BI__builtin_msa_bnegi_w:
2958   case Mips::BI__builtin_msa_bseti_w:
2959   case Mips::BI__builtin_msa_sat_s_w:
2960   case Mips::BI__builtin_msa_sat_u_w:
2961   case Mips::BI__builtin_msa_slli_w:
2962   case Mips::BI__builtin_msa_srai_w:
2963   case Mips::BI__builtin_msa_srari_w:
2964   case Mips::BI__builtin_msa_srli_w:
2965   case Mips::BI__builtin_msa_srlri_w:
2966   case Mips::BI__builtin_msa_subvi_b:
2967   case Mips::BI__builtin_msa_subvi_h:
2968   case Mips::BI__builtin_msa_subvi_w:
2969   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2970   case Mips::BI__builtin_msa_binsli_w:
2971   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2972   // These intrinsics take an unsigned 6 bit immediate.
2973   case Mips::BI__builtin_msa_bclri_d:
2974   case Mips::BI__builtin_msa_bnegi_d:
2975   case Mips::BI__builtin_msa_bseti_d:
2976   case Mips::BI__builtin_msa_sat_s_d:
2977   case Mips::BI__builtin_msa_sat_u_d:
2978   case Mips::BI__builtin_msa_slli_d:
2979   case Mips::BI__builtin_msa_srai_d:
2980   case Mips::BI__builtin_msa_srari_d:
2981   case Mips::BI__builtin_msa_srli_d:
2982   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2983   case Mips::BI__builtin_msa_binsli_d:
2984   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2985   // These intrinsics take a signed 5 bit immediate.
2986   case Mips::BI__builtin_msa_ceqi_b:
2987   case Mips::BI__builtin_msa_ceqi_h:
2988   case Mips::BI__builtin_msa_ceqi_w:
2989   case Mips::BI__builtin_msa_ceqi_d:
2990   case Mips::BI__builtin_msa_clti_s_b:
2991   case Mips::BI__builtin_msa_clti_s_h:
2992   case Mips::BI__builtin_msa_clti_s_w:
2993   case Mips::BI__builtin_msa_clti_s_d:
2994   case Mips::BI__builtin_msa_clei_s_b:
2995   case Mips::BI__builtin_msa_clei_s_h:
2996   case Mips::BI__builtin_msa_clei_s_w:
2997   case Mips::BI__builtin_msa_clei_s_d:
2998   case Mips::BI__builtin_msa_maxi_s_b:
2999   case Mips::BI__builtin_msa_maxi_s_h:
3000   case Mips::BI__builtin_msa_maxi_s_w:
3001   case Mips::BI__builtin_msa_maxi_s_d:
3002   case Mips::BI__builtin_msa_mini_s_b:
3003   case Mips::BI__builtin_msa_mini_s_h:
3004   case Mips::BI__builtin_msa_mini_s_w:
3005   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3006   // These intrinsics take an unsigned 8 bit immediate.
3007   case Mips::BI__builtin_msa_andi_b:
3008   case Mips::BI__builtin_msa_nori_b:
3009   case Mips::BI__builtin_msa_ori_b:
3010   case Mips::BI__builtin_msa_shf_b:
3011   case Mips::BI__builtin_msa_shf_h:
3012   case Mips::BI__builtin_msa_shf_w:
3013   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3014   case Mips::BI__builtin_msa_bseli_b:
3015   case Mips::BI__builtin_msa_bmnzi_b:
3016   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3017   // df/n format
3018   // These intrinsics take an unsigned 4 bit immediate.
3019   case Mips::BI__builtin_msa_copy_s_b:
3020   case Mips::BI__builtin_msa_copy_u_b:
3021   case Mips::BI__builtin_msa_insve_b:
3022   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3023   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3024   // These intrinsics take an unsigned 3 bit immediate.
3025   case Mips::BI__builtin_msa_copy_s_h:
3026   case Mips::BI__builtin_msa_copy_u_h:
3027   case Mips::BI__builtin_msa_insve_h:
3028   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3029   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3030   // These intrinsics take an unsigned 2 bit immediate.
3031   case Mips::BI__builtin_msa_copy_s_w:
3032   case Mips::BI__builtin_msa_copy_u_w:
3033   case Mips::BI__builtin_msa_insve_w:
3034   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3035   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3036   // These intrinsics take an unsigned 1 bit immediate.
3037   case Mips::BI__builtin_msa_copy_s_d:
3038   case Mips::BI__builtin_msa_copy_u_d:
3039   case Mips::BI__builtin_msa_insve_d:
3040   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3041   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3042   // Memory offsets and immediate loads.
3043   // These intrinsics take a signed 10 bit immediate.
3044   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3045   case Mips::BI__builtin_msa_ldi_h:
3046   case Mips::BI__builtin_msa_ldi_w:
3047   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3048   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3049   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3050   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3051   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3052   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3053   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3054   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3055   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3056   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3057   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3058   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3059   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3060   }
3061 
3062   if (!m)
3063     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3064 
3065   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3066          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3067 }
3068 
3069 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3070                                        CallExpr *TheCall) {
3071   unsigned i = 0, l = 0, u = 0;
3072   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3073                       BuiltinID == PPC::BI__builtin_divdeu ||
3074                       BuiltinID == PPC::BI__builtin_bpermd;
3075   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3076   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3077                        BuiltinID == PPC::BI__builtin_divweu ||
3078                        BuiltinID == PPC::BI__builtin_divde ||
3079                        BuiltinID == PPC::BI__builtin_divdeu;
3080 
3081   if (Is64BitBltin && !IsTarget64Bit)
3082     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3083            << TheCall->getSourceRange();
3084 
3085   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3086       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3087     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3088            << TheCall->getSourceRange();
3089 
3090   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3091     if (!TI.hasFeature("vsx"))
3092       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3093              << TheCall->getSourceRange();
3094     return false;
3095   };
3096 
3097   switch (BuiltinID) {
3098   default: return false;
3099   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3100   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3101     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3102            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3103   case PPC::BI__builtin_altivec_dss:
3104     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3105   case PPC::BI__builtin_tbegin:
3106   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3107   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3108   case PPC::BI__builtin_tabortwc:
3109   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3110   case PPC::BI__builtin_tabortwci:
3111   case PPC::BI__builtin_tabortdci:
3112     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3113            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3114   case PPC::BI__builtin_altivec_dst:
3115   case PPC::BI__builtin_altivec_dstt:
3116   case PPC::BI__builtin_altivec_dstst:
3117   case PPC::BI__builtin_altivec_dststt:
3118     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3119   case PPC::BI__builtin_vsx_xxpermdi:
3120   case PPC::BI__builtin_vsx_xxsldwi:
3121     return SemaBuiltinVSX(TheCall);
3122   case PPC::BI__builtin_unpack_vector_int128:
3123     return SemaVSXCheck(TheCall) ||
3124            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3125   case PPC::BI__builtin_pack_vector_int128:
3126     return SemaVSXCheck(TheCall);
3127   }
3128   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3129 }
3130 
3131 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3132                                           CallExpr *TheCall) {
3133   // position of memory order and scope arguments in the builtin
3134   unsigned OrderIndex, ScopeIndex;
3135   switch (BuiltinID) {
3136   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3137   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3138   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3139   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3140     OrderIndex = 2;
3141     ScopeIndex = 3;
3142     break;
3143   case AMDGPU::BI__builtin_amdgcn_fence:
3144     OrderIndex = 0;
3145     ScopeIndex = 1;
3146     break;
3147   default:
3148     return false;
3149   }
3150 
3151   ExprResult Arg = TheCall->getArg(OrderIndex);
3152   auto ArgExpr = Arg.get();
3153   Expr::EvalResult ArgResult;
3154 
3155   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3156     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3157            << ArgExpr->getType();
3158   int ord = ArgResult.Val.getInt().getZExtValue();
3159 
3160   // Check valididty of memory ordering as per C11 / C++11's memody model.
3161   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3162   case llvm::AtomicOrderingCABI::acquire:
3163   case llvm::AtomicOrderingCABI::release:
3164   case llvm::AtomicOrderingCABI::acq_rel:
3165   case llvm::AtomicOrderingCABI::seq_cst:
3166     break;
3167   default: {
3168     return Diag(ArgExpr->getBeginLoc(),
3169                 diag::warn_atomic_op_has_invalid_memory_order)
3170            << ArgExpr->getSourceRange();
3171   }
3172   }
3173 
3174   Arg = TheCall->getArg(ScopeIndex);
3175   ArgExpr = Arg.get();
3176   Expr::EvalResult ArgResult1;
3177   // Check that sync scope is a constant literal
3178   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen,
3179                                        Context))
3180     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3181            << ArgExpr->getType();
3182 
3183   return false;
3184 }
3185 
3186 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3187                                            CallExpr *TheCall) {
3188   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3189     Expr *Arg = TheCall->getArg(0);
3190     llvm::APSInt AbortCode(32);
3191     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3192         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3193       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3194              << Arg->getSourceRange();
3195   }
3196 
3197   // For intrinsics which take an immediate value as part of the instruction,
3198   // range check them here.
3199   unsigned i = 0, l = 0, u = 0;
3200   switch (BuiltinID) {
3201   default: return false;
3202   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3203   case SystemZ::BI__builtin_s390_verimb:
3204   case SystemZ::BI__builtin_s390_verimh:
3205   case SystemZ::BI__builtin_s390_verimf:
3206   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3207   case SystemZ::BI__builtin_s390_vfaeb:
3208   case SystemZ::BI__builtin_s390_vfaeh:
3209   case SystemZ::BI__builtin_s390_vfaef:
3210   case SystemZ::BI__builtin_s390_vfaebs:
3211   case SystemZ::BI__builtin_s390_vfaehs:
3212   case SystemZ::BI__builtin_s390_vfaefs:
3213   case SystemZ::BI__builtin_s390_vfaezb:
3214   case SystemZ::BI__builtin_s390_vfaezh:
3215   case SystemZ::BI__builtin_s390_vfaezf:
3216   case SystemZ::BI__builtin_s390_vfaezbs:
3217   case SystemZ::BI__builtin_s390_vfaezhs:
3218   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3219   case SystemZ::BI__builtin_s390_vfisb:
3220   case SystemZ::BI__builtin_s390_vfidb:
3221     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3222            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3223   case SystemZ::BI__builtin_s390_vftcisb:
3224   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3225   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3226   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3227   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3228   case SystemZ::BI__builtin_s390_vstrcb:
3229   case SystemZ::BI__builtin_s390_vstrch:
3230   case SystemZ::BI__builtin_s390_vstrcf:
3231   case SystemZ::BI__builtin_s390_vstrczb:
3232   case SystemZ::BI__builtin_s390_vstrczh:
3233   case SystemZ::BI__builtin_s390_vstrczf:
3234   case SystemZ::BI__builtin_s390_vstrcbs:
3235   case SystemZ::BI__builtin_s390_vstrchs:
3236   case SystemZ::BI__builtin_s390_vstrcfs:
3237   case SystemZ::BI__builtin_s390_vstrczbs:
3238   case SystemZ::BI__builtin_s390_vstrczhs:
3239   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3240   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3241   case SystemZ::BI__builtin_s390_vfminsb:
3242   case SystemZ::BI__builtin_s390_vfmaxsb:
3243   case SystemZ::BI__builtin_s390_vfmindb:
3244   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3245   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3246   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3247   }
3248   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3249 }
3250 
3251 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3252 /// This checks that the target supports __builtin_cpu_supports and
3253 /// that the string argument is constant and valid.
3254 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3255                                    CallExpr *TheCall) {
3256   Expr *Arg = TheCall->getArg(0);
3257 
3258   // Check if the argument is a string literal.
3259   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3260     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3261            << Arg->getSourceRange();
3262 
3263   // Check the contents of the string.
3264   StringRef Feature =
3265       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3266   if (!TI.validateCpuSupports(Feature))
3267     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3268            << Arg->getSourceRange();
3269   return false;
3270 }
3271 
3272 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3273 /// This checks that the target supports __builtin_cpu_is and
3274 /// that the string argument is constant and valid.
3275 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3276   Expr *Arg = TheCall->getArg(0);
3277 
3278   // Check if the argument is a string literal.
3279   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3280     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3281            << Arg->getSourceRange();
3282 
3283   // Check the contents of the string.
3284   StringRef Feature =
3285       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3286   if (!TI.validateCpuIs(Feature))
3287     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3288            << Arg->getSourceRange();
3289   return false;
3290 }
3291 
3292 // Check if the rounding mode is legal.
3293 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3294   // Indicates if this instruction has rounding control or just SAE.
3295   bool HasRC = false;
3296 
3297   unsigned ArgNum = 0;
3298   switch (BuiltinID) {
3299   default:
3300     return false;
3301   case X86::BI__builtin_ia32_vcvttsd2si32:
3302   case X86::BI__builtin_ia32_vcvttsd2si64:
3303   case X86::BI__builtin_ia32_vcvttsd2usi32:
3304   case X86::BI__builtin_ia32_vcvttsd2usi64:
3305   case X86::BI__builtin_ia32_vcvttss2si32:
3306   case X86::BI__builtin_ia32_vcvttss2si64:
3307   case X86::BI__builtin_ia32_vcvttss2usi32:
3308   case X86::BI__builtin_ia32_vcvttss2usi64:
3309     ArgNum = 1;
3310     break;
3311   case X86::BI__builtin_ia32_maxpd512:
3312   case X86::BI__builtin_ia32_maxps512:
3313   case X86::BI__builtin_ia32_minpd512:
3314   case X86::BI__builtin_ia32_minps512:
3315     ArgNum = 2;
3316     break;
3317   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3318   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3319   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3320   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3321   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3322   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3323   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3324   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3325   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3326   case X86::BI__builtin_ia32_exp2pd_mask:
3327   case X86::BI__builtin_ia32_exp2ps_mask:
3328   case X86::BI__builtin_ia32_getexppd512_mask:
3329   case X86::BI__builtin_ia32_getexpps512_mask:
3330   case X86::BI__builtin_ia32_rcp28pd_mask:
3331   case X86::BI__builtin_ia32_rcp28ps_mask:
3332   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3333   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3334   case X86::BI__builtin_ia32_vcomisd:
3335   case X86::BI__builtin_ia32_vcomiss:
3336   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3337     ArgNum = 3;
3338     break;
3339   case X86::BI__builtin_ia32_cmppd512_mask:
3340   case X86::BI__builtin_ia32_cmpps512_mask:
3341   case X86::BI__builtin_ia32_cmpsd_mask:
3342   case X86::BI__builtin_ia32_cmpss_mask:
3343   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3344   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3345   case X86::BI__builtin_ia32_getexpss128_round_mask:
3346   case X86::BI__builtin_ia32_getmantpd512_mask:
3347   case X86::BI__builtin_ia32_getmantps512_mask:
3348   case X86::BI__builtin_ia32_maxsd_round_mask:
3349   case X86::BI__builtin_ia32_maxss_round_mask:
3350   case X86::BI__builtin_ia32_minsd_round_mask:
3351   case X86::BI__builtin_ia32_minss_round_mask:
3352   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3353   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3354   case X86::BI__builtin_ia32_reducepd512_mask:
3355   case X86::BI__builtin_ia32_reduceps512_mask:
3356   case X86::BI__builtin_ia32_rndscalepd_mask:
3357   case X86::BI__builtin_ia32_rndscaleps_mask:
3358   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3359   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3360     ArgNum = 4;
3361     break;
3362   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3363   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3364   case X86::BI__builtin_ia32_fixupimmps512_mask:
3365   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3366   case X86::BI__builtin_ia32_fixupimmsd_mask:
3367   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3368   case X86::BI__builtin_ia32_fixupimmss_mask:
3369   case X86::BI__builtin_ia32_fixupimmss_maskz:
3370   case X86::BI__builtin_ia32_getmantsd_round_mask:
3371   case X86::BI__builtin_ia32_getmantss_round_mask:
3372   case X86::BI__builtin_ia32_rangepd512_mask:
3373   case X86::BI__builtin_ia32_rangeps512_mask:
3374   case X86::BI__builtin_ia32_rangesd128_round_mask:
3375   case X86::BI__builtin_ia32_rangess128_round_mask:
3376   case X86::BI__builtin_ia32_reducesd_mask:
3377   case X86::BI__builtin_ia32_reducess_mask:
3378   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3379   case X86::BI__builtin_ia32_rndscaless_round_mask:
3380     ArgNum = 5;
3381     break;
3382   case X86::BI__builtin_ia32_vcvtsd2si64:
3383   case X86::BI__builtin_ia32_vcvtsd2si32:
3384   case X86::BI__builtin_ia32_vcvtsd2usi32:
3385   case X86::BI__builtin_ia32_vcvtsd2usi64:
3386   case X86::BI__builtin_ia32_vcvtss2si32:
3387   case X86::BI__builtin_ia32_vcvtss2si64:
3388   case X86::BI__builtin_ia32_vcvtss2usi32:
3389   case X86::BI__builtin_ia32_vcvtss2usi64:
3390   case X86::BI__builtin_ia32_sqrtpd512:
3391   case X86::BI__builtin_ia32_sqrtps512:
3392     ArgNum = 1;
3393     HasRC = true;
3394     break;
3395   case X86::BI__builtin_ia32_addpd512:
3396   case X86::BI__builtin_ia32_addps512:
3397   case X86::BI__builtin_ia32_divpd512:
3398   case X86::BI__builtin_ia32_divps512:
3399   case X86::BI__builtin_ia32_mulpd512:
3400   case X86::BI__builtin_ia32_mulps512:
3401   case X86::BI__builtin_ia32_subpd512:
3402   case X86::BI__builtin_ia32_subps512:
3403   case X86::BI__builtin_ia32_cvtsi2sd64:
3404   case X86::BI__builtin_ia32_cvtsi2ss32:
3405   case X86::BI__builtin_ia32_cvtsi2ss64:
3406   case X86::BI__builtin_ia32_cvtusi2sd64:
3407   case X86::BI__builtin_ia32_cvtusi2ss32:
3408   case X86::BI__builtin_ia32_cvtusi2ss64:
3409     ArgNum = 2;
3410     HasRC = true;
3411     break;
3412   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3413   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3414   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3415   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3416   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3417   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3418   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3419   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3420   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3421   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3422   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3423   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3424   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3425   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3426   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3427     ArgNum = 3;
3428     HasRC = true;
3429     break;
3430   case X86::BI__builtin_ia32_addss_round_mask:
3431   case X86::BI__builtin_ia32_addsd_round_mask:
3432   case X86::BI__builtin_ia32_divss_round_mask:
3433   case X86::BI__builtin_ia32_divsd_round_mask:
3434   case X86::BI__builtin_ia32_mulss_round_mask:
3435   case X86::BI__builtin_ia32_mulsd_round_mask:
3436   case X86::BI__builtin_ia32_subss_round_mask:
3437   case X86::BI__builtin_ia32_subsd_round_mask:
3438   case X86::BI__builtin_ia32_scalefpd512_mask:
3439   case X86::BI__builtin_ia32_scalefps512_mask:
3440   case X86::BI__builtin_ia32_scalefsd_round_mask:
3441   case X86::BI__builtin_ia32_scalefss_round_mask:
3442   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3443   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3444   case X86::BI__builtin_ia32_sqrtss_round_mask:
3445   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3446   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3447   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3448   case X86::BI__builtin_ia32_vfmaddss3_mask:
3449   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3450   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3451   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3452   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3453   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3454   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3455   case X86::BI__builtin_ia32_vfmaddps512_mask:
3456   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3457   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3458   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3459   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3460   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3461   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3462   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3463   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3464   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3465   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3466   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3467     ArgNum = 4;
3468     HasRC = true;
3469     break;
3470   }
3471 
3472   llvm::APSInt Result;
3473 
3474   // We can't check the value of a dependent argument.
3475   Expr *Arg = TheCall->getArg(ArgNum);
3476   if (Arg->isTypeDependent() || Arg->isValueDependent())
3477     return false;
3478 
3479   // Check constant-ness first.
3480   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3481     return true;
3482 
3483   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3484   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3485   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3486   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3487   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3488       Result == 8/*ROUND_NO_EXC*/ ||
3489       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3490       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3491     return false;
3492 
3493   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3494          << Arg->getSourceRange();
3495 }
3496 
3497 // Check if the gather/scatter scale is legal.
3498 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3499                                              CallExpr *TheCall) {
3500   unsigned ArgNum = 0;
3501   switch (BuiltinID) {
3502   default:
3503     return false;
3504   case X86::BI__builtin_ia32_gatherpfdpd:
3505   case X86::BI__builtin_ia32_gatherpfdps:
3506   case X86::BI__builtin_ia32_gatherpfqpd:
3507   case X86::BI__builtin_ia32_gatherpfqps:
3508   case X86::BI__builtin_ia32_scatterpfdpd:
3509   case X86::BI__builtin_ia32_scatterpfdps:
3510   case X86::BI__builtin_ia32_scatterpfqpd:
3511   case X86::BI__builtin_ia32_scatterpfqps:
3512     ArgNum = 3;
3513     break;
3514   case X86::BI__builtin_ia32_gatherd_pd:
3515   case X86::BI__builtin_ia32_gatherd_pd256:
3516   case X86::BI__builtin_ia32_gatherq_pd:
3517   case X86::BI__builtin_ia32_gatherq_pd256:
3518   case X86::BI__builtin_ia32_gatherd_ps:
3519   case X86::BI__builtin_ia32_gatherd_ps256:
3520   case X86::BI__builtin_ia32_gatherq_ps:
3521   case X86::BI__builtin_ia32_gatherq_ps256:
3522   case X86::BI__builtin_ia32_gatherd_q:
3523   case X86::BI__builtin_ia32_gatherd_q256:
3524   case X86::BI__builtin_ia32_gatherq_q:
3525   case X86::BI__builtin_ia32_gatherq_q256:
3526   case X86::BI__builtin_ia32_gatherd_d:
3527   case X86::BI__builtin_ia32_gatherd_d256:
3528   case X86::BI__builtin_ia32_gatherq_d:
3529   case X86::BI__builtin_ia32_gatherq_d256:
3530   case X86::BI__builtin_ia32_gather3div2df:
3531   case X86::BI__builtin_ia32_gather3div2di:
3532   case X86::BI__builtin_ia32_gather3div4df:
3533   case X86::BI__builtin_ia32_gather3div4di:
3534   case X86::BI__builtin_ia32_gather3div4sf:
3535   case X86::BI__builtin_ia32_gather3div4si:
3536   case X86::BI__builtin_ia32_gather3div8sf:
3537   case X86::BI__builtin_ia32_gather3div8si:
3538   case X86::BI__builtin_ia32_gather3siv2df:
3539   case X86::BI__builtin_ia32_gather3siv2di:
3540   case X86::BI__builtin_ia32_gather3siv4df:
3541   case X86::BI__builtin_ia32_gather3siv4di:
3542   case X86::BI__builtin_ia32_gather3siv4sf:
3543   case X86::BI__builtin_ia32_gather3siv4si:
3544   case X86::BI__builtin_ia32_gather3siv8sf:
3545   case X86::BI__builtin_ia32_gather3siv8si:
3546   case X86::BI__builtin_ia32_gathersiv8df:
3547   case X86::BI__builtin_ia32_gathersiv16sf:
3548   case X86::BI__builtin_ia32_gatherdiv8df:
3549   case X86::BI__builtin_ia32_gatherdiv16sf:
3550   case X86::BI__builtin_ia32_gathersiv8di:
3551   case X86::BI__builtin_ia32_gathersiv16si:
3552   case X86::BI__builtin_ia32_gatherdiv8di:
3553   case X86::BI__builtin_ia32_gatherdiv16si:
3554   case X86::BI__builtin_ia32_scatterdiv2df:
3555   case X86::BI__builtin_ia32_scatterdiv2di:
3556   case X86::BI__builtin_ia32_scatterdiv4df:
3557   case X86::BI__builtin_ia32_scatterdiv4di:
3558   case X86::BI__builtin_ia32_scatterdiv4sf:
3559   case X86::BI__builtin_ia32_scatterdiv4si:
3560   case X86::BI__builtin_ia32_scatterdiv8sf:
3561   case X86::BI__builtin_ia32_scatterdiv8si:
3562   case X86::BI__builtin_ia32_scattersiv2df:
3563   case X86::BI__builtin_ia32_scattersiv2di:
3564   case X86::BI__builtin_ia32_scattersiv4df:
3565   case X86::BI__builtin_ia32_scattersiv4di:
3566   case X86::BI__builtin_ia32_scattersiv4sf:
3567   case X86::BI__builtin_ia32_scattersiv4si:
3568   case X86::BI__builtin_ia32_scattersiv8sf:
3569   case X86::BI__builtin_ia32_scattersiv8si:
3570   case X86::BI__builtin_ia32_scattersiv8df:
3571   case X86::BI__builtin_ia32_scattersiv16sf:
3572   case X86::BI__builtin_ia32_scatterdiv8df:
3573   case X86::BI__builtin_ia32_scatterdiv16sf:
3574   case X86::BI__builtin_ia32_scattersiv8di:
3575   case X86::BI__builtin_ia32_scattersiv16si:
3576   case X86::BI__builtin_ia32_scatterdiv8di:
3577   case X86::BI__builtin_ia32_scatterdiv16si:
3578     ArgNum = 4;
3579     break;
3580   }
3581 
3582   llvm::APSInt Result;
3583 
3584   // We can't check the value of a dependent argument.
3585   Expr *Arg = TheCall->getArg(ArgNum);
3586   if (Arg->isTypeDependent() || Arg->isValueDependent())
3587     return false;
3588 
3589   // Check constant-ness first.
3590   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3591     return true;
3592 
3593   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3594     return false;
3595 
3596   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3597          << Arg->getSourceRange();
3598 }
3599 
3600 static bool isX86_32Builtin(unsigned BuiltinID) {
3601   // These builtins only work on x86-32 targets.
3602   switch (BuiltinID) {
3603   case X86::BI__builtin_ia32_readeflags_u32:
3604   case X86::BI__builtin_ia32_writeeflags_u32:
3605     return true;
3606   }
3607 
3608   return false;
3609 }
3610 
3611 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3612                                        CallExpr *TheCall) {
3613   if (BuiltinID == X86::BI__builtin_cpu_supports)
3614     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3615 
3616   if (BuiltinID == X86::BI__builtin_cpu_is)
3617     return SemaBuiltinCpuIs(*this, TI, TheCall);
3618 
3619   // Check for 32-bit only builtins on a 64-bit target.
3620   const llvm::Triple &TT = TI.getTriple();
3621   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3622     return Diag(TheCall->getCallee()->getBeginLoc(),
3623                 diag::err_32_bit_builtin_64_bit_tgt);
3624 
3625   // If the intrinsic has rounding or SAE make sure its valid.
3626   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3627     return true;
3628 
3629   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3630   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3631     return true;
3632 
3633   // For intrinsics which take an immediate value as part of the instruction,
3634   // range check them here.
3635   int i = 0, l = 0, u = 0;
3636   switch (BuiltinID) {
3637   default:
3638     return false;
3639   case X86::BI__builtin_ia32_vec_ext_v2si:
3640   case X86::BI__builtin_ia32_vec_ext_v2di:
3641   case X86::BI__builtin_ia32_vextractf128_pd256:
3642   case X86::BI__builtin_ia32_vextractf128_ps256:
3643   case X86::BI__builtin_ia32_vextractf128_si256:
3644   case X86::BI__builtin_ia32_extract128i256:
3645   case X86::BI__builtin_ia32_extractf64x4_mask:
3646   case X86::BI__builtin_ia32_extracti64x4_mask:
3647   case X86::BI__builtin_ia32_extractf32x8_mask:
3648   case X86::BI__builtin_ia32_extracti32x8_mask:
3649   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3650   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3651   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3652   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3653     i = 1; l = 0; u = 1;
3654     break;
3655   case X86::BI__builtin_ia32_vec_set_v2di:
3656   case X86::BI__builtin_ia32_vinsertf128_pd256:
3657   case X86::BI__builtin_ia32_vinsertf128_ps256:
3658   case X86::BI__builtin_ia32_vinsertf128_si256:
3659   case X86::BI__builtin_ia32_insert128i256:
3660   case X86::BI__builtin_ia32_insertf32x8:
3661   case X86::BI__builtin_ia32_inserti32x8:
3662   case X86::BI__builtin_ia32_insertf64x4:
3663   case X86::BI__builtin_ia32_inserti64x4:
3664   case X86::BI__builtin_ia32_insertf64x2_256:
3665   case X86::BI__builtin_ia32_inserti64x2_256:
3666   case X86::BI__builtin_ia32_insertf32x4_256:
3667   case X86::BI__builtin_ia32_inserti32x4_256:
3668     i = 2; l = 0; u = 1;
3669     break;
3670   case X86::BI__builtin_ia32_vpermilpd:
3671   case X86::BI__builtin_ia32_vec_ext_v4hi:
3672   case X86::BI__builtin_ia32_vec_ext_v4si:
3673   case X86::BI__builtin_ia32_vec_ext_v4sf:
3674   case X86::BI__builtin_ia32_vec_ext_v4di:
3675   case X86::BI__builtin_ia32_extractf32x4_mask:
3676   case X86::BI__builtin_ia32_extracti32x4_mask:
3677   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3678   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3679     i = 1; l = 0; u = 3;
3680     break;
3681   case X86::BI_mm_prefetch:
3682   case X86::BI__builtin_ia32_vec_ext_v8hi:
3683   case X86::BI__builtin_ia32_vec_ext_v8si:
3684     i = 1; l = 0; u = 7;
3685     break;
3686   case X86::BI__builtin_ia32_sha1rnds4:
3687   case X86::BI__builtin_ia32_blendpd:
3688   case X86::BI__builtin_ia32_shufpd:
3689   case X86::BI__builtin_ia32_vec_set_v4hi:
3690   case X86::BI__builtin_ia32_vec_set_v4si:
3691   case X86::BI__builtin_ia32_vec_set_v4di:
3692   case X86::BI__builtin_ia32_shuf_f32x4_256:
3693   case X86::BI__builtin_ia32_shuf_f64x2_256:
3694   case X86::BI__builtin_ia32_shuf_i32x4_256:
3695   case X86::BI__builtin_ia32_shuf_i64x2_256:
3696   case X86::BI__builtin_ia32_insertf64x2_512:
3697   case X86::BI__builtin_ia32_inserti64x2_512:
3698   case X86::BI__builtin_ia32_insertf32x4:
3699   case X86::BI__builtin_ia32_inserti32x4:
3700     i = 2; l = 0; u = 3;
3701     break;
3702   case X86::BI__builtin_ia32_vpermil2pd:
3703   case X86::BI__builtin_ia32_vpermil2pd256:
3704   case X86::BI__builtin_ia32_vpermil2ps:
3705   case X86::BI__builtin_ia32_vpermil2ps256:
3706     i = 3; l = 0; u = 3;
3707     break;
3708   case X86::BI__builtin_ia32_cmpb128_mask:
3709   case X86::BI__builtin_ia32_cmpw128_mask:
3710   case X86::BI__builtin_ia32_cmpd128_mask:
3711   case X86::BI__builtin_ia32_cmpq128_mask:
3712   case X86::BI__builtin_ia32_cmpb256_mask:
3713   case X86::BI__builtin_ia32_cmpw256_mask:
3714   case X86::BI__builtin_ia32_cmpd256_mask:
3715   case X86::BI__builtin_ia32_cmpq256_mask:
3716   case X86::BI__builtin_ia32_cmpb512_mask:
3717   case X86::BI__builtin_ia32_cmpw512_mask:
3718   case X86::BI__builtin_ia32_cmpd512_mask:
3719   case X86::BI__builtin_ia32_cmpq512_mask:
3720   case X86::BI__builtin_ia32_ucmpb128_mask:
3721   case X86::BI__builtin_ia32_ucmpw128_mask:
3722   case X86::BI__builtin_ia32_ucmpd128_mask:
3723   case X86::BI__builtin_ia32_ucmpq128_mask:
3724   case X86::BI__builtin_ia32_ucmpb256_mask:
3725   case X86::BI__builtin_ia32_ucmpw256_mask:
3726   case X86::BI__builtin_ia32_ucmpd256_mask:
3727   case X86::BI__builtin_ia32_ucmpq256_mask:
3728   case X86::BI__builtin_ia32_ucmpb512_mask:
3729   case X86::BI__builtin_ia32_ucmpw512_mask:
3730   case X86::BI__builtin_ia32_ucmpd512_mask:
3731   case X86::BI__builtin_ia32_ucmpq512_mask:
3732   case X86::BI__builtin_ia32_vpcomub:
3733   case X86::BI__builtin_ia32_vpcomuw:
3734   case X86::BI__builtin_ia32_vpcomud:
3735   case X86::BI__builtin_ia32_vpcomuq:
3736   case X86::BI__builtin_ia32_vpcomb:
3737   case X86::BI__builtin_ia32_vpcomw:
3738   case X86::BI__builtin_ia32_vpcomd:
3739   case X86::BI__builtin_ia32_vpcomq:
3740   case X86::BI__builtin_ia32_vec_set_v8hi:
3741   case X86::BI__builtin_ia32_vec_set_v8si:
3742     i = 2; l = 0; u = 7;
3743     break;
3744   case X86::BI__builtin_ia32_vpermilpd256:
3745   case X86::BI__builtin_ia32_roundps:
3746   case X86::BI__builtin_ia32_roundpd:
3747   case X86::BI__builtin_ia32_roundps256:
3748   case X86::BI__builtin_ia32_roundpd256:
3749   case X86::BI__builtin_ia32_getmantpd128_mask:
3750   case X86::BI__builtin_ia32_getmantpd256_mask:
3751   case X86::BI__builtin_ia32_getmantps128_mask:
3752   case X86::BI__builtin_ia32_getmantps256_mask:
3753   case X86::BI__builtin_ia32_getmantpd512_mask:
3754   case X86::BI__builtin_ia32_getmantps512_mask:
3755   case X86::BI__builtin_ia32_vec_ext_v16qi:
3756   case X86::BI__builtin_ia32_vec_ext_v16hi:
3757     i = 1; l = 0; u = 15;
3758     break;
3759   case X86::BI__builtin_ia32_pblendd128:
3760   case X86::BI__builtin_ia32_blendps:
3761   case X86::BI__builtin_ia32_blendpd256:
3762   case X86::BI__builtin_ia32_shufpd256:
3763   case X86::BI__builtin_ia32_roundss:
3764   case X86::BI__builtin_ia32_roundsd:
3765   case X86::BI__builtin_ia32_rangepd128_mask:
3766   case X86::BI__builtin_ia32_rangepd256_mask:
3767   case X86::BI__builtin_ia32_rangepd512_mask:
3768   case X86::BI__builtin_ia32_rangeps128_mask:
3769   case X86::BI__builtin_ia32_rangeps256_mask:
3770   case X86::BI__builtin_ia32_rangeps512_mask:
3771   case X86::BI__builtin_ia32_getmantsd_round_mask:
3772   case X86::BI__builtin_ia32_getmantss_round_mask:
3773   case X86::BI__builtin_ia32_vec_set_v16qi:
3774   case X86::BI__builtin_ia32_vec_set_v16hi:
3775     i = 2; l = 0; u = 15;
3776     break;
3777   case X86::BI__builtin_ia32_vec_ext_v32qi:
3778     i = 1; l = 0; u = 31;
3779     break;
3780   case X86::BI__builtin_ia32_cmpps:
3781   case X86::BI__builtin_ia32_cmpss:
3782   case X86::BI__builtin_ia32_cmppd:
3783   case X86::BI__builtin_ia32_cmpsd:
3784   case X86::BI__builtin_ia32_cmpps256:
3785   case X86::BI__builtin_ia32_cmppd256:
3786   case X86::BI__builtin_ia32_cmpps128_mask:
3787   case X86::BI__builtin_ia32_cmppd128_mask:
3788   case X86::BI__builtin_ia32_cmpps256_mask:
3789   case X86::BI__builtin_ia32_cmppd256_mask:
3790   case X86::BI__builtin_ia32_cmpps512_mask:
3791   case X86::BI__builtin_ia32_cmppd512_mask:
3792   case X86::BI__builtin_ia32_cmpsd_mask:
3793   case X86::BI__builtin_ia32_cmpss_mask:
3794   case X86::BI__builtin_ia32_vec_set_v32qi:
3795     i = 2; l = 0; u = 31;
3796     break;
3797   case X86::BI__builtin_ia32_permdf256:
3798   case X86::BI__builtin_ia32_permdi256:
3799   case X86::BI__builtin_ia32_permdf512:
3800   case X86::BI__builtin_ia32_permdi512:
3801   case X86::BI__builtin_ia32_vpermilps:
3802   case X86::BI__builtin_ia32_vpermilps256:
3803   case X86::BI__builtin_ia32_vpermilpd512:
3804   case X86::BI__builtin_ia32_vpermilps512:
3805   case X86::BI__builtin_ia32_pshufd:
3806   case X86::BI__builtin_ia32_pshufd256:
3807   case X86::BI__builtin_ia32_pshufd512:
3808   case X86::BI__builtin_ia32_pshufhw:
3809   case X86::BI__builtin_ia32_pshufhw256:
3810   case X86::BI__builtin_ia32_pshufhw512:
3811   case X86::BI__builtin_ia32_pshuflw:
3812   case X86::BI__builtin_ia32_pshuflw256:
3813   case X86::BI__builtin_ia32_pshuflw512:
3814   case X86::BI__builtin_ia32_vcvtps2ph:
3815   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3816   case X86::BI__builtin_ia32_vcvtps2ph256:
3817   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3818   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3819   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3820   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3821   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3822   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3823   case X86::BI__builtin_ia32_rndscaleps_mask:
3824   case X86::BI__builtin_ia32_rndscalepd_mask:
3825   case X86::BI__builtin_ia32_reducepd128_mask:
3826   case X86::BI__builtin_ia32_reducepd256_mask:
3827   case X86::BI__builtin_ia32_reducepd512_mask:
3828   case X86::BI__builtin_ia32_reduceps128_mask:
3829   case X86::BI__builtin_ia32_reduceps256_mask:
3830   case X86::BI__builtin_ia32_reduceps512_mask:
3831   case X86::BI__builtin_ia32_prold512:
3832   case X86::BI__builtin_ia32_prolq512:
3833   case X86::BI__builtin_ia32_prold128:
3834   case X86::BI__builtin_ia32_prold256:
3835   case X86::BI__builtin_ia32_prolq128:
3836   case X86::BI__builtin_ia32_prolq256:
3837   case X86::BI__builtin_ia32_prord512:
3838   case X86::BI__builtin_ia32_prorq512:
3839   case X86::BI__builtin_ia32_prord128:
3840   case X86::BI__builtin_ia32_prord256:
3841   case X86::BI__builtin_ia32_prorq128:
3842   case X86::BI__builtin_ia32_prorq256:
3843   case X86::BI__builtin_ia32_fpclasspd128_mask:
3844   case X86::BI__builtin_ia32_fpclasspd256_mask:
3845   case X86::BI__builtin_ia32_fpclassps128_mask:
3846   case X86::BI__builtin_ia32_fpclassps256_mask:
3847   case X86::BI__builtin_ia32_fpclassps512_mask:
3848   case X86::BI__builtin_ia32_fpclasspd512_mask:
3849   case X86::BI__builtin_ia32_fpclasssd_mask:
3850   case X86::BI__builtin_ia32_fpclassss_mask:
3851   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3852   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3853   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3854   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3855   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3856   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3857   case X86::BI__builtin_ia32_kshiftliqi:
3858   case X86::BI__builtin_ia32_kshiftlihi:
3859   case X86::BI__builtin_ia32_kshiftlisi:
3860   case X86::BI__builtin_ia32_kshiftlidi:
3861   case X86::BI__builtin_ia32_kshiftriqi:
3862   case X86::BI__builtin_ia32_kshiftrihi:
3863   case X86::BI__builtin_ia32_kshiftrisi:
3864   case X86::BI__builtin_ia32_kshiftridi:
3865     i = 1; l = 0; u = 255;
3866     break;
3867   case X86::BI__builtin_ia32_vperm2f128_pd256:
3868   case X86::BI__builtin_ia32_vperm2f128_ps256:
3869   case X86::BI__builtin_ia32_vperm2f128_si256:
3870   case X86::BI__builtin_ia32_permti256:
3871   case X86::BI__builtin_ia32_pblendw128:
3872   case X86::BI__builtin_ia32_pblendw256:
3873   case X86::BI__builtin_ia32_blendps256:
3874   case X86::BI__builtin_ia32_pblendd256:
3875   case X86::BI__builtin_ia32_palignr128:
3876   case X86::BI__builtin_ia32_palignr256:
3877   case X86::BI__builtin_ia32_palignr512:
3878   case X86::BI__builtin_ia32_alignq512:
3879   case X86::BI__builtin_ia32_alignd512:
3880   case X86::BI__builtin_ia32_alignd128:
3881   case X86::BI__builtin_ia32_alignd256:
3882   case X86::BI__builtin_ia32_alignq128:
3883   case X86::BI__builtin_ia32_alignq256:
3884   case X86::BI__builtin_ia32_vcomisd:
3885   case X86::BI__builtin_ia32_vcomiss:
3886   case X86::BI__builtin_ia32_shuf_f32x4:
3887   case X86::BI__builtin_ia32_shuf_f64x2:
3888   case X86::BI__builtin_ia32_shuf_i32x4:
3889   case X86::BI__builtin_ia32_shuf_i64x2:
3890   case X86::BI__builtin_ia32_shufpd512:
3891   case X86::BI__builtin_ia32_shufps:
3892   case X86::BI__builtin_ia32_shufps256:
3893   case X86::BI__builtin_ia32_shufps512:
3894   case X86::BI__builtin_ia32_dbpsadbw128:
3895   case X86::BI__builtin_ia32_dbpsadbw256:
3896   case X86::BI__builtin_ia32_dbpsadbw512:
3897   case X86::BI__builtin_ia32_vpshldd128:
3898   case X86::BI__builtin_ia32_vpshldd256:
3899   case X86::BI__builtin_ia32_vpshldd512:
3900   case X86::BI__builtin_ia32_vpshldq128:
3901   case X86::BI__builtin_ia32_vpshldq256:
3902   case X86::BI__builtin_ia32_vpshldq512:
3903   case X86::BI__builtin_ia32_vpshldw128:
3904   case X86::BI__builtin_ia32_vpshldw256:
3905   case X86::BI__builtin_ia32_vpshldw512:
3906   case X86::BI__builtin_ia32_vpshrdd128:
3907   case X86::BI__builtin_ia32_vpshrdd256:
3908   case X86::BI__builtin_ia32_vpshrdd512:
3909   case X86::BI__builtin_ia32_vpshrdq128:
3910   case X86::BI__builtin_ia32_vpshrdq256:
3911   case X86::BI__builtin_ia32_vpshrdq512:
3912   case X86::BI__builtin_ia32_vpshrdw128:
3913   case X86::BI__builtin_ia32_vpshrdw256:
3914   case X86::BI__builtin_ia32_vpshrdw512:
3915     i = 2; l = 0; u = 255;
3916     break;
3917   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3918   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3919   case X86::BI__builtin_ia32_fixupimmps512_mask:
3920   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3921   case X86::BI__builtin_ia32_fixupimmsd_mask:
3922   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3923   case X86::BI__builtin_ia32_fixupimmss_mask:
3924   case X86::BI__builtin_ia32_fixupimmss_maskz:
3925   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3926   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3927   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3928   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3929   case X86::BI__builtin_ia32_fixupimmps128_mask:
3930   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3931   case X86::BI__builtin_ia32_fixupimmps256_mask:
3932   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3933   case X86::BI__builtin_ia32_pternlogd512_mask:
3934   case X86::BI__builtin_ia32_pternlogd512_maskz:
3935   case X86::BI__builtin_ia32_pternlogq512_mask:
3936   case X86::BI__builtin_ia32_pternlogq512_maskz:
3937   case X86::BI__builtin_ia32_pternlogd128_mask:
3938   case X86::BI__builtin_ia32_pternlogd128_maskz:
3939   case X86::BI__builtin_ia32_pternlogd256_mask:
3940   case X86::BI__builtin_ia32_pternlogd256_maskz:
3941   case X86::BI__builtin_ia32_pternlogq128_mask:
3942   case X86::BI__builtin_ia32_pternlogq128_maskz:
3943   case X86::BI__builtin_ia32_pternlogq256_mask:
3944   case X86::BI__builtin_ia32_pternlogq256_maskz:
3945     i = 3; l = 0; u = 255;
3946     break;
3947   case X86::BI__builtin_ia32_gatherpfdpd:
3948   case X86::BI__builtin_ia32_gatherpfdps:
3949   case X86::BI__builtin_ia32_gatherpfqpd:
3950   case X86::BI__builtin_ia32_gatherpfqps:
3951   case X86::BI__builtin_ia32_scatterpfdpd:
3952   case X86::BI__builtin_ia32_scatterpfdps:
3953   case X86::BI__builtin_ia32_scatterpfqpd:
3954   case X86::BI__builtin_ia32_scatterpfqps:
3955     i = 4; l = 2; u = 3;
3956     break;
3957   case X86::BI__builtin_ia32_reducesd_mask:
3958   case X86::BI__builtin_ia32_reducess_mask:
3959   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3960   case X86::BI__builtin_ia32_rndscaless_round_mask:
3961     i = 4; l = 0; u = 255;
3962     break;
3963   }
3964 
3965   // Note that we don't force a hard error on the range check here, allowing
3966   // template-generated or macro-generated dead code to potentially have out-of-
3967   // range values. These need to code generate, but don't need to necessarily
3968   // make any sense. We use a warning that defaults to an error.
3969   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3970 }
3971 
3972 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3973 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3974 /// Returns true when the format fits the function and the FormatStringInfo has
3975 /// been populated.
3976 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3977                                FormatStringInfo *FSI) {
3978   FSI->HasVAListArg = Format->getFirstArg() == 0;
3979   FSI->FormatIdx = Format->getFormatIdx() - 1;
3980   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3981 
3982   // The way the format attribute works in GCC, the implicit this argument
3983   // of member functions is counted. However, it doesn't appear in our own
3984   // lists, so decrement format_idx in that case.
3985   if (IsCXXMember) {
3986     if(FSI->FormatIdx == 0)
3987       return false;
3988     --FSI->FormatIdx;
3989     if (FSI->FirstDataArg != 0)
3990       --FSI->FirstDataArg;
3991   }
3992   return true;
3993 }
3994 
3995 /// Checks if a the given expression evaluates to null.
3996 ///
3997 /// Returns true if the value evaluates to null.
3998 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3999   // If the expression has non-null type, it doesn't evaluate to null.
4000   if (auto nullability
4001         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4002     if (*nullability == NullabilityKind::NonNull)
4003       return false;
4004   }
4005 
4006   // As a special case, transparent unions initialized with zero are
4007   // considered null for the purposes of the nonnull attribute.
4008   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4009     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4010       if (const CompoundLiteralExpr *CLE =
4011           dyn_cast<CompoundLiteralExpr>(Expr))
4012         if (const InitListExpr *ILE =
4013             dyn_cast<InitListExpr>(CLE->getInitializer()))
4014           Expr = ILE->getInit(0);
4015   }
4016 
4017   bool Result;
4018   return (!Expr->isValueDependent() &&
4019           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4020           !Result);
4021 }
4022 
4023 static void CheckNonNullArgument(Sema &S,
4024                                  const Expr *ArgExpr,
4025                                  SourceLocation CallSiteLoc) {
4026   if (CheckNonNullExpr(S, ArgExpr))
4027     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4028                           S.PDiag(diag::warn_null_arg)
4029                               << ArgExpr->getSourceRange());
4030 }
4031 
4032 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4033   FormatStringInfo FSI;
4034   if ((GetFormatStringType(Format) == FST_NSString) &&
4035       getFormatStringInfo(Format, false, &FSI)) {
4036     Idx = FSI.FormatIdx;
4037     return true;
4038   }
4039   return false;
4040 }
4041 
4042 /// Diagnose use of %s directive in an NSString which is being passed
4043 /// as formatting string to formatting method.
4044 static void
4045 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4046                                         const NamedDecl *FDecl,
4047                                         Expr **Args,
4048                                         unsigned NumArgs) {
4049   unsigned Idx = 0;
4050   bool Format = false;
4051   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4052   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4053     Idx = 2;
4054     Format = true;
4055   }
4056   else
4057     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4058       if (S.GetFormatNSStringIdx(I, Idx)) {
4059         Format = true;
4060         break;
4061       }
4062     }
4063   if (!Format || NumArgs <= Idx)
4064     return;
4065   const Expr *FormatExpr = Args[Idx];
4066   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4067     FormatExpr = CSCE->getSubExpr();
4068   const StringLiteral *FormatString;
4069   if (const ObjCStringLiteral *OSL =
4070       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4071     FormatString = OSL->getString();
4072   else
4073     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4074   if (!FormatString)
4075     return;
4076   if (S.FormatStringHasSArg(FormatString)) {
4077     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4078       << "%s" << 1 << 1;
4079     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4080       << FDecl->getDeclName();
4081   }
4082 }
4083 
4084 /// Determine whether the given type has a non-null nullability annotation.
4085 static bool isNonNullType(ASTContext &ctx, QualType type) {
4086   if (auto nullability = type->getNullability(ctx))
4087     return *nullability == NullabilityKind::NonNull;
4088 
4089   return false;
4090 }
4091 
4092 static void CheckNonNullArguments(Sema &S,
4093                                   const NamedDecl *FDecl,
4094                                   const FunctionProtoType *Proto,
4095                                   ArrayRef<const Expr *> Args,
4096                                   SourceLocation CallSiteLoc) {
4097   assert((FDecl || Proto) && "Need a function declaration or prototype");
4098 
4099   // Already checked by by constant evaluator.
4100   if (S.isConstantEvaluated())
4101     return;
4102   // Check the attributes attached to the method/function itself.
4103   llvm::SmallBitVector NonNullArgs;
4104   if (FDecl) {
4105     // Handle the nonnull attribute on the function/method declaration itself.
4106     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4107       if (!NonNull->args_size()) {
4108         // Easy case: all pointer arguments are nonnull.
4109         for (const auto *Arg : Args)
4110           if (S.isValidPointerAttrType(Arg->getType()))
4111             CheckNonNullArgument(S, Arg, CallSiteLoc);
4112         return;
4113       }
4114 
4115       for (const ParamIdx &Idx : NonNull->args()) {
4116         unsigned IdxAST = Idx.getASTIndex();
4117         if (IdxAST >= Args.size())
4118           continue;
4119         if (NonNullArgs.empty())
4120           NonNullArgs.resize(Args.size());
4121         NonNullArgs.set(IdxAST);
4122       }
4123     }
4124   }
4125 
4126   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4127     // Handle the nonnull attribute on the parameters of the
4128     // function/method.
4129     ArrayRef<ParmVarDecl*> parms;
4130     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4131       parms = FD->parameters();
4132     else
4133       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4134 
4135     unsigned ParamIndex = 0;
4136     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4137          I != E; ++I, ++ParamIndex) {
4138       const ParmVarDecl *PVD = *I;
4139       if (PVD->hasAttr<NonNullAttr>() ||
4140           isNonNullType(S.Context, PVD->getType())) {
4141         if (NonNullArgs.empty())
4142           NonNullArgs.resize(Args.size());
4143 
4144         NonNullArgs.set(ParamIndex);
4145       }
4146     }
4147   } else {
4148     // If we have a non-function, non-method declaration but no
4149     // function prototype, try to dig out the function prototype.
4150     if (!Proto) {
4151       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4152         QualType type = VD->getType().getNonReferenceType();
4153         if (auto pointerType = type->getAs<PointerType>())
4154           type = pointerType->getPointeeType();
4155         else if (auto blockType = type->getAs<BlockPointerType>())
4156           type = blockType->getPointeeType();
4157         // FIXME: data member pointers?
4158 
4159         // Dig out the function prototype, if there is one.
4160         Proto = type->getAs<FunctionProtoType>();
4161       }
4162     }
4163 
4164     // Fill in non-null argument information from the nullability
4165     // information on the parameter types (if we have them).
4166     if (Proto) {
4167       unsigned Index = 0;
4168       for (auto paramType : Proto->getParamTypes()) {
4169         if (isNonNullType(S.Context, paramType)) {
4170           if (NonNullArgs.empty())
4171             NonNullArgs.resize(Args.size());
4172 
4173           NonNullArgs.set(Index);
4174         }
4175 
4176         ++Index;
4177       }
4178     }
4179   }
4180 
4181   // Check for non-null arguments.
4182   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4183        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4184     if (NonNullArgs[ArgIndex])
4185       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4186   }
4187 }
4188 
4189 /// Handles the checks for format strings, non-POD arguments to vararg
4190 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4191 /// attributes.
4192 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4193                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4194                      bool IsMemberFunction, SourceLocation Loc,
4195                      SourceRange Range, VariadicCallType CallType) {
4196   // FIXME: We should check as much as we can in the template definition.
4197   if (CurContext->isDependentContext())
4198     return;
4199 
4200   // Printf and scanf checking.
4201   llvm::SmallBitVector CheckedVarArgs;
4202   if (FDecl) {
4203     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4204       // Only create vector if there are format attributes.
4205       CheckedVarArgs.resize(Args.size());
4206 
4207       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4208                            CheckedVarArgs);
4209     }
4210   }
4211 
4212   // Refuse POD arguments that weren't caught by the format string
4213   // checks above.
4214   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4215   if (CallType != VariadicDoesNotApply &&
4216       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4217     unsigned NumParams = Proto ? Proto->getNumParams()
4218                        : FDecl && isa<FunctionDecl>(FDecl)
4219                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4220                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4221                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4222                        : 0;
4223 
4224     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4225       // Args[ArgIdx] can be null in malformed code.
4226       if (const Expr *Arg = Args[ArgIdx]) {
4227         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4228           checkVariadicArgument(Arg, CallType);
4229       }
4230     }
4231   }
4232 
4233   if (FDecl || Proto) {
4234     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4235 
4236     // Type safety checking.
4237     if (FDecl) {
4238       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4239         CheckArgumentWithTypeTag(I, Args, Loc);
4240     }
4241   }
4242 
4243   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4244     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4245     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4246     if (!Arg->isValueDependent()) {
4247       Expr::EvalResult Align;
4248       if (Arg->EvaluateAsInt(Align, Context)) {
4249         const llvm::APSInt &I = Align.Val.getInt();
4250         if (!I.isPowerOf2())
4251           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4252               << Arg->getSourceRange();
4253 
4254         if (I > Sema::MaximumAlignment)
4255           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4256               << Arg->getSourceRange() << Sema::MaximumAlignment;
4257       }
4258     }
4259   }
4260 
4261   if (FD)
4262     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4263 }
4264 
4265 /// CheckConstructorCall - Check a constructor call for correctness and safety
4266 /// properties not enforced by the C type system.
4267 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4268                                 ArrayRef<const Expr *> Args,
4269                                 const FunctionProtoType *Proto,
4270                                 SourceLocation Loc) {
4271   VariadicCallType CallType =
4272     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4273   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4274             Loc, SourceRange(), CallType);
4275 }
4276 
4277 /// CheckFunctionCall - Check a direct function call for various correctness
4278 /// and safety properties not strictly enforced by the C type system.
4279 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4280                              const FunctionProtoType *Proto) {
4281   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4282                               isa<CXXMethodDecl>(FDecl);
4283   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4284                           IsMemberOperatorCall;
4285   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4286                                                   TheCall->getCallee());
4287   Expr** Args = TheCall->getArgs();
4288   unsigned NumArgs = TheCall->getNumArgs();
4289 
4290   Expr *ImplicitThis = nullptr;
4291   if (IsMemberOperatorCall) {
4292     // If this is a call to a member operator, hide the first argument
4293     // from checkCall.
4294     // FIXME: Our choice of AST representation here is less than ideal.
4295     ImplicitThis = Args[0];
4296     ++Args;
4297     --NumArgs;
4298   } else if (IsMemberFunction)
4299     ImplicitThis =
4300         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4301 
4302   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4303             IsMemberFunction, TheCall->getRParenLoc(),
4304             TheCall->getCallee()->getSourceRange(), CallType);
4305 
4306   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4307   // None of the checks below are needed for functions that don't have
4308   // simple names (e.g., C++ conversion functions).
4309   if (!FnInfo)
4310     return false;
4311 
4312   CheckAbsoluteValueFunction(TheCall, FDecl);
4313   CheckMaxUnsignedZero(TheCall, FDecl);
4314 
4315   if (getLangOpts().ObjC)
4316     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4317 
4318   unsigned CMId = FDecl->getMemoryFunctionKind();
4319   if (CMId == 0)
4320     return false;
4321 
4322   // Handle memory setting and copying functions.
4323   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4324     CheckStrlcpycatArguments(TheCall, FnInfo);
4325   else if (CMId == Builtin::BIstrncat)
4326     CheckStrncatArguments(TheCall, FnInfo);
4327   else
4328     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4329 
4330   return false;
4331 }
4332 
4333 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4334                                ArrayRef<const Expr *> Args) {
4335   VariadicCallType CallType =
4336       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4337 
4338   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4339             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4340             CallType);
4341 
4342   return false;
4343 }
4344 
4345 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4346                             const FunctionProtoType *Proto) {
4347   QualType Ty;
4348   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4349     Ty = V->getType().getNonReferenceType();
4350   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4351     Ty = F->getType().getNonReferenceType();
4352   else
4353     return false;
4354 
4355   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4356       !Ty->isFunctionProtoType())
4357     return false;
4358 
4359   VariadicCallType CallType;
4360   if (!Proto || !Proto->isVariadic()) {
4361     CallType = VariadicDoesNotApply;
4362   } else if (Ty->isBlockPointerType()) {
4363     CallType = VariadicBlock;
4364   } else { // Ty->isFunctionPointerType()
4365     CallType = VariadicFunction;
4366   }
4367 
4368   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4369             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4370             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4371             TheCall->getCallee()->getSourceRange(), CallType);
4372 
4373   return false;
4374 }
4375 
4376 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4377 /// such as function pointers returned from functions.
4378 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4379   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4380                                                   TheCall->getCallee());
4381   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4382             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4383             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4384             TheCall->getCallee()->getSourceRange(), CallType);
4385 
4386   return false;
4387 }
4388 
4389 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4390   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4391     return false;
4392 
4393   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4394   switch (Op) {
4395   case AtomicExpr::AO__c11_atomic_init:
4396   case AtomicExpr::AO__opencl_atomic_init:
4397     llvm_unreachable("There is no ordering argument for an init");
4398 
4399   case AtomicExpr::AO__c11_atomic_load:
4400   case AtomicExpr::AO__opencl_atomic_load:
4401   case AtomicExpr::AO__atomic_load_n:
4402   case AtomicExpr::AO__atomic_load:
4403     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4404            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4405 
4406   case AtomicExpr::AO__c11_atomic_store:
4407   case AtomicExpr::AO__opencl_atomic_store:
4408   case AtomicExpr::AO__atomic_store:
4409   case AtomicExpr::AO__atomic_store_n:
4410     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4411            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4412            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4413 
4414   default:
4415     return true;
4416   }
4417 }
4418 
4419 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4420                                          AtomicExpr::AtomicOp Op) {
4421   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4422   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4423   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4424   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4425                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4426                          Op);
4427 }
4428 
4429 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4430                                  SourceLocation RParenLoc, MultiExprArg Args,
4431                                  AtomicExpr::AtomicOp Op,
4432                                  AtomicArgumentOrder ArgOrder) {
4433   // All the non-OpenCL operations take one of the following forms.
4434   // The OpenCL operations take the __c11 forms with one extra argument for
4435   // synchronization scope.
4436   enum {
4437     // C    __c11_atomic_init(A *, C)
4438     Init,
4439 
4440     // C    __c11_atomic_load(A *, int)
4441     Load,
4442 
4443     // void __atomic_load(A *, CP, int)
4444     LoadCopy,
4445 
4446     // void __atomic_store(A *, CP, int)
4447     Copy,
4448 
4449     // C    __c11_atomic_add(A *, M, int)
4450     Arithmetic,
4451 
4452     // C    __atomic_exchange_n(A *, CP, int)
4453     Xchg,
4454 
4455     // void __atomic_exchange(A *, C *, CP, int)
4456     GNUXchg,
4457 
4458     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4459     C11CmpXchg,
4460 
4461     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4462     GNUCmpXchg
4463   } Form = Init;
4464 
4465   const unsigned NumForm = GNUCmpXchg + 1;
4466   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4467   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4468   // where:
4469   //   C is an appropriate type,
4470   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4471   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4472   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4473   //   the int parameters are for orderings.
4474 
4475   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4476       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4477       "need to update code for modified forms");
4478   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4479                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4480                         AtomicExpr::AO__atomic_load,
4481                 "need to update code for modified C11 atomics");
4482   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4483                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4484   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4485                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4486                IsOpenCL;
4487   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4488              Op == AtomicExpr::AO__atomic_store_n ||
4489              Op == AtomicExpr::AO__atomic_exchange_n ||
4490              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4491   bool IsAddSub = false;
4492 
4493   switch (Op) {
4494   case AtomicExpr::AO__c11_atomic_init:
4495   case AtomicExpr::AO__opencl_atomic_init:
4496     Form = Init;
4497     break;
4498 
4499   case AtomicExpr::AO__c11_atomic_load:
4500   case AtomicExpr::AO__opencl_atomic_load:
4501   case AtomicExpr::AO__atomic_load_n:
4502     Form = Load;
4503     break;
4504 
4505   case AtomicExpr::AO__atomic_load:
4506     Form = LoadCopy;
4507     break;
4508 
4509   case AtomicExpr::AO__c11_atomic_store:
4510   case AtomicExpr::AO__opencl_atomic_store:
4511   case AtomicExpr::AO__atomic_store:
4512   case AtomicExpr::AO__atomic_store_n:
4513     Form = Copy;
4514     break;
4515 
4516   case AtomicExpr::AO__c11_atomic_fetch_add:
4517   case AtomicExpr::AO__c11_atomic_fetch_sub:
4518   case AtomicExpr::AO__opencl_atomic_fetch_add:
4519   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4520   case AtomicExpr::AO__atomic_fetch_add:
4521   case AtomicExpr::AO__atomic_fetch_sub:
4522   case AtomicExpr::AO__atomic_add_fetch:
4523   case AtomicExpr::AO__atomic_sub_fetch:
4524     IsAddSub = true;
4525     LLVM_FALLTHROUGH;
4526   case AtomicExpr::AO__c11_atomic_fetch_and:
4527   case AtomicExpr::AO__c11_atomic_fetch_or:
4528   case AtomicExpr::AO__c11_atomic_fetch_xor:
4529   case AtomicExpr::AO__opencl_atomic_fetch_and:
4530   case AtomicExpr::AO__opencl_atomic_fetch_or:
4531   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4532   case AtomicExpr::AO__atomic_fetch_and:
4533   case AtomicExpr::AO__atomic_fetch_or:
4534   case AtomicExpr::AO__atomic_fetch_xor:
4535   case AtomicExpr::AO__atomic_fetch_nand:
4536   case AtomicExpr::AO__atomic_and_fetch:
4537   case AtomicExpr::AO__atomic_or_fetch:
4538   case AtomicExpr::AO__atomic_xor_fetch:
4539   case AtomicExpr::AO__atomic_nand_fetch:
4540   case AtomicExpr::AO__c11_atomic_fetch_min:
4541   case AtomicExpr::AO__c11_atomic_fetch_max:
4542   case AtomicExpr::AO__opencl_atomic_fetch_min:
4543   case AtomicExpr::AO__opencl_atomic_fetch_max:
4544   case AtomicExpr::AO__atomic_min_fetch:
4545   case AtomicExpr::AO__atomic_max_fetch:
4546   case AtomicExpr::AO__atomic_fetch_min:
4547   case AtomicExpr::AO__atomic_fetch_max:
4548     Form = Arithmetic;
4549     break;
4550 
4551   case AtomicExpr::AO__c11_atomic_exchange:
4552   case AtomicExpr::AO__opencl_atomic_exchange:
4553   case AtomicExpr::AO__atomic_exchange_n:
4554     Form = Xchg;
4555     break;
4556 
4557   case AtomicExpr::AO__atomic_exchange:
4558     Form = GNUXchg;
4559     break;
4560 
4561   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4562   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4563   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4564   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4565     Form = C11CmpXchg;
4566     break;
4567 
4568   case AtomicExpr::AO__atomic_compare_exchange:
4569   case AtomicExpr::AO__atomic_compare_exchange_n:
4570     Form = GNUCmpXchg;
4571     break;
4572   }
4573 
4574   unsigned AdjustedNumArgs = NumArgs[Form];
4575   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4576     ++AdjustedNumArgs;
4577   // Check we have the right number of arguments.
4578   if (Args.size() < AdjustedNumArgs) {
4579     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4580         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4581         << ExprRange;
4582     return ExprError();
4583   } else if (Args.size() > AdjustedNumArgs) {
4584     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4585          diag::err_typecheck_call_too_many_args)
4586         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4587         << ExprRange;
4588     return ExprError();
4589   }
4590 
4591   // Inspect the first argument of the atomic operation.
4592   Expr *Ptr = Args[0];
4593   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4594   if (ConvertedPtr.isInvalid())
4595     return ExprError();
4596 
4597   Ptr = ConvertedPtr.get();
4598   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4599   if (!pointerType) {
4600     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4601         << Ptr->getType() << Ptr->getSourceRange();
4602     return ExprError();
4603   }
4604 
4605   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4606   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4607   QualType ValType = AtomTy; // 'C'
4608   if (IsC11) {
4609     if (!AtomTy->isAtomicType()) {
4610       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4611           << Ptr->getType() << Ptr->getSourceRange();
4612       return ExprError();
4613     }
4614     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4615         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4616       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4617           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4618           << Ptr->getSourceRange();
4619       return ExprError();
4620     }
4621     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4622   } else if (Form != Load && Form != LoadCopy) {
4623     if (ValType.isConstQualified()) {
4624       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4625           << Ptr->getType() << Ptr->getSourceRange();
4626       return ExprError();
4627     }
4628   }
4629 
4630   // For an arithmetic operation, the implied arithmetic must be well-formed.
4631   if (Form == Arithmetic) {
4632     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4633     if (IsAddSub && !ValType->isIntegerType()
4634         && !ValType->isPointerType()) {
4635       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4636           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4637       return ExprError();
4638     }
4639     if (!IsAddSub && !ValType->isIntegerType()) {
4640       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4641           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4642       return ExprError();
4643     }
4644     if (IsC11 && ValType->isPointerType() &&
4645         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4646                             diag::err_incomplete_type)) {
4647       return ExprError();
4648     }
4649   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4650     // For __atomic_*_n operations, the value type must be a scalar integral or
4651     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4652     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4653         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4654     return ExprError();
4655   }
4656 
4657   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4658       !AtomTy->isScalarType()) {
4659     // For GNU atomics, require a trivially-copyable type. This is not part of
4660     // the GNU atomics specification, but we enforce it for sanity.
4661     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4662         << Ptr->getType() << Ptr->getSourceRange();
4663     return ExprError();
4664   }
4665 
4666   switch (ValType.getObjCLifetime()) {
4667   case Qualifiers::OCL_None:
4668   case Qualifiers::OCL_ExplicitNone:
4669     // okay
4670     break;
4671 
4672   case Qualifiers::OCL_Weak:
4673   case Qualifiers::OCL_Strong:
4674   case Qualifiers::OCL_Autoreleasing:
4675     // FIXME: Can this happen? By this point, ValType should be known
4676     // to be trivially copyable.
4677     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4678         << ValType << Ptr->getSourceRange();
4679     return ExprError();
4680   }
4681 
4682   // All atomic operations have an overload which takes a pointer to a volatile
4683   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4684   // into the result or the other operands. Similarly atomic_load takes a
4685   // pointer to a const 'A'.
4686   ValType.removeLocalVolatile();
4687   ValType.removeLocalConst();
4688   QualType ResultType = ValType;
4689   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4690       Form == Init)
4691     ResultType = Context.VoidTy;
4692   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4693     ResultType = Context.BoolTy;
4694 
4695   // The type of a parameter passed 'by value'. In the GNU atomics, such
4696   // arguments are actually passed as pointers.
4697   QualType ByValType = ValType; // 'CP'
4698   bool IsPassedByAddress = false;
4699   if (!IsC11 && !IsN) {
4700     ByValType = Ptr->getType();
4701     IsPassedByAddress = true;
4702   }
4703 
4704   SmallVector<Expr *, 5> APIOrderedArgs;
4705   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4706     APIOrderedArgs.push_back(Args[0]);
4707     switch (Form) {
4708     case Init:
4709     case Load:
4710       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4711       break;
4712     case LoadCopy:
4713     case Copy:
4714     case Arithmetic:
4715     case Xchg:
4716       APIOrderedArgs.push_back(Args[2]); // Val1
4717       APIOrderedArgs.push_back(Args[1]); // Order
4718       break;
4719     case GNUXchg:
4720       APIOrderedArgs.push_back(Args[2]); // Val1
4721       APIOrderedArgs.push_back(Args[3]); // Val2
4722       APIOrderedArgs.push_back(Args[1]); // Order
4723       break;
4724     case C11CmpXchg:
4725       APIOrderedArgs.push_back(Args[2]); // Val1
4726       APIOrderedArgs.push_back(Args[4]); // Val2
4727       APIOrderedArgs.push_back(Args[1]); // Order
4728       APIOrderedArgs.push_back(Args[3]); // OrderFail
4729       break;
4730     case GNUCmpXchg:
4731       APIOrderedArgs.push_back(Args[2]); // Val1
4732       APIOrderedArgs.push_back(Args[4]); // Val2
4733       APIOrderedArgs.push_back(Args[5]); // Weak
4734       APIOrderedArgs.push_back(Args[1]); // Order
4735       APIOrderedArgs.push_back(Args[3]); // OrderFail
4736       break;
4737     }
4738   } else
4739     APIOrderedArgs.append(Args.begin(), Args.end());
4740 
4741   // The first argument's non-CV pointer type is used to deduce the type of
4742   // subsequent arguments, except for:
4743   //  - weak flag (always converted to bool)
4744   //  - memory order (always converted to int)
4745   //  - scope  (always converted to int)
4746   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4747     QualType Ty;
4748     if (i < NumVals[Form] + 1) {
4749       switch (i) {
4750       case 0:
4751         // The first argument is always a pointer. It has a fixed type.
4752         // It is always dereferenced, a nullptr is undefined.
4753         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4754         // Nothing else to do: we already know all we want about this pointer.
4755         continue;
4756       case 1:
4757         // The second argument is the non-atomic operand. For arithmetic, this
4758         // is always passed by value, and for a compare_exchange it is always
4759         // passed by address. For the rest, GNU uses by-address and C11 uses
4760         // by-value.
4761         assert(Form != Load);
4762         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4763           Ty = ValType;
4764         else if (Form == Copy || Form == Xchg) {
4765           if (IsPassedByAddress) {
4766             // The value pointer is always dereferenced, a nullptr is undefined.
4767             CheckNonNullArgument(*this, APIOrderedArgs[i],
4768                                  ExprRange.getBegin());
4769           }
4770           Ty = ByValType;
4771         } else if (Form == Arithmetic)
4772           Ty = Context.getPointerDiffType();
4773         else {
4774           Expr *ValArg = APIOrderedArgs[i];
4775           // The value pointer is always dereferenced, a nullptr is undefined.
4776           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4777           LangAS AS = LangAS::Default;
4778           // Keep address space of non-atomic pointer type.
4779           if (const PointerType *PtrTy =
4780                   ValArg->getType()->getAs<PointerType>()) {
4781             AS = PtrTy->getPointeeType().getAddressSpace();
4782           }
4783           Ty = Context.getPointerType(
4784               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4785         }
4786         break;
4787       case 2:
4788         // The third argument to compare_exchange / GNU exchange is the desired
4789         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4790         if (IsPassedByAddress)
4791           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4792         Ty = ByValType;
4793         break;
4794       case 3:
4795         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4796         Ty = Context.BoolTy;
4797         break;
4798       }
4799     } else {
4800       // The order(s) and scope are always converted to int.
4801       Ty = Context.IntTy;
4802     }
4803 
4804     InitializedEntity Entity =
4805         InitializedEntity::InitializeParameter(Context, Ty, false);
4806     ExprResult Arg = APIOrderedArgs[i];
4807     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4808     if (Arg.isInvalid())
4809       return true;
4810     APIOrderedArgs[i] = Arg.get();
4811   }
4812 
4813   // Permute the arguments into a 'consistent' order.
4814   SmallVector<Expr*, 5> SubExprs;
4815   SubExprs.push_back(Ptr);
4816   switch (Form) {
4817   case Init:
4818     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4819     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4820     break;
4821   case Load:
4822     SubExprs.push_back(APIOrderedArgs[1]); // Order
4823     break;
4824   case LoadCopy:
4825   case Copy:
4826   case Arithmetic:
4827   case Xchg:
4828     SubExprs.push_back(APIOrderedArgs[2]); // Order
4829     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4830     break;
4831   case GNUXchg:
4832     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4833     SubExprs.push_back(APIOrderedArgs[3]); // Order
4834     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4835     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4836     break;
4837   case C11CmpXchg:
4838     SubExprs.push_back(APIOrderedArgs[3]); // Order
4839     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4840     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4841     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4842     break;
4843   case GNUCmpXchg:
4844     SubExprs.push_back(APIOrderedArgs[4]); // Order
4845     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4846     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4847     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4848     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4849     break;
4850   }
4851 
4852   if (SubExprs.size() >= 2 && Form != Init) {
4853     llvm::APSInt Result(32);
4854     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4855         !isValidOrderingForOp(Result.getSExtValue(), Op))
4856       Diag(SubExprs[1]->getBeginLoc(),
4857            diag::warn_atomic_op_has_invalid_memory_order)
4858           << SubExprs[1]->getSourceRange();
4859   }
4860 
4861   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4862     auto *Scope = Args[Args.size() - 1];
4863     llvm::APSInt Result(32);
4864     if (Scope->isIntegerConstantExpr(Result, Context) &&
4865         !ScopeModel->isValid(Result.getZExtValue())) {
4866       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4867           << Scope->getSourceRange();
4868     }
4869     SubExprs.push_back(Scope);
4870   }
4871 
4872   AtomicExpr *AE = new (Context)
4873       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4874 
4875   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4876        Op == AtomicExpr::AO__c11_atomic_store ||
4877        Op == AtomicExpr::AO__opencl_atomic_load ||
4878        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4879       Context.AtomicUsesUnsupportedLibcall(AE))
4880     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4881         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4882              Op == AtomicExpr::AO__opencl_atomic_load)
4883                 ? 0
4884                 : 1);
4885 
4886   return AE;
4887 }
4888 
4889 /// checkBuiltinArgument - Given a call to a builtin function, perform
4890 /// normal type-checking on the given argument, updating the call in
4891 /// place.  This is useful when a builtin function requires custom
4892 /// type-checking for some of its arguments but not necessarily all of
4893 /// them.
4894 ///
4895 /// Returns true on error.
4896 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4897   FunctionDecl *Fn = E->getDirectCallee();
4898   assert(Fn && "builtin call without direct callee!");
4899 
4900   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4901   InitializedEntity Entity =
4902     InitializedEntity::InitializeParameter(S.Context, Param);
4903 
4904   ExprResult Arg = E->getArg(0);
4905   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4906   if (Arg.isInvalid())
4907     return true;
4908 
4909   E->setArg(ArgIndex, Arg.get());
4910   return false;
4911 }
4912 
4913 /// We have a call to a function like __sync_fetch_and_add, which is an
4914 /// overloaded function based on the pointer type of its first argument.
4915 /// The main BuildCallExpr routines have already promoted the types of
4916 /// arguments because all of these calls are prototyped as void(...).
4917 ///
4918 /// This function goes through and does final semantic checking for these
4919 /// builtins, as well as generating any warnings.
4920 ExprResult
4921 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4922   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4923   Expr *Callee = TheCall->getCallee();
4924   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4925   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4926 
4927   // Ensure that we have at least one argument to do type inference from.
4928   if (TheCall->getNumArgs() < 1) {
4929     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4930         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4931     return ExprError();
4932   }
4933 
4934   // Inspect the first argument of the atomic builtin.  This should always be
4935   // a pointer type, whose element is an integral scalar or pointer type.
4936   // Because it is a pointer type, we don't have to worry about any implicit
4937   // casts here.
4938   // FIXME: We don't allow floating point scalars as input.
4939   Expr *FirstArg = TheCall->getArg(0);
4940   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4941   if (FirstArgResult.isInvalid())
4942     return ExprError();
4943   FirstArg = FirstArgResult.get();
4944   TheCall->setArg(0, FirstArg);
4945 
4946   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4947   if (!pointerType) {
4948     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4949         << FirstArg->getType() << FirstArg->getSourceRange();
4950     return ExprError();
4951   }
4952 
4953   QualType ValType = pointerType->getPointeeType();
4954   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4955       !ValType->isBlockPointerType()) {
4956     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4957         << FirstArg->getType() << FirstArg->getSourceRange();
4958     return ExprError();
4959   }
4960 
4961   if (ValType.isConstQualified()) {
4962     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4963         << FirstArg->getType() << FirstArg->getSourceRange();
4964     return ExprError();
4965   }
4966 
4967   switch (ValType.getObjCLifetime()) {
4968   case Qualifiers::OCL_None:
4969   case Qualifiers::OCL_ExplicitNone:
4970     // okay
4971     break;
4972 
4973   case Qualifiers::OCL_Weak:
4974   case Qualifiers::OCL_Strong:
4975   case Qualifiers::OCL_Autoreleasing:
4976     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4977         << ValType << FirstArg->getSourceRange();
4978     return ExprError();
4979   }
4980 
4981   // Strip any qualifiers off ValType.
4982   ValType = ValType.getUnqualifiedType();
4983 
4984   // The majority of builtins return a value, but a few have special return
4985   // types, so allow them to override appropriately below.
4986   QualType ResultType = ValType;
4987 
4988   // We need to figure out which concrete builtin this maps onto.  For example,
4989   // __sync_fetch_and_add with a 2 byte object turns into
4990   // __sync_fetch_and_add_2.
4991 #define BUILTIN_ROW(x) \
4992   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4993     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4994 
4995   static const unsigned BuiltinIndices[][5] = {
4996     BUILTIN_ROW(__sync_fetch_and_add),
4997     BUILTIN_ROW(__sync_fetch_and_sub),
4998     BUILTIN_ROW(__sync_fetch_and_or),
4999     BUILTIN_ROW(__sync_fetch_and_and),
5000     BUILTIN_ROW(__sync_fetch_and_xor),
5001     BUILTIN_ROW(__sync_fetch_and_nand),
5002 
5003     BUILTIN_ROW(__sync_add_and_fetch),
5004     BUILTIN_ROW(__sync_sub_and_fetch),
5005     BUILTIN_ROW(__sync_and_and_fetch),
5006     BUILTIN_ROW(__sync_or_and_fetch),
5007     BUILTIN_ROW(__sync_xor_and_fetch),
5008     BUILTIN_ROW(__sync_nand_and_fetch),
5009 
5010     BUILTIN_ROW(__sync_val_compare_and_swap),
5011     BUILTIN_ROW(__sync_bool_compare_and_swap),
5012     BUILTIN_ROW(__sync_lock_test_and_set),
5013     BUILTIN_ROW(__sync_lock_release),
5014     BUILTIN_ROW(__sync_swap)
5015   };
5016 #undef BUILTIN_ROW
5017 
5018   // Determine the index of the size.
5019   unsigned SizeIndex;
5020   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5021   case 1: SizeIndex = 0; break;
5022   case 2: SizeIndex = 1; break;
5023   case 4: SizeIndex = 2; break;
5024   case 8: SizeIndex = 3; break;
5025   case 16: SizeIndex = 4; break;
5026   default:
5027     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5028         << FirstArg->getType() << FirstArg->getSourceRange();
5029     return ExprError();
5030   }
5031 
5032   // Each of these builtins has one pointer argument, followed by some number of
5033   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5034   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5035   // as the number of fixed args.
5036   unsigned BuiltinID = FDecl->getBuiltinID();
5037   unsigned BuiltinIndex, NumFixed = 1;
5038   bool WarnAboutSemanticsChange = false;
5039   switch (BuiltinID) {
5040   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5041   case Builtin::BI__sync_fetch_and_add:
5042   case Builtin::BI__sync_fetch_and_add_1:
5043   case Builtin::BI__sync_fetch_and_add_2:
5044   case Builtin::BI__sync_fetch_and_add_4:
5045   case Builtin::BI__sync_fetch_and_add_8:
5046   case Builtin::BI__sync_fetch_and_add_16:
5047     BuiltinIndex = 0;
5048     break;
5049 
5050   case Builtin::BI__sync_fetch_and_sub:
5051   case Builtin::BI__sync_fetch_and_sub_1:
5052   case Builtin::BI__sync_fetch_and_sub_2:
5053   case Builtin::BI__sync_fetch_and_sub_4:
5054   case Builtin::BI__sync_fetch_and_sub_8:
5055   case Builtin::BI__sync_fetch_and_sub_16:
5056     BuiltinIndex = 1;
5057     break;
5058 
5059   case Builtin::BI__sync_fetch_and_or:
5060   case Builtin::BI__sync_fetch_and_or_1:
5061   case Builtin::BI__sync_fetch_and_or_2:
5062   case Builtin::BI__sync_fetch_and_or_4:
5063   case Builtin::BI__sync_fetch_and_or_8:
5064   case Builtin::BI__sync_fetch_and_or_16:
5065     BuiltinIndex = 2;
5066     break;
5067 
5068   case Builtin::BI__sync_fetch_and_and:
5069   case Builtin::BI__sync_fetch_and_and_1:
5070   case Builtin::BI__sync_fetch_and_and_2:
5071   case Builtin::BI__sync_fetch_and_and_4:
5072   case Builtin::BI__sync_fetch_and_and_8:
5073   case Builtin::BI__sync_fetch_and_and_16:
5074     BuiltinIndex = 3;
5075     break;
5076 
5077   case Builtin::BI__sync_fetch_and_xor:
5078   case Builtin::BI__sync_fetch_and_xor_1:
5079   case Builtin::BI__sync_fetch_and_xor_2:
5080   case Builtin::BI__sync_fetch_and_xor_4:
5081   case Builtin::BI__sync_fetch_and_xor_8:
5082   case Builtin::BI__sync_fetch_and_xor_16:
5083     BuiltinIndex = 4;
5084     break;
5085 
5086   case Builtin::BI__sync_fetch_and_nand:
5087   case Builtin::BI__sync_fetch_and_nand_1:
5088   case Builtin::BI__sync_fetch_and_nand_2:
5089   case Builtin::BI__sync_fetch_and_nand_4:
5090   case Builtin::BI__sync_fetch_and_nand_8:
5091   case Builtin::BI__sync_fetch_and_nand_16:
5092     BuiltinIndex = 5;
5093     WarnAboutSemanticsChange = true;
5094     break;
5095 
5096   case Builtin::BI__sync_add_and_fetch:
5097   case Builtin::BI__sync_add_and_fetch_1:
5098   case Builtin::BI__sync_add_and_fetch_2:
5099   case Builtin::BI__sync_add_and_fetch_4:
5100   case Builtin::BI__sync_add_and_fetch_8:
5101   case Builtin::BI__sync_add_and_fetch_16:
5102     BuiltinIndex = 6;
5103     break;
5104 
5105   case Builtin::BI__sync_sub_and_fetch:
5106   case Builtin::BI__sync_sub_and_fetch_1:
5107   case Builtin::BI__sync_sub_and_fetch_2:
5108   case Builtin::BI__sync_sub_and_fetch_4:
5109   case Builtin::BI__sync_sub_and_fetch_8:
5110   case Builtin::BI__sync_sub_and_fetch_16:
5111     BuiltinIndex = 7;
5112     break;
5113 
5114   case Builtin::BI__sync_and_and_fetch:
5115   case Builtin::BI__sync_and_and_fetch_1:
5116   case Builtin::BI__sync_and_and_fetch_2:
5117   case Builtin::BI__sync_and_and_fetch_4:
5118   case Builtin::BI__sync_and_and_fetch_8:
5119   case Builtin::BI__sync_and_and_fetch_16:
5120     BuiltinIndex = 8;
5121     break;
5122 
5123   case Builtin::BI__sync_or_and_fetch:
5124   case Builtin::BI__sync_or_and_fetch_1:
5125   case Builtin::BI__sync_or_and_fetch_2:
5126   case Builtin::BI__sync_or_and_fetch_4:
5127   case Builtin::BI__sync_or_and_fetch_8:
5128   case Builtin::BI__sync_or_and_fetch_16:
5129     BuiltinIndex = 9;
5130     break;
5131 
5132   case Builtin::BI__sync_xor_and_fetch:
5133   case Builtin::BI__sync_xor_and_fetch_1:
5134   case Builtin::BI__sync_xor_and_fetch_2:
5135   case Builtin::BI__sync_xor_and_fetch_4:
5136   case Builtin::BI__sync_xor_and_fetch_8:
5137   case Builtin::BI__sync_xor_and_fetch_16:
5138     BuiltinIndex = 10;
5139     break;
5140 
5141   case Builtin::BI__sync_nand_and_fetch:
5142   case Builtin::BI__sync_nand_and_fetch_1:
5143   case Builtin::BI__sync_nand_and_fetch_2:
5144   case Builtin::BI__sync_nand_and_fetch_4:
5145   case Builtin::BI__sync_nand_and_fetch_8:
5146   case Builtin::BI__sync_nand_and_fetch_16:
5147     BuiltinIndex = 11;
5148     WarnAboutSemanticsChange = true;
5149     break;
5150 
5151   case Builtin::BI__sync_val_compare_and_swap:
5152   case Builtin::BI__sync_val_compare_and_swap_1:
5153   case Builtin::BI__sync_val_compare_and_swap_2:
5154   case Builtin::BI__sync_val_compare_and_swap_4:
5155   case Builtin::BI__sync_val_compare_and_swap_8:
5156   case Builtin::BI__sync_val_compare_and_swap_16:
5157     BuiltinIndex = 12;
5158     NumFixed = 2;
5159     break;
5160 
5161   case Builtin::BI__sync_bool_compare_and_swap:
5162   case Builtin::BI__sync_bool_compare_and_swap_1:
5163   case Builtin::BI__sync_bool_compare_and_swap_2:
5164   case Builtin::BI__sync_bool_compare_and_swap_4:
5165   case Builtin::BI__sync_bool_compare_and_swap_8:
5166   case Builtin::BI__sync_bool_compare_and_swap_16:
5167     BuiltinIndex = 13;
5168     NumFixed = 2;
5169     ResultType = Context.BoolTy;
5170     break;
5171 
5172   case Builtin::BI__sync_lock_test_and_set:
5173   case Builtin::BI__sync_lock_test_and_set_1:
5174   case Builtin::BI__sync_lock_test_and_set_2:
5175   case Builtin::BI__sync_lock_test_and_set_4:
5176   case Builtin::BI__sync_lock_test_and_set_8:
5177   case Builtin::BI__sync_lock_test_and_set_16:
5178     BuiltinIndex = 14;
5179     break;
5180 
5181   case Builtin::BI__sync_lock_release:
5182   case Builtin::BI__sync_lock_release_1:
5183   case Builtin::BI__sync_lock_release_2:
5184   case Builtin::BI__sync_lock_release_4:
5185   case Builtin::BI__sync_lock_release_8:
5186   case Builtin::BI__sync_lock_release_16:
5187     BuiltinIndex = 15;
5188     NumFixed = 0;
5189     ResultType = Context.VoidTy;
5190     break;
5191 
5192   case Builtin::BI__sync_swap:
5193   case Builtin::BI__sync_swap_1:
5194   case Builtin::BI__sync_swap_2:
5195   case Builtin::BI__sync_swap_4:
5196   case Builtin::BI__sync_swap_8:
5197   case Builtin::BI__sync_swap_16:
5198     BuiltinIndex = 16;
5199     break;
5200   }
5201 
5202   // Now that we know how many fixed arguments we expect, first check that we
5203   // have at least that many.
5204   if (TheCall->getNumArgs() < 1+NumFixed) {
5205     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5206         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5207         << Callee->getSourceRange();
5208     return ExprError();
5209   }
5210 
5211   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5212       << Callee->getSourceRange();
5213 
5214   if (WarnAboutSemanticsChange) {
5215     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5216         << Callee->getSourceRange();
5217   }
5218 
5219   // Get the decl for the concrete builtin from this, we can tell what the
5220   // concrete integer type we should convert to is.
5221   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5222   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5223   FunctionDecl *NewBuiltinDecl;
5224   if (NewBuiltinID == BuiltinID)
5225     NewBuiltinDecl = FDecl;
5226   else {
5227     // Perform builtin lookup to avoid redeclaring it.
5228     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5229     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5230     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5231     assert(Res.getFoundDecl());
5232     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5233     if (!NewBuiltinDecl)
5234       return ExprError();
5235   }
5236 
5237   // The first argument --- the pointer --- has a fixed type; we
5238   // deduce the types of the rest of the arguments accordingly.  Walk
5239   // the remaining arguments, converting them to the deduced value type.
5240   for (unsigned i = 0; i != NumFixed; ++i) {
5241     ExprResult Arg = TheCall->getArg(i+1);
5242 
5243     // GCC does an implicit conversion to the pointer or integer ValType.  This
5244     // can fail in some cases (1i -> int**), check for this error case now.
5245     // Initialize the argument.
5246     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5247                                                    ValType, /*consume*/ false);
5248     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5249     if (Arg.isInvalid())
5250       return ExprError();
5251 
5252     // Okay, we have something that *can* be converted to the right type.  Check
5253     // to see if there is a potentially weird extension going on here.  This can
5254     // happen when you do an atomic operation on something like an char* and
5255     // pass in 42.  The 42 gets converted to char.  This is even more strange
5256     // for things like 45.123 -> char, etc.
5257     // FIXME: Do this check.
5258     TheCall->setArg(i+1, Arg.get());
5259   }
5260 
5261   // Create a new DeclRefExpr to refer to the new decl.
5262   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5263       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5264       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5265       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5266 
5267   // Set the callee in the CallExpr.
5268   // FIXME: This loses syntactic information.
5269   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5270   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5271                                               CK_BuiltinFnToFnPtr);
5272   TheCall->setCallee(PromotedCall.get());
5273 
5274   // Change the result type of the call to match the original value type. This
5275   // is arbitrary, but the codegen for these builtins ins design to handle it
5276   // gracefully.
5277   TheCall->setType(ResultType);
5278 
5279   return TheCallResult;
5280 }
5281 
5282 /// SemaBuiltinNontemporalOverloaded - We have a call to
5283 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5284 /// overloaded function based on the pointer type of its last argument.
5285 ///
5286 /// This function goes through and does final semantic checking for these
5287 /// builtins.
5288 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5289   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5290   DeclRefExpr *DRE =
5291       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5292   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5293   unsigned BuiltinID = FDecl->getBuiltinID();
5294   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5295           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5296          "Unexpected nontemporal load/store builtin!");
5297   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5298   unsigned numArgs = isStore ? 2 : 1;
5299 
5300   // Ensure that we have the proper number of arguments.
5301   if (checkArgCount(*this, TheCall, numArgs))
5302     return ExprError();
5303 
5304   // Inspect the last argument of the nontemporal builtin.  This should always
5305   // be a pointer type, from which we imply the type of the memory access.
5306   // Because it is a pointer type, we don't have to worry about any implicit
5307   // casts here.
5308   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5309   ExprResult PointerArgResult =
5310       DefaultFunctionArrayLvalueConversion(PointerArg);
5311 
5312   if (PointerArgResult.isInvalid())
5313     return ExprError();
5314   PointerArg = PointerArgResult.get();
5315   TheCall->setArg(numArgs - 1, PointerArg);
5316 
5317   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5318   if (!pointerType) {
5319     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5320         << PointerArg->getType() << PointerArg->getSourceRange();
5321     return ExprError();
5322   }
5323 
5324   QualType ValType = pointerType->getPointeeType();
5325 
5326   // Strip any qualifiers off ValType.
5327   ValType = ValType.getUnqualifiedType();
5328   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5329       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5330       !ValType->isVectorType()) {
5331     Diag(DRE->getBeginLoc(),
5332          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5333         << PointerArg->getType() << PointerArg->getSourceRange();
5334     return ExprError();
5335   }
5336 
5337   if (!isStore) {
5338     TheCall->setType(ValType);
5339     return TheCallResult;
5340   }
5341 
5342   ExprResult ValArg = TheCall->getArg(0);
5343   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5344       Context, ValType, /*consume*/ false);
5345   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5346   if (ValArg.isInvalid())
5347     return ExprError();
5348 
5349   TheCall->setArg(0, ValArg.get());
5350   TheCall->setType(Context.VoidTy);
5351   return TheCallResult;
5352 }
5353 
5354 /// CheckObjCString - Checks that the argument to the builtin
5355 /// CFString constructor is correct
5356 /// Note: It might also make sense to do the UTF-16 conversion here (would
5357 /// simplify the backend).
5358 bool Sema::CheckObjCString(Expr *Arg) {
5359   Arg = Arg->IgnoreParenCasts();
5360   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5361 
5362   if (!Literal || !Literal->isAscii()) {
5363     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5364         << Arg->getSourceRange();
5365     return true;
5366   }
5367 
5368   if (Literal->containsNonAsciiOrNull()) {
5369     StringRef String = Literal->getString();
5370     unsigned NumBytes = String.size();
5371     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5372     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5373     llvm::UTF16 *ToPtr = &ToBuf[0];
5374 
5375     llvm::ConversionResult Result =
5376         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5377                                  ToPtr + NumBytes, llvm::strictConversion);
5378     // Check for conversion failure.
5379     if (Result != llvm::conversionOK)
5380       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5381           << Arg->getSourceRange();
5382   }
5383   return false;
5384 }
5385 
5386 /// CheckObjCString - Checks that the format string argument to the os_log()
5387 /// and os_trace() functions is correct, and converts it to const char *.
5388 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5389   Arg = Arg->IgnoreParenCasts();
5390   auto *Literal = dyn_cast<StringLiteral>(Arg);
5391   if (!Literal) {
5392     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5393       Literal = ObjcLiteral->getString();
5394     }
5395   }
5396 
5397   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5398     return ExprError(
5399         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5400         << Arg->getSourceRange());
5401   }
5402 
5403   ExprResult Result(Literal);
5404   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5405   InitializedEntity Entity =
5406       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5407   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5408   return Result;
5409 }
5410 
5411 /// Check that the user is calling the appropriate va_start builtin for the
5412 /// target and calling convention.
5413 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5414   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5415   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5416   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5417                     TT.getArch() == llvm::Triple::aarch64_32);
5418   bool IsWindows = TT.isOSWindows();
5419   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5420   if (IsX64 || IsAArch64) {
5421     CallingConv CC = CC_C;
5422     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5423       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5424     if (IsMSVAStart) {
5425       // Don't allow this in System V ABI functions.
5426       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5427         return S.Diag(Fn->getBeginLoc(),
5428                       diag::err_ms_va_start_used_in_sysv_function);
5429     } else {
5430       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5431       // On x64 Windows, don't allow this in System V ABI functions.
5432       // (Yes, that means there's no corresponding way to support variadic
5433       // System V ABI functions on Windows.)
5434       if ((IsWindows && CC == CC_X86_64SysV) ||
5435           (!IsWindows && CC == CC_Win64))
5436         return S.Diag(Fn->getBeginLoc(),
5437                       diag::err_va_start_used_in_wrong_abi_function)
5438                << !IsWindows;
5439     }
5440     return false;
5441   }
5442 
5443   if (IsMSVAStart)
5444     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5445   return false;
5446 }
5447 
5448 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5449                                              ParmVarDecl **LastParam = nullptr) {
5450   // Determine whether the current function, block, or obj-c method is variadic
5451   // and get its parameter list.
5452   bool IsVariadic = false;
5453   ArrayRef<ParmVarDecl *> Params;
5454   DeclContext *Caller = S.CurContext;
5455   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5456     IsVariadic = Block->isVariadic();
5457     Params = Block->parameters();
5458   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5459     IsVariadic = FD->isVariadic();
5460     Params = FD->parameters();
5461   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5462     IsVariadic = MD->isVariadic();
5463     // FIXME: This isn't correct for methods (results in bogus warning).
5464     Params = MD->parameters();
5465   } else if (isa<CapturedDecl>(Caller)) {
5466     // We don't support va_start in a CapturedDecl.
5467     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5468     return true;
5469   } else {
5470     // This must be some other declcontext that parses exprs.
5471     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5472     return true;
5473   }
5474 
5475   if (!IsVariadic) {
5476     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5477     return true;
5478   }
5479 
5480   if (LastParam)
5481     *LastParam = Params.empty() ? nullptr : Params.back();
5482 
5483   return false;
5484 }
5485 
5486 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5487 /// for validity.  Emit an error and return true on failure; return false
5488 /// on success.
5489 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5490   Expr *Fn = TheCall->getCallee();
5491 
5492   if (checkVAStartABI(*this, BuiltinID, Fn))
5493     return true;
5494 
5495   if (TheCall->getNumArgs() > 2) {
5496     Diag(TheCall->getArg(2)->getBeginLoc(),
5497          diag::err_typecheck_call_too_many_args)
5498         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5499         << Fn->getSourceRange()
5500         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5501                        (*(TheCall->arg_end() - 1))->getEndLoc());
5502     return true;
5503   }
5504 
5505   if (TheCall->getNumArgs() < 2) {
5506     return Diag(TheCall->getEndLoc(),
5507                 diag::err_typecheck_call_too_few_args_at_least)
5508            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5509   }
5510 
5511   // Type-check the first argument normally.
5512   if (checkBuiltinArgument(*this, TheCall, 0))
5513     return true;
5514 
5515   // Check that the current function is variadic, and get its last parameter.
5516   ParmVarDecl *LastParam;
5517   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5518     return true;
5519 
5520   // Verify that the second argument to the builtin is the last argument of the
5521   // current function or method.
5522   bool SecondArgIsLastNamedArgument = false;
5523   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5524 
5525   // These are valid if SecondArgIsLastNamedArgument is false after the next
5526   // block.
5527   QualType Type;
5528   SourceLocation ParamLoc;
5529   bool IsCRegister = false;
5530 
5531   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5532     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5533       SecondArgIsLastNamedArgument = PV == LastParam;
5534 
5535       Type = PV->getType();
5536       ParamLoc = PV->getLocation();
5537       IsCRegister =
5538           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5539     }
5540   }
5541 
5542   if (!SecondArgIsLastNamedArgument)
5543     Diag(TheCall->getArg(1)->getBeginLoc(),
5544          diag::warn_second_arg_of_va_start_not_last_named_param);
5545   else if (IsCRegister || Type->isReferenceType() ||
5546            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5547              // Promotable integers are UB, but enumerations need a bit of
5548              // extra checking to see what their promotable type actually is.
5549              if (!Type->isPromotableIntegerType())
5550                return false;
5551              if (!Type->isEnumeralType())
5552                return true;
5553              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5554              return !(ED &&
5555                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5556            }()) {
5557     unsigned Reason = 0;
5558     if (Type->isReferenceType())  Reason = 1;
5559     else if (IsCRegister)         Reason = 2;
5560     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5561     Diag(ParamLoc, diag::note_parameter_type) << Type;
5562   }
5563 
5564   TheCall->setType(Context.VoidTy);
5565   return false;
5566 }
5567 
5568 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5569   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5570   //                 const char *named_addr);
5571 
5572   Expr *Func = Call->getCallee();
5573 
5574   if (Call->getNumArgs() < 3)
5575     return Diag(Call->getEndLoc(),
5576                 diag::err_typecheck_call_too_few_args_at_least)
5577            << 0 /*function call*/ << 3 << Call->getNumArgs();
5578 
5579   // Type-check the first argument normally.
5580   if (checkBuiltinArgument(*this, Call, 0))
5581     return true;
5582 
5583   // Check that the current function is variadic.
5584   if (checkVAStartIsInVariadicFunction(*this, Func))
5585     return true;
5586 
5587   // __va_start on Windows does not validate the parameter qualifiers
5588 
5589   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5590   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5591 
5592   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5593   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5594 
5595   const QualType &ConstCharPtrTy =
5596       Context.getPointerType(Context.CharTy.withConst());
5597   if (!Arg1Ty->isPointerType() ||
5598       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5599     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5600         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5601         << 0                                      /* qualifier difference */
5602         << 3                                      /* parameter mismatch */
5603         << 2 << Arg1->getType() << ConstCharPtrTy;
5604 
5605   const QualType SizeTy = Context.getSizeType();
5606   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5607     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5608         << Arg2->getType() << SizeTy << 1 /* different class */
5609         << 0                              /* qualifier difference */
5610         << 3                              /* parameter mismatch */
5611         << 3 << Arg2->getType() << SizeTy;
5612 
5613   return false;
5614 }
5615 
5616 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5617 /// friends.  This is declared to take (...), so we have to check everything.
5618 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5619   if (TheCall->getNumArgs() < 2)
5620     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5621            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5622   if (TheCall->getNumArgs() > 2)
5623     return Diag(TheCall->getArg(2)->getBeginLoc(),
5624                 diag::err_typecheck_call_too_many_args)
5625            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5626            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5627                           (*(TheCall->arg_end() - 1))->getEndLoc());
5628 
5629   ExprResult OrigArg0 = TheCall->getArg(0);
5630   ExprResult OrigArg1 = TheCall->getArg(1);
5631 
5632   // Do standard promotions between the two arguments, returning their common
5633   // type.
5634   QualType Res = UsualArithmeticConversions(
5635       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5636   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5637     return true;
5638 
5639   // Make sure any conversions are pushed back into the call; this is
5640   // type safe since unordered compare builtins are declared as "_Bool
5641   // foo(...)".
5642   TheCall->setArg(0, OrigArg0.get());
5643   TheCall->setArg(1, OrigArg1.get());
5644 
5645   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5646     return false;
5647 
5648   // If the common type isn't a real floating type, then the arguments were
5649   // invalid for this operation.
5650   if (Res.isNull() || !Res->isRealFloatingType())
5651     return Diag(OrigArg0.get()->getBeginLoc(),
5652                 diag::err_typecheck_call_invalid_ordered_compare)
5653            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5654            << SourceRange(OrigArg0.get()->getBeginLoc(),
5655                           OrigArg1.get()->getEndLoc());
5656 
5657   return false;
5658 }
5659 
5660 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5661 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5662 /// to check everything. We expect the last argument to be a floating point
5663 /// value.
5664 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5665   if (TheCall->getNumArgs() < NumArgs)
5666     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5667            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5668   if (TheCall->getNumArgs() > NumArgs)
5669     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5670                 diag::err_typecheck_call_too_many_args)
5671            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5672            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5673                           (*(TheCall->arg_end() - 1))->getEndLoc());
5674 
5675   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5676   // on all preceding parameters just being int.  Try all of those.
5677   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5678     Expr *Arg = TheCall->getArg(i);
5679 
5680     if (Arg->isTypeDependent())
5681       return false;
5682 
5683     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5684 
5685     if (Res.isInvalid())
5686       return true;
5687     TheCall->setArg(i, Res.get());
5688   }
5689 
5690   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5691 
5692   if (OrigArg->isTypeDependent())
5693     return false;
5694 
5695   // Usual Unary Conversions will convert half to float, which we want for
5696   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5697   // type how it is, but do normal L->Rvalue conversions.
5698   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5699     OrigArg = UsualUnaryConversions(OrigArg).get();
5700   else
5701     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5702   TheCall->setArg(NumArgs - 1, OrigArg);
5703 
5704   // This operation requires a non-_Complex floating-point number.
5705   if (!OrigArg->getType()->isRealFloatingType())
5706     return Diag(OrigArg->getBeginLoc(),
5707                 diag::err_typecheck_call_invalid_unary_fp)
5708            << OrigArg->getType() << OrigArg->getSourceRange();
5709 
5710   return false;
5711 }
5712 
5713 // Customized Sema Checking for VSX builtins that have the following signature:
5714 // vector [...] builtinName(vector [...], vector [...], const int);
5715 // Which takes the same type of vectors (any legal vector type) for the first
5716 // two arguments and takes compile time constant for the third argument.
5717 // Example builtins are :
5718 // vector double vec_xxpermdi(vector double, vector double, int);
5719 // vector short vec_xxsldwi(vector short, vector short, int);
5720 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5721   unsigned ExpectedNumArgs = 3;
5722   if (TheCall->getNumArgs() < ExpectedNumArgs)
5723     return Diag(TheCall->getEndLoc(),
5724                 diag::err_typecheck_call_too_few_args_at_least)
5725            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5726            << TheCall->getSourceRange();
5727 
5728   if (TheCall->getNumArgs() > ExpectedNumArgs)
5729     return Diag(TheCall->getEndLoc(),
5730                 diag::err_typecheck_call_too_many_args_at_most)
5731            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5732            << TheCall->getSourceRange();
5733 
5734   // Check the third argument is a compile time constant
5735   llvm::APSInt Value;
5736   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5737     return Diag(TheCall->getBeginLoc(),
5738                 diag::err_vsx_builtin_nonconstant_argument)
5739            << 3 /* argument index */ << TheCall->getDirectCallee()
5740            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5741                           TheCall->getArg(2)->getEndLoc());
5742 
5743   QualType Arg1Ty = TheCall->getArg(0)->getType();
5744   QualType Arg2Ty = TheCall->getArg(1)->getType();
5745 
5746   // Check the type of argument 1 and argument 2 are vectors.
5747   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5748   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5749       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5750     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5751            << TheCall->getDirectCallee()
5752            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5753                           TheCall->getArg(1)->getEndLoc());
5754   }
5755 
5756   // Check the first two arguments are the same type.
5757   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5758     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5759            << TheCall->getDirectCallee()
5760            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5761                           TheCall->getArg(1)->getEndLoc());
5762   }
5763 
5764   // When default clang type checking is turned off and the customized type
5765   // checking is used, the returning type of the function must be explicitly
5766   // set. Otherwise it is _Bool by default.
5767   TheCall->setType(Arg1Ty);
5768 
5769   return false;
5770 }
5771 
5772 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5773 // This is declared to take (...), so we have to check everything.
5774 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5775   if (TheCall->getNumArgs() < 2)
5776     return ExprError(Diag(TheCall->getEndLoc(),
5777                           diag::err_typecheck_call_too_few_args_at_least)
5778                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5779                      << TheCall->getSourceRange());
5780 
5781   // Determine which of the following types of shufflevector we're checking:
5782   // 1) unary, vector mask: (lhs, mask)
5783   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5784   QualType resType = TheCall->getArg(0)->getType();
5785   unsigned numElements = 0;
5786 
5787   if (!TheCall->getArg(0)->isTypeDependent() &&
5788       !TheCall->getArg(1)->isTypeDependent()) {
5789     QualType LHSType = TheCall->getArg(0)->getType();
5790     QualType RHSType = TheCall->getArg(1)->getType();
5791 
5792     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5793       return ExprError(
5794           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5795           << TheCall->getDirectCallee()
5796           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5797                          TheCall->getArg(1)->getEndLoc()));
5798 
5799     numElements = LHSType->castAs<VectorType>()->getNumElements();
5800     unsigned numResElements = TheCall->getNumArgs() - 2;
5801 
5802     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5803     // with mask.  If so, verify that RHS is an integer vector type with the
5804     // same number of elts as lhs.
5805     if (TheCall->getNumArgs() == 2) {
5806       if (!RHSType->hasIntegerRepresentation() ||
5807           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5808         return ExprError(Diag(TheCall->getBeginLoc(),
5809                               diag::err_vec_builtin_incompatible_vector)
5810                          << TheCall->getDirectCallee()
5811                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5812                                         TheCall->getArg(1)->getEndLoc()));
5813     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5814       return ExprError(Diag(TheCall->getBeginLoc(),
5815                             diag::err_vec_builtin_incompatible_vector)
5816                        << TheCall->getDirectCallee()
5817                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5818                                       TheCall->getArg(1)->getEndLoc()));
5819     } else if (numElements != numResElements) {
5820       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5821       resType = Context.getVectorType(eltType, numResElements,
5822                                       VectorType::GenericVector);
5823     }
5824   }
5825 
5826   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5827     if (TheCall->getArg(i)->isTypeDependent() ||
5828         TheCall->getArg(i)->isValueDependent())
5829       continue;
5830 
5831     llvm::APSInt Result(32);
5832     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5833       return ExprError(Diag(TheCall->getBeginLoc(),
5834                             diag::err_shufflevector_nonconstant_argument)
5835                        << TheCall->getArg(i)->getSourceRange());
5836 
5837     // Allow -1 which will be translated to undef in the IR.
5838     if (Result.isSigned() && Result.isAllOnesValue())
5839       continue;
5840 
5841     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5842       return ExprError(Diag(TheCall->getBeginLoc(),
5843                             diag::err_shufflevector_argument_too_large)
5844                        << TheCall->getArg(i)->getSourceRange());
5845   }
5846 
5847   SmallVector<Expr*, 32> exprs;
5848 
5849   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5850     exprs.push_back(TheCall->getArg(i));
5851     TheCall->setArg(i, nullptr);
5852   }
5853 
5854   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5855                                          TheCall->getCallee()->getBeginLoc(),
5856                                          TheCall->getRParenLoc());
5857 }
5858 
5859 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5860 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5861                                        SourceLocation BuiltinLoc,
5862                                        SourceLocation RParenLoc) {
5863   ExprValueKind VK = VK_RValue;
5864   ExprObjectKind OK = OK_Ordinary;
5865   QualType DstTy = TInfo->getType();
5866   QualType SrcTy = E->getType();
5867 
5868   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5869     return ExprError(Diag(BuiltinLoc,
5870                           diag::err_convertvector_non_vector)
5871                      << E->getSourceRange());
5872   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5873     return ExprError(Diag(BuiltinLoc,
5874                           diag::err_convertvector_non_vector_type));
5875 
5876   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5877     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5878     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5879     if (SrcElts != DstElts)
5880       return ExprError(Diag(BuiltinLoc,
5881                             diag::err_convertvector_incompatible_vector)
5882                        << E->getSourceRange());
5883   }
5884 
5885   return new (Context)
5886       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5887 }
5888 
5889 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5890 // This is declared to take (const void*, ...) and can take two
5891 // optional constant int args.
5892 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5893   unsigned NumArgs = TheCall->getNumArgs();
5894 
5895   if (NumArgs > 3)
5896     return Diag(TheCall->getEndLoc(),
5897                 diag::err_typecheck_call_too_many_args_at_most)
5898            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5899 
5900   // Argument 0 is checked for us and the remaining arguments must be
5901   // constant integers.
5902   for (unsigned i = 1; i != NumArgs; ++i)
5903     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5904       return true;
5905 
5906   return false;
5907 }
5908 
5909 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5910 // __assume does not evaluate its arguments, and should warn if its argument
5911 // has side effects.
5912 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5913   Expr *Arg = TheCall->getArg(0);
5914   if (Arg->isInstantiationDependent()) return false;
5915 
5916   if (Arg->HasSideEffects(Context))
5917     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5918         << Arg->getSourceRange()
5919         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5920 
5921   return false;
5922 }
5923 
5924 /// Handle __builtin_alloca_with_align. This is declared
5925 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5926 /// than 8.
5927 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5928   // The alignment must be a constant integer.
5929   Expr *Arg = TheCall->getArg(1);
5930 
5931   // We can't check the value of a dependent argument.
5932   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5933     if (const auto *UE =
5934             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5935       if (UE->getKind() == UETT_AlignOf ||
5936           UE->getKind() == UETT_PreferredAlignOf)
5937         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5938             << Arg->getSourceRange();
5939 
5940     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5941 
5942     if (!Result.isPowerOf2())
5943       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5944              << Arg->getSourceRange();
5945 
5946     if (Result < Context.getCharWidth())
5947       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5948              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5949 
5950     if (Result > std::numeric_limits<int32_t>::max())
5951       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5952              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5953   }
5954 
5955   return false;
5956 }
5957 
5958 /// Handle __builtin_assume_aligned. This is declared
5959 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5960 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5961   unsigned NumArgs = TheCall->getNumArgs();
5962 
5963   if (NumArgs > 3)
5964     return Diag(TheCall->getEndLoc(),
5965                 diag::err_typecheck_call_too_many_args_at_most)
5966            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5967 
5968   // The alignment must be a constant integer.
5969   Expr *Arg = TheCall->getArg(1);
5970 
5971   // We can't check the value of a dependent argument.
5972   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5973     llvm::APSInt Result;
5974     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5975       return true;
5976 
5977     if (!Result.isPowerOf2())
5978       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5979              << Arg->getSourceRange();
5980 
5981     if (Result > Sema::MaximumAlignment)
5982       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5983           << Arg->getSourceRange() << Sema::MaximumAlignment;
5984   }
5985 
5986   if (NumArgs > 2) {
5987     ExprResult Arg(TheCall->getArg(2));
5988     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5989       Context.getSizeType(), false);
5990     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5991     if (Arg.isInvalid()) return true;
5992     TheCall->setArg(2, Arg.get());
5993   }
5994 
5995   return false;
5996 }
5997 
5998 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5999   unsigned BuiltinID =
6000       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6001   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6002 
6003   unsigned NumArgs = TheCall->getNumArgs();
6004   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6005   if (NumArgs < NumRequiredArgs) {
6006     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6007            << 0 /* function call */ << NumRequiredArgs << NumArgs
6008            << TheCall->getSourceRange();
6009   }
6010   if (NumArgs >= NumRequiredArgs + 0x100) {
6011     return Diag(TheCall->getEndLoc(),
6012                 diag::err_typecheck_call_too_many_args_at_most)
6013            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6014            << TheCall->getSourceRange();
6015   }
6016   unsigned i = 0;
6017 
6018   // For formatting call, check buffer arg.
6019   if (!IsSizeCall) {
6020     ExprResult Arg(TheCall->getArg(i));
6021     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6022         Context, Context.VoidPtrTy, false);
6023     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6024     if (Arg.isInvalid())
6025       return true;
6026     TheCall->setArg(i, Arg.get());
6027     i++;
6028   }
6029 
6030   // Check string literal arg.
6031   unsigned FormatIdx = i;
6032   {
6033     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6034     if (Arg.isInvalid())
6035       return true;
6036     TheCall->setArg(i, Arg.get());
6037     i++;
6038   }
6039 
6040   // Make sure variadic args are scalar.
6041   unsigned FirstDataArg = i;
6042   while (i < NumArgs) {
6043     ExprResult Arg = DefaultVariadicArgumentPromotion(
6044         TheCall->getArg(i), VariadicFunction, nullptr);
6045     if (Arg.isInvalid())
6046       return true;
6047     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6048     if (ArgSize.getQuantity() >= 0x100) {
6049       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6050              << i << (int)ArgSize.getQuantity() << 0xff
6051              << TheCall->getSourceRange();
6052     }
6053     TheCall->setArg(i, Arg.get());
6054     i++;
6055   }
6056 
6057   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6058   // call to avoid duplicate diagnostics.
6059   if (!IsSizeCall) {
6060     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6061     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6062     bool Success = CheckFormatArguments(
6063         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6064         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6065         CheckedVarArgs);
6066     if (!Success)
6067       return true;
6068   }
6069 
6070   if (IsSizeCall) {
6071     TheCall->setType(Context.getSizeType());
6072   } else {
6073     TheCall->setType(Context.VoidPtrTy);
6074   }
6075   return false;
6076 }
6077 
6078 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6079 /// TheCall is a constant expression.
6080 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6081                                   llvm::APSInt &Result) {
6082   Expr *Arg = TheCall->getArg(ArgNum);
6083   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6084   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6085 
6086   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6087 
6088   if (!Arg->isIntegerConstantExpr(Result, Context))
6089     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6090            << FDecl->getDeclName() << Arg->getSourceRange();
6091 
6092   return false;
6093 }
6094 
6095 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6096 /// TheCall is a constant expression in the range [Low, High].
6097 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6098                                        int Low, int High, bool RangeIsError) {
6099   if (isConstantEvaluated())
6100     return false;
6101   llvm::APSInt Result;
6102 
6103   // We can't check the value of a dependent argument.
6104   Expr *Arg = TheCall->getArg(ArgNum);
6105   if (Arg->isTypeDependent() || Arg->isValueDependent())
6106     return false;
6107 
6108   // Check constant-ness first.
6109   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6110     return true;
6111 
6112   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6113     if (RangeIsError)
6114       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6115              << Result.toString(10) << Low << High << Arg->getSourceRange();
6116     else
6117       // Defer the warning until we know if the code will be emitted so that
6118       // dead code can ignore this.
6119       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6120                           PDiag(diag::warn_argument_invalid_range)
6121                               << Result.toString(10) << Low << High
6122                               << Arg->getSourceRange());
6123   }
6124 
6125   return false;
6126 }
6127 
6128 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6129 /// TheCall is a constant expression is a multiple of Num..
6130 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6131                                           unsigned Num) {
6132   llvm::APSInt Result;
6133 
6134   // We can't check the value of a dependent argument.
6135   Expr *Arg = TheCall->getArg(ArgNum);
6136   if (Arg->isTypeDependent() || Arg->isValueDependent())
6137     return false;
6138 
6139   // Check constant-ness first.
6140   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6141     return true;
6142 
6143   if (Result.getSExtValue() % Num != 0)
6144     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6145            << Num << Arg->getSourceRange();
6146 
6147   return false;
6148 }
6149 
6150 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6151 /// constant expression representing a power of 2.
6152 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6153   llvm::APSInt Result;
6154 
6155   // We can't check the value of a dependent argument.
6156   Expr *Arg = TheCall->getArg(ArgNum);
6157   if (Arg->isTypeDependent() || Arg->isValueDependent())
6158     return false;
6159 
6160   // Check constant-ness first.
6161   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6162     return true;
6163 
6164   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6165   // and only if x is a power of 2.
6166   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6167     return false;
6168 
6169   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6170          << Arg->getSourceRange();
6171 }
6172 
6173 static bool IsShiftedByte(llvm::APSInt Value) {
6174   if (Value.isNegative())
6175     return false;
6176 
6177   // Check if it's a shifted byte, by shifting it down
6178   while (true) {
6179     // If the value fits in the bottom byte, the check passes.
6180     if (Value < 0x100)
6181       return true;
6182 
6183     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6184     // fails.
6185     if ((Value & 0xFF) != 0)
6186       return false;
6187 
6188     // If the bottom 8 bits are all 0, but something above that is nonzero,
6189     // then shifting the value right by 8 bits won't affect whether it's a
6190     // shifted byte or not. So do that, and go round again.
6191     Value >>= 8;
6192   }
6193 }
6194 
6195 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6196 /// a constant expression representing an arbitrary byte value shifted left by
6197 /// a multiple of 8 bits.
6198 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6199                                              unsigned ArgBits) {
6200   llvm::APSInt Result;
6201 
6202   // We can't check the value of a dependent argument.
6203   Expr *Arg = TheCall->getArg(ArgNum);
6204   if (Arg->isTypeDependent() || Arg->isValueDependent())
6205     return false;
6206 
6207   // Check constant-ness first.
6208   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6209     return true;
6210 
6211   // Truncate to the given size.
6212   Result = Result.getLoBits(ArgBits);
6213   Result.setIsUnsigned(true);
6214 
6215   if (IsShiftedByte(Result))
6216     return false;
6217 
6218   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6219          << Arg->getSourceRange();
6220 }
6221 
6222 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6223 /// TheCall is a constant expression representing either a shifted byte value,
6224 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6225 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6226 /// Arm MVE intrinsics.
6227 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6228                                                    int ArgNum,
6229                                                    unsigned ArgBits) {
6230   llvm::APSInt Result;
6231 
6232   // We can't check the value of a dependent argument.
6233   Expr *Arg = TheCall->getArg(ArgNum);
6234   if (Arg->isTypeDependent() || Arg->isValueDependent())
6235     return false;
6236 
6237   // Check constant-ness first.
6238   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6239     return true;
6240 
6241   // Truncate to the given size.
6242   Result = Result.getLoBits(ArgBits);
6243   Result.setIsUnsigned(true);
6244 
6245   // Check to see if it's in either of the required forms.
6246   if (IsShiftedByte(Result) ||
6247       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6248     return false;
6249 
6250   return Diag(TheCall->getBeginLoc(),
6251               diag::err_argument_not_shifted_byte_or_xxff)
6252          << Arg->getSourceRange();
6253 }
6254 
6255 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6256 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6257   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6258     if (checkArgCount(*this, TheCall, 2))
6259       return true;
6260     Expr *Arg0 = TheCall->getArg(0);
6261     Expr *Arg1 = TheCall->getArg(1);
6262 
6263     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6264     if (FirstArg.isInvalid())
6265       return true;
6266     QualType FirstArgType = FirstArg.get()->getType();
6267     if (!FirstArgType->isAnyPointerType())
6268       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6269                << "first" << FirstArgType << Arg0->getSourceRange();
6270     TheCall->setArg(0, FirstArg.get());
6271 
6272     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6273     if (SecArg.isInvalid())
6274       return true;
6275     QualType SecArgType = SecArg.get()->getType();
6276     if (!SecArgType->isIntegerType())
6277       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6278                << "second" << SecArgType << Arg1->getSourceRange();
6279 
6280     // Derive the return type from the pointer argument.
6281     TheCall->setType(FirstArgType);
6282     return false;
6283   }
6284 
6285   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6286     if (checkArgCount(*this, TheCall, 2))
6287       return true;
6288 
6289     Expr *Arg0 = TheCall->getArg(0);
6290     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6291     if (FirstArg.isInvalid())
6292       return true;
6293     QualType FirstArgType = FirstArg.get()->getType();
6294     if (!FirstArgType->isAnyPointerType())
6295       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6296                << "first" << FirstArgType << Arg0->getSourceRange();
6297     TheCall->setArg(0, FirstArg.get());
6298 
6299     // Derive the return type from the pointer argument.
6300     TheCall->setType(FirstArgType);
6301 
6302     // Second arg must be an constant in range [0,15]
6303     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6304   }
6305 
6306   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6307     if (checkArgCount(*this, TheCall, 2))
6308       return true;
6309     Expr *Arg0 = TheCall->getArg(0);
6310     Expr *Arg1 = TheCall->getArg(1);
6311 
6312     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6313     if (FirstArg.isInvalid())
6314       return true;
6315     QualType FirstArgType = FirstArg.get()->getType();
6316     if (!FirstArgType->isAnyPointerType())
6317       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6318                << "first" << FirstArgType << Arg0->getSourceRange();
6319 
6320     QualType SecArgType = Arg1->getType();
6321     if (!SecArgType->isIntegerType())
6322       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6323                << "second" << SecArgType << Arg1->getSourceRange();
6324     TheCall->setType(Context.IntTy);
6325     return false;
6326   }
6327 
6328   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6329       BuiltinID == AArch64::BI__builtin_arm_stg) {
6330     if (checkArgCount(*this, TheCall, 1))
6331       return true;
6332     Expr *Arg0 = TheCall->getArg(0);
6333     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6334     if (FirstArg.isInvalid())
6335       return true;
6336 
6337     QualType FirstArgType = FirstArg.get()->getType();
6338     if (!FirstArgType->isAnyPointerType())
6339       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6340                << "first" << FirstArgType << Arg0->getSourceRange();
6341     TheCall->setArg(0, FirstArg.get());
6342 
6343     // Derive the return type from the pointer argument.
6344     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6345       TheCall->setType(FirstArgType);
6346     return false;
6347   }
6348 
6349   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6350     Expr *ArgA = TheCall->getArg(0);
6351     Expr *ArgB = TheCall->getArg(1);
6352 
6353     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6354     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6355 
6356     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6357       return true;
6358 
6359     QualType ArgTypeA = ArgExprA.get()->getType();
6360     QualType ArgTypeB = ArgExprB.get()->getType();
6361 
6362     auto isNull = [&] (Expr *E) -> bool {
6363       return E->isNullPointerConstant(
6364                         Context, Expr::NPC_ValueDependentIsNotNull); };
6365 
6366     // argument should be either a pointer or null
6367     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6368       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6369         << "first" << ArgTypeA << ArgA->getSourceRange();
6370 
6371     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6372       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6373         << "second" << ArgTypeB << ArgB->getSourceRange();
6374 
6375     // Ensure Pointee types are compatible
6376     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6377         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6378       QualType pointeeA = ArgTypeA->getPointeeType();
6379       QualType pointeeB = ArgTypeB->getPointeeType();
6380       if (!Context.typesAreCompatible(
6381              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6382              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6383         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6384           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6385           << ArgB->getSourceRange();
6386       }
6387     }
6388 
6389     // at least one argument should be pointer type
6390     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6391       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6392         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6393 
6394     if (isNull(ArgA)) // adopt type of the other pointer
6395       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6396 
6397     if (isNull(ArgB))
6398       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6399 
6400     TheCall->setArg(0, ArgExprA.get());
6401     TheCall->setArg(1, ArgExprB.get());
6402     TheCall->setType(Context.LongLongTy);
6403     return false;
6404   }
6405   assert(false && "Unhandled ARM MTE intrinsic");
6406   return true;
6407 }
6408 
6409 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6410 /// TheCall is an ARM/AArch64 special register string literal.
6411 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6412                                     int ArgNum, unsigned ExpectedFieldNum,
6413                                     bool AllowName) {
6414   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6415                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6416                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6417                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6418                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6419                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6420   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6421                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6422                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6423                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6424                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6425                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6426   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6427 
6428   // We can't check the value of a dependent argument.
6429   Expr *Arg = TheCall->getArg(ArgNum);
6430   if (Arg->isTypeDependent() || Arg->isValueDependent())
6431     return false;
6432 
6433   // Check if the argument is a string literal.
6434   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6435     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6436            << Arg->getSourceRange();
6437 
6438   // Check the type of special register given.
6439   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6440   SmallVector<StringRef, 6> Fields;
6441   Reg.split(Fields, ":");
6442 
6443   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6444     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6445            << Arg->getSourceRange();
6446 
6447   // If the string is the name of a register then we cannot check that it is
6448   // valid here but if the string is of one the forms described in ACLE then we
6449   // can check that the supplied fields are integers and within the valid
6450   // ranges.
6451   if (Fields.size() > 1) {
6452     bool FiveFields = Fields.size() == 5;
6453 
6454     bool ValidString = true;
6455     if (IsARMBuiltin) {
6456       ValidString &= Fields[0].startswith_lower("cp") ||
6457                      Fields[0].startswith_lower("p");
6458       if (ValidString)
6459         Fields[0] =
6460           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6461 
6462       ValidString &= Fields[2].startswith_lower("c");
6463       if (ValidString)
6464         Fields[2] = Fields[2].drop_front(1);
6465 
6466       if (FiveFields) {
6467         ValidString &= Fields[3].startswith_lower("c");
6468         if (ValidString)
6469           Fields[3] = Fields[3].drop_front(1);
6470       }
6471     }
6472 
6473     SmallVector<int, 5> Ranges;
6474     if (FiveFields)
6475       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6476     else
6477       Ranges.append({15, 7, 15});
6478 
6479     for (unsigned i=0; i<Fields.size(); ++i) {
6480       int IntField;
6481       ValidString &= !Fields[i].getAsInteger(10, IntField);
6482       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6483     }
6484 
6485     if (!ValidString)
6486       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6487              << Arg->getSourceRange();
6488   } else if (IsAArch64Builtin && Fields.size() == 1) {
6489     // If the register name is one of those that appear in the condition below
6490     // and the special register builtin being used is one of the write builtins,
6491     // then we require that the argument provided for writing to the register
6492     // is an integer constant expression. This is because it will be lowered to
6493     // an MSR (immediate) instruction, so we need to know the immediate at
6494     // compile time.
6495     if (TheCall->getNumArgs() != 2)
6496       return false;
6497 
6498     std::string RegLower = Reg.lower();
6499     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6500         RegLower != "pan" && RegLower != "uao")
6501       return false;
6502 
6503     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6504   }
6505 
6506   return false;
6507 }
6508 
6509 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6510 /// This checks that the target supports __builtin_longjmp and
6511 /// that val is a constant 1.
6512 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6513   if (!Context.getTargetInfo().hasSjLjLowering())
6514     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6515            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6516 
6517   Expr *Arg = TheCall->getArg(1);
6518   llvm::APSInt Result;
6519 
6520   // TODO: This is less than ideal. Overload this to take a value.
6521   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6522     return true;
6523 
6524   if (Result != 1)
6525     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6526            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6527 
6528   return false;
6529 }
6530 
6531 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6532 /// This checks that the target supports __builtin_setjmp.
6533 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6534   if (!Context.getTargetInfo().hasSjLjLowering())
6535     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6536            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6537   return false;
6538 }
6539 
6540 namespace {
6541 
6542 class UncoveredArgHandler {
6543   enum { Unknown = -1, AllCovered = -2 };
6544 
6545   signed FirstUncoveredArg = Unknown;
6546   SmallVector<const Expr *, 4> DiagnosticExprs;
6547 
6548 public:
6549   UncoveredArgHandler() = default;
6550 
6551   bool hasUncoveredArg() const {
6552     return (FirstUncoveredArg >= 0);
6553   }
6554 
6555   unsigned getUncoveredArg() const {
6556     assert(hasUncoveredArg() && "no uncovered argument");
6557     return FirstUncoveredArg;
6558   }
6559 
6560   void setAllCovered() {
6561     // A string has been found with all arguments covered, so clear out
6562     // the diagnostics.
6563     DiagnosticExprs.clear();
6564     FirstUncoveredArg = AllCovered;
6565   }
6566 
6567   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6568     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6569 
6570     // Don't update if a previous string covers all arguments.
6571     if (FirstUncoveredArg == AllCovered)
6572       return;
6573 
6574     // UncoveredArgHandler tracks the highest uncovered argument index
6575     // and with it all the strings that match this index.
6576     if (NewFirstUncoveredArg == FirstUncoveredArg)
6577       DiagnosticExprs.push_back(StrExpr);
6578     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6579       DiagnosticExprs.clear();
6580       DiagnosticExprs.push_back(StrExpr);
6581       FirstUncoveredArg = NewFirstUncoveredArg;
6582     }
6583   }
6584 
6585   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6586 };
6587 
6588 enum StringLiteralCheckType {
6589   SLCT_NotALiteral,
6590   SLCT_UncheckedLiteral,
6591   SLCT_CheckedLiteral
6592 };
6593 
6594 } // namespace
6595 
6596 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6597                                      BinaryOperatorKind BinOpKind,
6598                                      bool AddendIsRight) {
6599   unsigned BitWidth = Offset.getBitWidth();
6600   unsigned AddendBitWidth = Addend.getBitWidth();
6601   // There might be negative interim results.
6602   if (Addend.isUnsigned()) {
6603     Addend = Addend.zext(++AddendBitWidth);
6604     Addend.setIsSigned(true);
6605   }
6606   // Adjust the bit width of the APSInts.
6607   if (AddendBitWidth > BitWidth) {
6608     Offset = Offset.sext(AddendBitWidth);
6609     BitWidth = AddendBitWidth;
6610   } else if (BitWidth > AddendBitWidth) {
6611     Addend = Addend.sext(BitWidth);
6612   }
6613 
6614   bool Ov = false;
6615   llvm::APSInt ResOffset = Offset;
6616   if (BinOpKind == BO_Add)
6617     ResOffset = Offset.sadd_ov(Addend, Ov);
6618   else {
6619     assert(AddendIsRight && BinOpKind == BO_Sub &&
6620            "operator must be add or sub with addend on the right");
6621     ResOffset = Offset.ssub_ov(Addend, Ov);
6622   }
6623 
6624   // We add an offset to a pointer here so we should support an offset as big as
6625   // possible.
6626   if (Ov) {
6627     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6628            "index (intermediate) result too big");
6629     Offset = Offset.sext(2 * BitWidth);
6630     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6631     return;
6632   }
6633 
6634   Offset = ResOffset;
6635 }
6636 
6637 namespace {
6638 
6639 // This is a wrapper class around StringLiteral to support offsetted string
6640 // literals as format strings. It takes the offset into account when returning
6641 // the string and its length or the source locations to display notes correctly.
6642 class FormatStringLiteral {
6643   const StringLiteral *FExpr;
6644   int64_t Offset;
6645 
6646  public:
6647   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6648       : FExpr(fexpr), Offset(Offset) {}
6649 
6650   StringRef getString() const {
6651     return FExpr->getString().drop_front(Offset);
6652   }
6653 
6654   unsigned getByteLength() const {
6655     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6656   }
6657 
6658   unsigned getLength() const { return FExpr->getLength() - Offset; }
6659   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6660 
6661   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6662 
6663   QualType getType() const { return FExpr->getType(); }
6664 
6665   bool isAscii() const { return FExpr->isAscii(); }
6666   bool isWide() const { return FExpr->isWide(); }
6667   bool isUTF8() const { return FExpr->isUTF8(); }
6668   bool isUTF16() const { return FExpr->isUTF16(); }
6669   bool isUTF32() const { return FExpr->isUTF32(); }
6670   bool isPascal() const { return FExpr->isPascal(); }
6671 
6672   SourceLocation getLocationOfByte(
6673       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6674       const TargetInfo &Target, unsigned *StartToken = nullptr,
6675       unsigned *StartTokenByteOffset = nullptr) const {
6676     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6677                                     StartToken, StartTokenByteOffset);
6678   }
6679 
6680   SourceLocation getBeginLoc() const LLVM_READONLY {
6681     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6682   }
6683 
6684   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6685 };
6686 
6687 }  // namespace
6688 
6689 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6690                               const Expr *OrigFormatExpr,
6691                               ArrayRef<const Expr *> Args,
6692                               bool HasVAListArg, unsigned format_idx,
6693                               unsigned firstDataArg,
6694                               Sema::FormatStringType Type,
6695                               bool inFunctionCall,
6696                               Sema::VariadicCallType CallType,
6697                               llvm::SmallBitVector &CheckedVarArgs,
6698                               UncoveredArgHandler &UncoveredArg,
6699                               bool IgnoreStringsWithoutSpecifiers);
6700 
6701 // Determine if an expression is a string literal or constant string.
6702 // If this function returns false on the arguments to a function expecting a
6703 // format string, we will usually need to emit a warning.
6704 // True string literals are then checked by CheckFormatString.
6705 static StringLiteralCheckType
6706 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6707                       bool HasVAListArg, unsigned format_idx,
6708                       unsigned firstDataArg, Sema::FormatStringType Type,
6709                       Sema::VariadicCallType CallType, bool InFunctionCall,
6710                       llvm::SmallBitVector &CheckedVarArgs,
6711                       UncoveredArgHandler &UncoveredArg,
6712                       llvm::APSInt Offset,
6713                       bool IgnoreStringsWithoutSpecifiers = false) {
6714   if (S.isConstantEvaluated())
6715     return SLCT_NotALiteral;
6716  tryAgain:
6717   assert(Offset.isSigned() && "invalid offset");
6718 
6719   if (E->isTypeDependent() || E->isValueDependent())
6720     return SLCT_NotALiteral;
6721 
6722   E = E->IgnoreParenCasts();
6723 
6724   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6725     // Technically -Wformat-nonliteral does not warn about this case.
6726     // The behavior of printf and friends in this case is implementation
6727     // dependent.  Ideally if the format string cannot be null then
6728     // it should have a 'nonnull' attribute in the function prototype.
6729     return SLCT_UncheckedLiteral;
6730 
6731   switch (E->getStmtClass()) {
6732   case Stmt::BinaryConditionalOperatorClass:
6733   case Stmt::ConditionalOperatorClass: {
6734     // The expression is a literal if both sub-expressions were, and it was
6735     // completely checked only if both sub-expressions were checked.
6736     const AbstractConditionalOperator *C =
6737         cast<AbstractConditionalOperator>(E);
6738 
6739     // Determine whether it is necessary to check both sub-expressions, for
6740     // example, because the condition expression is a constant that can be
6741     // evaluated at compile time.
6742     bool CheckLeft = true, CheckRight = true;
6743 
6744     bool Cond;
6745     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6746                                                  S.isConstantEvaluated())) {
6747       if (Cond)
6748         CheckRight = false;
6749       else
6750         CheckLeft = false;
6751     }
6752 
6753     // We need to maintain the offsets for the right and the left hand side
6754     // separately to check if every possible indexed expression is a valid
6755     // string literal. They might have different offsets for different string
6756     // literals in the end.
6757     StringLiteralCheckType Left;
6758     if (!CheckLeft)
6759       Left = SLCT_UncheckedLiteral;
6760     else {
6761       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6762                                    HasVAListArg, format_idx, firstDataArg,
6763                                    Type, CallType, InFunctionCall,
6764                                    CheckedVarArgs, UncoveredArg, Offset,
6765                                    IgnoreStringsWithoutSpecifiers);
6766       if (Left == SLCT_NotALiteral || !CheckRight) {
6767         return Left;
6768       }
6769     }
6770 
6771     StringLiteralCheckType Right = checkFormatStringExpr(
6772         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6773         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6774         IgnoreStringsWithoutSpecifiers);
6775 
6776     return (CheckLeft && Left < Right) ? Left : Right;
6777   }
6778 
6779   case Stmt::ImplicitCastExprClass:
6780     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6781     goto tryAgain;
6782 
6783   case Stmt::OpaqueValueExprClass:
6784     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6785       E = src;
6786       goto tryAgain;
6787     }
6788     return SLCT_NotALiteral;
6789 
6790   case Stmt::PredefinedExprClass:
6791     // While __func__, etc., are technically not string literals, they
6792     // cannot contain format specifiers and thus are not a security
6793     // liability.
6794     return SLCT_UncheckedLiteral;
6795 
6796   case Stmt::DeclRefExprClass: {
6797     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6798 
6799     // As an exception, do not flag errors for variables binding to
6800     // const string literals.
6801     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6802       bool isConstant = false;
6803       QualType T = DR->getType();
6804 
6805       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6806         isConstant = AT->getElementType().isConstant(S.Context);
6807       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6808         isConstant = T.isConstant(S.Context) &&
6809                      PT->getPointeeType().isConstant(S.Context);
6810       } else if (T->isObjCObjectPointerType()) {
6811         // In ObjC, there is usually no "const ObjectPointer" type,
6812         // so don't check if the pointee type is constant.
6813         isConstant = T.isConstant(S.Context);
6814       }
6815 
6816       if (isConstant) {
6817         if (const Expr *Init = VD->getAnyInitializer()) {
6818           // Look through initializers like const char c[] = { "foo" }
6819           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6820             if (InitList->isStringLiteralInit())
6821               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6822           }
6823           return checkFormatStringExpr(S, Init, Args,
6824                                        HasVAListArg, format_idx,
6825                                        firstDataArg, Type, CallType,
6826                                        /*InFunctionCall*/ false, CheckedVarArgs,
6827                                        UncoveredArg, Offset);
6828         }
6829       }
6830 
6831       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6832       // special check to see if the format string is a function parameter
6833       // of the function calling the printf function.  If the function
6834       // has an attribute indicating it is a printf-like function, then we
6835       // should suppress warnings concerning non-literals being used in a call
6836       // to a vprintf function.  For example:
6837       //
6838       // void
6839       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6840       //      va_list ap;
6841       //      va_start(ap, fmt);
6842       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6843       //      ...
6844       // }
6845       if (HasVAListArg) {
6846         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6847           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6848             int PVIndex = PV->getFunctionScopeIndex() + 1;
6849             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6850               // adjust for implicit parameter
6851               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6852                 if (MD->isInstance())
6853                   ++PVIndex;
6854               // We also check if the formats are compatible.
6855               // We can't pass a 'scanf' string to a 'printf' function.
6856               if (PVIndex == PVFormat->getFormatIdx() &&
6857                   Type == S.GetFormatStringType(PVFormat))
6858                 return SLCT_UncheckedLiteral;
6859             }
6860           }
6861         }
6862       }
6863     }
6864 
6865     return SLCT_NotALiteral;
6866   }
6867 
6868   case Stmt::CallExprClass:
6869   case Stmt::CXXMemberCallExprClass: {
6870     const CallExpr *CE = cast<CallExpr>(E);
6871     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6872       bool IsFirst = true;
6873       StringLiteralCheckType CommonResult;
6874       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6875         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6876         StringLiteralCheckType Result = checkFormatStringExpr(
6877             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6878             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6879             IgnoreStringsWithoutSpecifiers);
6880         if (IsFirst) {
6881           CommonResult = Result;
6882           IsFirst = false;
6883         }
6884       }
6885       if (!IsFirst)
6886         return CommonResult;
6887 
6888       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6889         unsigned BuiltinID = FD->getBuiltinID();
6890         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6891             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6892           const Expr *Arg = CE->getArg(0);
6893           return checkFormatStringExpr(S, Arg, Args,
6894                                        HasVAListArg, format_idx,
6895                                        firstDataArg, Type, CallType,
6896                                        InFunctionCall, CheckedVarArgs,
6897                                        UncoveredArg, Offset,
6898                                        IgnoreStringsWithoutSpecifiers);
6899         }
6900       }
6901     }
6902 
6903     return SLCT_NotALiteral;
6904   }
6905   case Stmt::ObjCMessageExprClass: {
6906     const auto *ME = cast<ObjCMessageExpr>(E);
6907     if (const auto *MD = ME->getMethodDecl()) {
6908       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6909         // As a special case heuristic, if we're using the method -[NSBundle
6910         // localizedStringForKey:value:table:], ignore any key strings that lack
6911         // format specifiers. The idea is that if the key doesn't have any
6912         // format specifiers then its probably just a key to map to the
6913         // localized strings. If it does have format specifiers though, then its
6914         // likely that the text of the key is the format string in the
6915         // programmer's language, and should be checked.
6916         const ObjCInterfaceDecl *IFace;
6917         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6918             IFace->getIdentifier()->isStr("NSBundle") &&
6919             MD->getSelector().isKeywordSelector(
6920                 {"localizedStringForKey", "value", "table"})) {
6921           IgnoreStringsWithoutSpecifiers = true;
6922         }
6923 
6924         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6925         return checkFormatStringExpr(
6926             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6927             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6928             IgnoreStringsWithoutSpecifiers);
6929       }
6930     }
6931 
6932     return SLCT_NotALiteral;
6933   }
6934   case Stmt::ObjCStringLiteralClass:
6935   case Stmt::StringLiteralClass: {
6936     const StringLiteral *StrE = nullptr;
6937 
6938     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6939       StrE = ObjCFExpr->getString();
6940     else
6941       StrE = cast<StringLiteral>(E);
6942 
6943     if (StrE) {
6944       if (Offset.isNegative() || Offset > StrE->getLength()) {
6945         // TODO: It would be better to have an explicit warning for out of
6946         // bounds literals.
6947         return SLCT_NotALiteral;
6948       }
6949       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6950       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6951                         firstDataArg, Type, InFunctionCall, CallType,
6952                         CheckedVarArgs, UncoveredArg,
6953                         IgnoreStringsWithoutSpecifiers);
6954       return SLCT_CheckedLiteral;
6955     }
6956 
6957     return SLCT_NotALiteral;
6958   }
6959   case Stmt::BinaryOperatorClass: {
6960     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6961 
6962     // A string literal + an int offset is still a string literal.
6963     if (BinOp->isAdditiveOp()) {
6964       Expr::EvalResult LResult, RResult;
6965 
6966       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6967           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6968       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6969           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6970 
6971       if (LIsInt != RIsInt) {
6972         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6973 
6974         if (LIsInt) {
6975           if (BinOpKind == BO_Add) {
6976             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6977             E = BinOp->getRHS();
6978             goto tryAgain;
6979           }
6980         } else {
6981           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6982           E = BinOp->getLHS();
6983           goto tryAgain;
6984         }
6985       }
6986     }
6987 
6988     return SLCT_NotALiteral;
6989   }
6990   case Stmt::UnaryOperatorClass: {
6991     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6992     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6993     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6994       Expr::EvalResult IndexResult;
6995       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6996                                        Expr::SE_NoSideEffects,
6997                                        S.isConstantEvaluated())) {
6998         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6999                    /*RHS is int*/ true);
7000         E = ASE->getBase();
7001         goto tryAgain;
7002       }
7003     }
7004 
7005     return SLCT_NotALiteral;
7006   }
7007 
7008   default:
7009     return SLCT_NotALiteral;
7010   }
7011 }
7012 
7013 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7014   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7015       .Case("scanf", FST_Scanf)
7016       .Cases("printf", "printf0", FST_Printf)
7017       .Cases("NSString", "CFString", FST_NSString)
7018       .Case("strftime", FST_Strftime)
7019       .Case("strfmon", FST_Strfmon)
7020       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7021       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7022       .Case("os_trace", FST_OSLog)
7023       .Case("os_log", FST_OSLog)
7024       .Default(FST_Unknown);
7025 }
7026 
7027 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7028 /// functions) for correct use of format strings.
7029 /// Returns true if a format string has been fully checked.
7030 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7031                                 ArrayRef<const Expr *> Args,
7032                                 bool IsCXXMember,
7033                                 VariadicCallType CallType,
7034                                 SourceLocation Loc, SourceRange Range,
7035                                 llvm::SmallBitVector &CheckedVarArgs) {
7036   FormatStringInfo FSI;
7037   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7038     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7039                                 FSI.FirstDataArg, GetFormatStringType(Format),
7040                                 CallType, Loc, Range, CheckedVarArgs);
7041   return false;
7042 }
7043 
7044 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7045                                 bool HasVAListArg, unsigned format_idx,
7046                                 unsigned firstDataArg, FormatStringType Type,
7047                                 VariadicCallType CallType,
7048                                 SourceLocation Loc, SourceRange Range,
7049                                 llvm::SmallBitVector &CheckedVarArgs) {
7050   // CHECK: printf/scanf-like function is called with no format string.
7051   if (format_idx >= Args.size()) {
7052     Diag(Loc, diag::warn_missing_format_string) << Range;
7053     return false;
7054   }
7055 
7056   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7057 
7058   // CHECK: format string is not a string literal.
7059   //
7060   // Dynamically generated format strings are difficult to
7061   // automatically vet at compile time.  Requiring that format strings
7062   // are string literals: (1) permits the checking of format strings by
7063   // the compiler and thereby (2) can practically remove the source of
7064   // many format string exploits.
7065 
7066   // Format string can be either ObjC string (e.g. @"%d") or
7067   // C string (e.g. "%d")
7068   // ObjC string uses the same format specifiers as C string, so we can use
7069   // the same format string checking logic for both ObjC and C strings.
7070   UncoveredArgHandler UncoveredArg;
7071   StringLiteralCheckType CT =
7072       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7073                             format_idx, firstDataArg, Type, CallType,
7074                             /*IsFunctionCall*/ true, CheckedVarArgs,
7075                             UncoveredArg,
7076                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7077 
7078   // Generate a diagnostic where an uncovered argument is detected.
7079   if (UncoveredArg.hasUncoveredArg()) {
7080     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7081     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7082     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7083   }
7084 
7085   if (CT != SLCT_NotALiteral)
7086     // Literal format string found, check done!
7087     return CT == SLCT_CheckedLiteral;
7088 
7089   // Strftime is particular as it always uses a single 'time' argument,
7090   // so it is safe to pass a non-literal string.
7091   if (Type == FST_Strftime)
7092     return false;
7093 
7094   // Do not emit diag when the string param is a macro expansion and the
7095   // format is either NSString or CFString. This is a hack to prevent
7096   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7097   // which are usually used in place of NS and CF string literals.
7098   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7099   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7100     return false;
7101 
7102   // If there are no arguments specified, warn with -Wformat-security, otherwise
7103   // warn only with -Wformat-nonliteral.
7104   if (Args.size() == firstDataArg) {
7105     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7106       << OrigFormatExpr->getSourceRange();
7107     switch (Type) {
7108     default:
7109       break;
7110     case FST_Kprintf:
7111     case FST_FreeBSDKPrintf:
7112     case FST_Printf:
7113       Diag(FormatLoc, diag::note_format_security_fixit)
7114         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7115       break;
7116     case FST_NSString:
7117       Diag(FormatLoc, diag::note_format_security_fixit)
7118         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7119       break;
7120     }
7121   } else {
7122     Diag(FormatLoc, diag::warn_format_nonliteral)
7123       << OrigFormatExpr->getSourceRange();
7124   }
7125   return false;
7126 }
7127 
7128 namespace {
7129 
7130 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7131 protected:
7132   Sema &S;
7133   const FormatStringLiteral *FExpr;
7134   const Expr *OrigFormatExpr;
7135   const Sema::FormatStringType FSType;
7136   const unsigned FirstDataArg;
7137   const unsigned NumDataArgs;
7138   const char *Beg; // Start of format string.
7139   const bool HasVAListArg;
7140   ArrayRef<const Expr *> Args;
7141   unsigned FormatIdx;
7142   llvm::SmallBitVector CoveredArgs;
7143   bool usesPositionalArgs = false;
7144   bool atFirstArg = true;
7145   bool inFunctionCall;
7146   Sema::VariadicCallType CallType;
7147   llvm::SmallBitVector &CheckedVarArgs;
7148   UncoveredArgHandler &UncoveredArg;
7149 
7150 public:
7151   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7152                      const Expr *origFormatExpr,
7153                      const Sema::FormatStringType type, unsigned firstDataArg,
7154                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7155                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7156                      bool inFunctionCall, Sema::VariadicCallType callType,
7157                      llvm::SmallBitVector &CheckedVarArgs,
7158                      UncoveredArgHandler &UncoveredArg)
7159       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7160         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7161         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7162         inFunctionCall(inFunctionCall), CallType(callType),
7163         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7164     CoveredArgs.resize(numDataArgs);
7165     CoveredArgs.reset();
7166   }
7167 
7168   void DoneProcessing();
7169 
7170   void HandleIncompleteSpecifier(const char *startSpecifier,
7171                                  unsigned specifierLen) override;
7172 
7173   void HandleInvalidLengthModifier(
7174                            const analyze_format_string::FormatSpecifier &FS,
7175                            const analyze_format_string::ConversionSpecifier &CS,
7176                            const char *startSpecifier, unsigned specifierLen,
7177                            unsigned DiagID);
7178 
7179   void HandleNonStandardLengthModifier(
7180                     const analyze_format_string::FormatSpecifier &FS,
7181                     const char *startSpecifier, unsigned specifierLen);
7182 
7183   void HandleNonStandardConversionSpecifier(
7184                     const analyze_format_string::ConversionSpecifier &CS,
7185                     const char *startSpecifier, unsigned specifierLen);
7186 
7187   void HandlePosition(const char *startPos, unsigned posLen) override;
7188 
7189   void HandleInvalidPosition(const char *startSpecifier,
7190                              unsigned specifierLen,
7191                              analyze_format_string::PositionContext p) override;
7192 
7193   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7194 
7195   void HandleNullChar(const char *nullCharacter) override;
7196 
7197   template <typename Range>
7198   static void
7199   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7200                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7201                        bool IsStringLocation, Range StringRange,
7202                        ArrayRef<FixItHint> Fixit = None);
7203 
7204 protected:
7205   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7206                                         const char *startSpec,
7207                                         unsigned specifierLen,
7208                                         const char *csStart, unsigned csLen);
7209 
7210   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7211                                          const char *startSpec,
7212                                          unsigned specifierLen);
7213 
7214   SourceRange getFormatStringRange();
7215   CharSourceRange getSpecifierRange(const char *startSpecifier,
7216                                     unsigned specifierLen);
7217   SourceLocation getLocationOfByte(const char *x);
7218 
7219   const Expr *getDataArg(unsigned i) const;
7220 
7221   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7222                     const analyze_format_string::ConversionSpecifier &CS,
7223                     const char *startSpecifier, unsigned specifierLen,
7224                     unsigned argIndex);
7225 
7226   template <typename Range>
7227   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7228                             bool IsStringLocation, Range StringRange,
7229                             ArrayRef<FixItHint> Fixit = None);
7230 };
7231 
7232 } // namespace
7233 
7234 SourceRange CheckFormatHandler::getFormatStringRange() {
7235   return OrigFormatExpr->getSourceRange();
7236 }
7237 
7238 CharSourceRange CheckFormatHandler::
7239 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7240   SourceLocation Start = getLocationOfByte(startSpecifier);
7241   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7242 
7243   // Advance the end SourceLocation by one due to half-open ranges.
7244   End = End.getLocWithOffset(1);
7245 
7246   return CharSourceRange::getCharRange(Start, End);
7247 }
7248 
7249 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7250   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7251                                   S.getLangOpts(), S.Context.getTargetInfo());
7252 }
7253 
7254 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7255                                                    unsigned specifierLen){
7256   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7257                        getLocationOfByte(startSpecifier),
7258                        /*IsStringLocation*/true,
7259                        getSpecifierRange(startSpecifier, specifierLen));
7260 }
7261 
7262 void CheckFormatHandler::HandleInvalidLengthModifier(
7263     const analyze_format_string::FormatSpecifier &FS,
7264     const analyze_format_string::ConversionSpecifier &CS,
7265     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7266   using namespace analyze_format_string;
7267 
7268   const LengthModifier &LM = FS.getLengthModifier();
7269   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7270 
7271   // See if we know how to fix this length modifier.
7272   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7273   if (FixedLM) {
7274     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7275                          getLocationOfByte(LM.getStart()),
7276                          /*IsStringLocation*/true,
7277                          getSpecifierRange(startSpecifier, specifierLen));
7278 
7279     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7280       << FixedLM->toString()
7281       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7282 
7283   } else {
7284     FixItHint Hint;
7285     if (DiagID == diag::warn_format_nonsensical_length)
7286       Hint = FixItHint::CreateRemoval(LMRange);
7287 
7288     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7289                          getLocationOfByte(LM.getStart()),
7290                          /*IsStringLocation*/true,
7291                          getSpecifierRange(startSpecifier, specifierLen),
7292                          Hint);
7293   }
7294 }
7295 
7296 void CheckFormatHandler::HandleNonStandardLengthModifier(
7297     const analyze_format_string::FormatSpecifier &FS,
7298     const char *startSpecifier, unsigned specifierLen) {
7299   using namespace analyze_format_string;
7300 
7301   const LengthModifier &LM = FS.getLengthModifier();
7302   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7303 
7304   // See if we know how to fix this length modifier.
7305   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7306   if (FixedLM) {
7307     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7308                            << LM.toString() << 0,
7309                          getLocationOfByte(LM.getStart()),
7310                          /*IsStringLocation*/true,
7311                          getSpecifierRange(startSpecifier, specifierLen));
7312 
7313     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7314       << FixedLM->toString()
7315       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7316 
7317   } else {
7318     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7319                            << LM.toString() << 0,
7320                          getLocationOfByte(LM.getStart()),
7321                          /*IsStringLocation*/true,
7322                          getSpecifierRange(startSpecifier, specifierLen));
7323   }
7324 }
7325 
7326 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7327     const analyze_format_string::ConversionSpecifier &CS,
7328     const char *startSpecifier, unsigned specifierLen) {
7329   using namespace analyze_format_string;
7330 
7331   // See if we know how to fix this conversion specifier.
7332   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7333   if (FixedCS) {
7334     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7335                           << CS.toString() << /*conversion specifier*/1,
7336                          getLocationOfByte(CS.getStart()),
7337                          /*IsStringLocation*/true,
7338                          getSpecifierRange(startSpecifier, specifierLen));
7339 
7340     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7341     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7342       << FixedCS->toString()
7343       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7344   } else {
7345     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7346                           << CS.toString() << /*conversion specifier*/1,
7347                          getLocationOfByte(CS.getStart()),
7348                          /*IsStringLocation*/true,
7349                          getSpecifierRange(startSpecifier, specifierLen));
7350   }
7351 }
7352 
7353 void CheckFormatHandler::HandlePosition(const char *startPos,
7354                                         unsigned posLen) {
7355   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7356                                getLocationOfByte(startPos),
7357                                /*IsStringLocation*/true,
7358                                getSpecifierRange(startPos, posLen));
7359 }
7360 
7361 void
7362 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7363                                      analyze_format_string::PositionContext p) {
7364   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7365                          << (unsigned) p,
7366                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7367                        getSpecifierRange(startPos, posLen));
7368 }
7369 
7370 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7371                                             unsigned posLen) {
7372   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7373                                getLocationOfByte(startPos),
7374                                /*IsStringLocation*/true,
7375                                getSpecifierRange(startPos, posLen));
7376 }
7377 
7378 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7379   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7380     // The presence of a null character is likely an error.
7381     EmitFormatDiagnostic(
7382       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7383       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7384       getFormatStringRange());
7385   }
7386 }
7387 
7388 // Note that this may return NULL if there was an error parsing or building
7389 // one of the argument expressions.
7390 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7391   return Args[FirstDataArg + i];
7392 }
7393 
7394 void CheckFormatHandler::DoneProcessing() {
7395   // Does the number of data arguments exceed the number of
7396   // format conversions in the format string?
7397   if (!HasVAListArg) {
7398       // Find any arguments that weren't covered.
7399     CoveredArgs.flip();
7400     signed notCoveredArg = CoveredArgs.find_first();
7401     if (notCoveredArg >= 0) {
7402       assert((unsigned)notCoveredArg < NumDataArgs);
7403       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7404     } else {
7405       UncoveredArg.setAllCovered();
7406     }
7407   }
7408 }
7409 
7410 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7411                                    const Expr *ArgExpr) {
7412   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7413          "Invalid state");
7414 
7415   if (!ArgExpr)
7416     return;
7417 
7418   SourceLocation Loc = ArgExpr->getBeginLoc();
7419 
7420   if (S.getSourceManager().isInSystemMacro(Loc))
7421     return;
7422 
7423   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7424   for (auto E : DiagnosticExprs)
7425     PDiag << E->getSourceRange();
7426 
7427   CheckFormatHandler::EmitFormatDiagnostic(
7428                                   S, IsFunctionCall, DiagnosticExprs[0],
7429                                   PDiag, Loc, /*IsStringLocation*/false,
7430                                   DiagnosticExprs[0]->getSourceRange());
7431 }
7432 
7433 bool
7434 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7435                                                      SourceLocation Loc,
7436                                                      const char *startSpec,
7437                                                      unsigned specifierLen,
7438                                                      const char *csStart,
7439                                                      unsigned csLen) {
7440   bool keepGoing = true;
7441   if (argIndex < NumDataArgs) {
7442     // Consider the argument coverered, even though the specifier doesn't
7443     // make sense.
7444     CoveredArgs.set(argIndex);
7445   }
7446   else {
7447     // If argIndex exceeds the number of data arguments we
7448     // don't issue a warning because that is just a cascade of warnings (and
7449     // they may have intended '%%' anyway). We don't want to continue processing
7450     // the format string after this point, however, as we will like just get
7451     // gibberish when trying to match arguments.
7452     keepGoing = false;
7453   }
7454 
7455   StringRef Specifier(csStart, csLen);
7456 
7457   // If the specifier in non-printable, it could be the first byte of a UTF-8
7458   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7459   // hex value.
7460   std::string CodePointStr;
7461   if (!llvm::sys::locale::isPrint(*csStart)) {
7462     llvm::UTF32 CodePoint;
7463     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7464     const llvm::UTF8 *E =
7465         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7466     llvm::ConversionResult Result =
7467         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7468 
7469     if (Result != llvm::conversionOK) {
7470       unsigned char FirstChar = *csStart;
7471       CodePoint = (llvm::UTF32)FirstChar;
7472     }
7473 
7474     llvm::raw_string_ostream OS(CodePointStr);
7475     if (CodePoint < 256)
7476       OS << "\\x" << llvm::format("%02x", CodePoint);
7477     else if (CodePoint <= 0xFFFF)
7478       OS << "\\u" << llvm::format("%04x", CodePoint);
7479     else
7480       OS << "\\U" << llvm::format("%08x", CodePoint);
7481     OS.flush();
7482     Specifier = CodePointStr;
7483   }
7484 
7485   EmitFormatDiagnostic(
7486       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7487       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7488 
7489   return keepGoing;
7490 }
7491 
7492 void
7493 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7494                                                       const char *startSpec,
7495                                                       unsigned specifierLen) {
7496   EmitFormatDiagnostic(
7497     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7498     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7499 }
7500 
7501 bool
7502 CheckFormatHandler::CheckNumArgs(
7503   const analyze_format_string::FormatSpecifier &FS,
7504   const analyze_format_string::ConversionSpecifier &CS,
7505   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7506 
7507   if (argIndex >= NumDataArgs) {
7508     PartialDiagnostic PDiag = FS.usesPositionalArg()
7509       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7510            << (argIndex+1) << NumDataArgs)
7511       : S.PDiag(diag::warn_printf_insufficient_data_args);
7512     EmitFormatDiagnostic(
7513       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7514       getSpecifierRange(startSpecifier, specifierLen));
7515 
7516     // Since more arguments than conversion tokens are given, by extension
7517     // all arguments are covered, so mark this as so.
7518     UncoveredArg.setAllCovered();
7519     return false;
7520   }
7521   return true;
7522 }
7523 
7524 template<typename Range>
7525 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7526                                               SourceLocation Loc,
7527                                               bool IsStringLocation,
7528                                               Range StringRange,
7529                                               ArrayRef<FixItHint> FixIt) {
7530   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7531                        Loc, IsStringLocation, StringRange, FixIt);
7532 }
7533 
7534 /// If the format string is not within the function call, emit a note
7535 /// so that the function call and string are in diagnostic messages.
7536 ///
7537 /// \param InFunctionCall if true, the format string is within the function
7538 /// call and only one diagnostic message will be produced.  Otherwise, an
7539 /// extra note will be emitted pointing to location of the format string.
7540 ///
7541 /// \param ArgumentExpr the expression that is passed as the format string
7542 /// argument in the function call.  Used for getting locations when two
7543 /// diagnostics are emitted.
7544 ///
7545 /// \param PDiag the callee should already have provided any strings for the
7546 /// diagnostic message.  This function only adds locations and fixits
7547 /// to diagnostics.
7548 ///
7549 /// \param Loc primary location for diagnostic.  If two diagnostics are
7550 /// required, one will be at Loc and a new SourceLocation will be created for
7551 /// the other one.
7552 ///
7553 /// \param IsStringLocation if true, Loc points to the format string should be
7554 /// used for the note.  Otherwise, Loc points to the argument list and will
7555 /// be used with PDiag.
7556 ///
7557 /// \param StringRange some or all of the string to highlight.  This is
7558 /// templated so it can accept either a CharSourceRange or a SourceRange.
7559 ///
7560 /// \param FixIt optional fix it hint for the format string.
7561 template <typename Range>
7562 void CheckFormatHandler::EmitFormatDiagnostic(
7563     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7564     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7565     Range StringRange, ArrayRef<FixItHint> FixIt) {
7566   if (InFunctionCall) {
7567     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7568     D << StringRange;
7569     D << FixIt;
7570   } else {
7571     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7572       << ArgumentExpr->getSourceRange();
7573 
7574     const Sema::SemaDiagnosticBuilder &Note =
7575       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7576              diag::note_format_string_defined);
7577 
7578     Note << StringRange;
7579     Note << FixIt;
7580   }
7581 }
7582 
7583 //===--- CHECK: Printf format string checking ------------------------------===//
7584 
7585 namespace {
7586 
7587 class CheckPrintfHandler : public CheckFormatHandler {
7588 public:
7589   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7590                      const Expr *origFormatExpr,
7591                      const Sema::FormatStringType type, unsigned firstDataArg,
7592                      unsigned numDataArgs, bool isObjC, const char *beg,
7593                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7594                      unsigned formatIdx, bool inFunctionCall,
7595                      Sema::VariadicCallType CallType,
7596                      llvm::SmallBitVector &CheckedVarArgs,
7597                      UncoveredArgHandler &UncoveredArg)
7598       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7599                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7600                            inFunctionCall, CallType, CheckedVarArgs,
7601                            UncoveredArg) {}
7602 
7603   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7604 
7605   /// Returns true if '%@' specifiers are allowed in the format string.
7606   bool allowsObjCArg() const {
7607     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7608            FSType == Sema::FST_OSTrace;
7609   }
7610 
7611   bool HandleInvalidPrintfConversionSpecifier(
7612                                       const analyze_printf::PrintfSpecifier &FS,
7613                                       const char *startSpecifier,
7614                                       unsigned specifierLen) override;
7615 
7616   void handleInvalidMaskType(StringRef MaskType) override;
7617 
7618   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7619                              const char *startSpecifier,
7620                              unsigned specifierLen) override;
7621   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7622                        const char *StartSpecifier,
7623                        unsigned SpecifierLen,
7624                        const Expr *E);
7625 
7626   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7627                     const char *startSpecifier, unsigned specifierLen);
7628   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7629                            const analyze_printf::OptionalAmount &Amt,
7630                            unsigned type,
7631                            const char *startSpecifier, unsigned specifierLen);
7632   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7633                   const analyze_printf::OptionalFlag &flag,
7634                   const char *startSpecifier, unsigned specifierLen);
7635   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7636                          const analyze_printf::OptionalFlag &ignoredFlag,
7637                          const analyze_printf::OptionalFlag &flag,
7638                          const char *startSpecifier, unsigned specifierLen);
7639   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7640                            const Expr *E);
7641 
7642   void HandleEmptyObjCModifierFlag(const char *startFlag,
7643                                    unsigned flagLen) override;
7644 
7645   void HandleInvalidObjCModifierFlag(const char *startFlag,
7646                                             unsigned flagLen) override;
7647 
7648   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7649                                            const char *flagsEnd,
7650                                            const char *conversionPosition)
7651                                              override;
7652 };
7653 
7654 } // namespace
7655 
7656 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7657                                       const analyze_printf::PrintfSpecifier &FS,
7658                                       const char *startSpecifier,
7659                                       unsigned specifierLen) {
7660   const analyze_printf::PrintfConversionSpecifier &CS =
7661     FS.getConversionSpecifier();
7662 
7663   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7664                                           getLocationOfByte(CS.getStart()),
7665                                           startSpecifier, specifierLen,
7666                                           CS.getStart(), CS.getLength());
7667 }
7668 
7669 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7670   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7671 }
7672 
7673 bool CheckPrintfHandler::HandleAmount(
7674                                const analyze_format_string::OptionalAmount &Amt,
7675                                unsigned k, const char *startSpecifier,
7676                                unsigned specifierLen) {
7677   if (Amt.hasDataArgument()) {
7678     if (!HasVAListArg) {
7679       unsigned argIndex = Amt.getArgIndex();
7680       if (argIndex >= NumDataArgs) {
7681         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7682                                << k,
7683                              getLocationOfByte(Amt.getStart()),
7684                              /*IsStringLocation*/true,
7685                              getSpecifierRange(startSpecifier, specifierLen));
7686         // Don't do any more checking.  We will just emit
7687         // spurious errors.
7688         return false;
7689       }
7690 
7691       // Type check the data argument.  It should be an 'int'.
7692       // Although not in conformance with C99, we also allow the argument to be
7693       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7694       // doesn't emit a warning for that case.
7695       CoveredArgs.set(argIndex);
7696       const Expr *Arg = getDataArg(argIndex);
7697       if (!Arg)
7698         return false;
7699 
7700       QualType T = Arg->getType();
7701 
7702       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7703       assert(AT.isValid());
7704 
7705       if (!AT.matchesType(S.Context, T)) {
7706         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7707                                << k << AT.getRepresentativeTypeName(S.Context)
7708                                << T << Arg->getSourceRange(),
7709                              getLocationOfByte(Amt.getStart()),
7710                              /*IsStringLocation*/true,
7711                              getSpecifierRange(startSpecifier, specifierLen));
7712         // Don't do any more checking.  We will just emit
7713         // spurious errors.
7714         return false;
7715       }
7716     }
7717   }
7718   return true;
7719 }
7720 
7721 void CheckPrintfHandler::HandleInvalidAmount(
7722                                       const analyze_printf::PrintfSpecifier &FS,
7723                                       const analyze_printf::OptionalAmount &Amt,
7724                                       unsigned type,
7725                                       const char *startSpecifier,
7726                                       unsigned specifierLen) {
7727   const analyze_printf::PrintfConversionSpecifier &CS =
7728     FS.getConversionSpecifier();
7729 
7730   FixItHint fixit =
7731     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7732       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7733                                  Amt.getConstantLength()))
7734       : FixItHint();
7735 
7736   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7737                          << type << CS.toString(),
7738                        getLocationOfByte(Amt.getStart()),
7739                        /*IsStringLocation*/true,
7740                        getSpecifierRange(startSpecifier, specifierLen),
7741                        fixit);
7742 }
7743 
7744 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7745                                     const analyze_printf::OptionalFlag &flag,
7746                                     const char *startSpecifier,
7747                                     unsigned specifierLen) {
7748   // Warn about pointless flag with a fixit removal.
7749   const analyze_printf::PrintfConversionSpecifier &CS =
7750     FS.getConversionSpecifier();
7751   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7752                          << flag.toString() << CS.toString(),
7753                        getLocationOfByte(flag.getPosition()),
7754                        /*IsStringLocation*/true,
7755                        getSpecifierRange(startSpecifier, specifierLen),
7756                        FixItHint::CreateRemoval(
7757                          getSpecifierRange(flag.getPosition(), 1)));
7758 }
7759 
7760 void CheckPrintfHandler::HandleIgnoredFlag(
7761                                 const analyze_printf::PrintfSpecifier &FS,
7762                                 const analyze_printf::OptionalFlag &ignoredFlag,
7763                                 const analyze_printf::OptionalFlag &flag,
7764                                 const char *startSpecifier,
7765                                 unsigned specifierLen) {
7766   // Warn about ignored flag with a fixit removal.
7767   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7768                          << ignoredFlag.toString() << flag.toString(),
7769                        getLocationOfByte(ignoredFlag.getPosition()),
7770                        /*IsStringLocation*/true,
7771                        getSpecifierRange(startSpecifier, specifierLen),
7772                        FixItHint::CreateRemoval(
7773                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7774 }
7775 
7776 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7777                                                      unsigned flagLen) {
7778   // Warn about an empty flag.
7779   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7780                        getLocationOfByte(startFlag),
7781                        /*IsStringLocation*/true,
7782                        getSpecifierRange(startFlag, flagLen));
7783 }
7784 
7785 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7786                                                        unsigned flagLen) {
7787   // Warn about an invalid flag.
7788   auto Range = getSpecifierRange(startFlag, flagLen);
7789   StringRef flag(startFlag, flagLen);
7790   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7791                       getLocationOfByte(startFlag),
7792                       /*IsStringLocation*/true,
7793                       Range, FixItHint::CreateRemoval(Range));
7794 }
7795 
7796 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7797     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7798     // Warn about using '[...]' without a '@' conversion.
7799     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7800     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7801     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7802                          getLocationOfByte(conversionPosition),
7803                          /*IsStringLocation*/true,
7804                          Range, FixItHint::CreateRemoval(Range));
7805 }
7806 
7807 // Determines if the specified is a C++ class or struct containing
7808 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7809 // "c_str()").
7810 template<typename MemberKind>
7811 static llvm::SmallPtrSet<MemberKind*, 1>
7812 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7813   const RecordType *RT = Ty->getAs<RecordType>();
7814   llvm::SmallPtrSet<MemberKind*, 1> Results;
7815 
7816   if (!RT)
7817     return Results;
7818   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7819   if (!RD || !RD->getDefinition())
7820     return Results;
7821 
7822   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7823                  Sema::LookupMemberName);
7824   R.suppressDiagnostics();
7825 
7826   // We just need to include all members of the right kind turned up by the
7827   // filter, at this point.
7828   if (S.LookupQualifiedName(R, RT->getDecl()))
7829     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7830       NamedDecl *decl = (*I)->getUnderlyingDecl();
7831       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7832         Results.insert(FK);
7833     }
7834   return Results;
7835 }
7836 
7837 /// Check if we could call '.c_str()' on an object.
7838 ///
7839 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7840 /// allow the call, or if it would be ambiguous).
7841 bool Sema::hasCStrMethod(const Expr *E) {
7842   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7843 
7844   MethodSet Results =
7845       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7846   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7847        MI != ME; ++MI)
7848     if ((*MI)->getMinRequiredArguments() == 0)
7849       return true;
7850   return false;
7851 }
7852 
7853 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7854 // better diagnostic if so. AT is assumed to be valid.
7855 // Returns true when a c_str() conversion method is found.
7856 bool CheckPrintfHandler::checkForCStrMembers(
7857     const analyze_printf::ArgType &AT, const Expr *E) {
7858   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7859 
7860   MethodSet Results =
7861       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7862 
7863   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7864        MI != ME; ++MI) {
7865     const CXXMethodDecl *Method = *MI;
7866     if (Method->getMinRequiredArguments() == 0 &&
7867         AT.matchesType(S.Context, Method->getReturnType())) {
7868       // FIXME: Suggest parens if the expression needs them.
7869       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7870       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7871           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7872       return true;
7873     }
7874   }
7875 
7876   return false;
7877 }
7878 
7879 bool
7880 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7881                                             &FS,
7882                                           const char *startSpecifier,
7883                                           unsigned specifierLen) {
7884   using namespace analyze_format_string;
7885   using namespace analyze_printf;
7886 
7887   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7888 
7889   if (FS.consumesDataArgument()) {
7890     if (atFirstArg) {
7891         atFirstArg = false;
7892         usesPositionalArgs = FS.usesPositionalArg();
7893     }
7894     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7895       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7896                                         startSpecifier, specifierLen);
7897       return false;
7898     }
7899   }
7900 
7901   // First check if the field width, precision, and conversion specifier
7902   // have matching data arguments.
7903   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7904                     startSpecifier, specifierLen)) {
7905     return false;
7906   }
7907 
7908   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7909                     startSpecifier, specifierLen)) {
7910     return false;
7911   }
7912 
7913   if (!CS.consumesDataArgument()) {
7914     // FIXME: Technically specifying a precision or field width here
7915     // makes no sense.  Worth issuing a warning at some point.
7916     return true;
7917   }
7918 
7919   // Consume the argument.
7920   unsigned argIndex = FS.getArgIndex();
7921   if (argIndex < NumDataArgs) {
7922     // The check to see if the argIndex is valid will come later.
7923     // We set the bit here because we may exit early from this
7924     // function if we encounter some other error.
7925     CoveredArgs.set(argIndex);
7926   }
7927 
7928   // FreeBSD kernel extensions.
7929   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7930       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7931     // We need at least two arguments.
7932     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7933       return false;
7934 
7935     // Claim the second argument.
7936     CoveredArgs.set(argIndex + 1);
7937 
7938     // Type check the first argument (int for %b, pointer for %D)
7939     const Expr *Ex = getDataArg(argIndex);
7940     const analyze_printf::ArgType &AT =
7941       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7942         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7943     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7944       EmitFormatDiagnostic(
7945           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7946               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7947               << false << Ex->getSourceRange(),
7948           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7949           getSpecifierRange(startSpecifier, specifierLen));
7950 
7951     // Type check the second argument (char * for both %b and %D)
7952     Ex = getDataArg(argIndex + 1);
7953     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7954     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7955       EmitFormatDiagnostic(
7956           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7957               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7958               << false << Ex->getSourceRange(),
7959           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7960           getSpecifierRange(startSpecifier, specifierLen));
7961 
7962      return true;
7963   }
7964 
7965   // Check for using an Objective-C specific conversion specifier
7966   // in a non-ObjC literal.
7967   if (!allowsObjCArg() && CS.isObjCArg()) {
7968     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7969                                                   specifierLen);
7970   }
7971 
7972   // %P can only be used with os_log.
7973   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7974     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7975                                                   specifierLen);
7976   }
7977 
7978   // %n is not allowed with os_log.
7979   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7980     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7981                          getLocationOfByte(CS.getStart()),
7982                          /*IsStringLocation*/ false,
7983                          getSpecifierRange(startSpecifier, specifierLen));
7984 
7985     return true;
7986   }
7987 
7988   // Only scalars are allowed for os_trace.
7989   if (FSType == Sema::FST_OSTrace &&
7990       (CS.getKind() == ConversionSpecifier::PArg ||
7991        CS.getKind() == ConversionSpecifier::sArg ||
7992        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7993     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7994                                                   specifierLen);
7995   }
7996 
7997   // Check for use of public/private annotation outside of os_log().
7998   if (FSType != Sema::FST_OSLog) {
7999     if (FS.isPublic().isSet()) {
8000       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8001                                << "public",
8002                            getLocationOfByte(FS.isPublic().getPosition()),
8003                            /*IsStringLocation*/ false,
8004                            getSpecifierRange(startSpecifier, specifierLen));
8005     }
8006     if (FS.isPrivate().isSet()) {
8007       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8008                                << "private",
8009                            getLocationOfByte(FS.isPrivate().getPosition()),
8010                            /*IsStringLocation*/ false,
8011                            getSpecifierRange(startSpecifier, specifierLen));
8012     }
8013   }
8014 
8015   // Check for invalid use of field width
8016   if (!FS.hasValidFieldWidth()) {
8017     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8018         startSpecifier, specifierLen);
8019   }
8020 
8021   // Check for invalid use of precision
8022   if (!FS.hasValidPrecision()) {
8023     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8024         startSpecifier, specifierLen);
8025   }
8026 
8027   // Precision is mandatory for %P specifier.
8028   if (CS.getKind() == ConversionSpecifier::PArg &&
8029       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8030     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8031                          getLocationOfByte(startSpecifier),
8032                          /*IsStringLocation*/ false,
8033                          getSpecifierRange(startSpecifier, specifierLen));
8034   }
8035 
8036   // Check each flag does not conflict with any other component.
8037   if (!FS.hasValidThousandsGroupingPrefix())
8038     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8039   if (!FS.hasValidLeadingZeros())
8040     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8041   if (!FS.hasValidPlusPrefix())
8042     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8043   if (!FS.hasValidSpacePrefix())
8044     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8045   if (!FS.hasValidAlternativeForm())
8046     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8047   if (!FS.hasValidLeftJustified())
8048     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8049 
8050   // Check that flags are not ignored by another flag
8051   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8052     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8053         startSpecifier, specifierLen);
8054   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8055     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8056             startSpecifier, specifierLen);
8057 
8058   // Check the length modifier is valid with the given conversion specifier.
8059   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8060                                  S.getLangOpts()))
8061     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8062                                 diag::warn_format_nonsensical_length);
8063   else if (!FS.hasStandardLengthModifier())
8064     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8065   else if (!FS.hasStandardLengthConversionCombination())
8066     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8067                                 diag::warn_format_non_standard_conversion_spec);
8068 
8069   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8070     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8071 
8072   // The remaining checks depend on the data arguments.
8073   if (HasVAListArg)
8074     return true;
8075 
8076   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8077     return false;
8078 
8079   const Expr *Arg = getDataArg(argIndex);
8080   if (!Arg)
8081     return true;
8082 
8083   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8084 }
8085 
8086 static bool requiresParensToAddCast(const Expr *E) {
8087   // FIXME: We should have a general way to reason about operator
8088   // precedence and whether parens are actually needed here.
8089   // Take care of a few common cases where they aren't.
8090   const Expr *Inside = E->IgnoreImpCasts();
8091   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8092     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8093 
8094   switch (Inside->getStmtClass()) {
8095   case Stmt::ArraySubscriptExprClass:
8096   case Stmt::CallExprClass:
8097   case Stmt::CharacterLiteralClass:
8098   case Stmt::CXXBoolLiteralExprClass:
8099   case Stmt::DeclRefExprClass:
8100   case Stmt::FloatingLiteralClass:
8101   case Stmt::IntegerLiteralClass:
8102   case Stmt::MemberExprClass:
8103   case Stmt::ObjCArrayLiteralClass:
8104   case Stmt::ObjCBoolLiteralExprClass:
8105   case Stmt::ObjCBoxedExprClass:
8106   case Stmt::ObjCDictionaryLiteralClass:
8107   case Stmt::ObjCEncodeExprClass:
8108   case Stmt::ObjCIvarRefExprClass:
8109   case Stmt::ObjCMessageExprClass:
8110   case Stmt::ObjCPropertyRefExprClass:
8111   case Stmt::ObjCStringLiteralClass:
8112   case Stmt::ObjCSubscriptRefExprClass:
8113   case Stmt::ParenExprClass:
8114   case Stmt::StringLiteralClass:
8115   case Stmt::UnaryOperatorClass:
8116     return false;
8117   default:
8118     return true;
8119   }
8120 }
8121 
8122 static std::pair<QualType, StringRef>
8123 shouldNotPrintDirectly(const ASTContext &Context,
8124                        QualType IntendedTy,
8125                        const Expr *E) {
8126   // Use a 'while' to peel off layers of typedefs.
8127   QualType TyTy = IntendedTy;
8128   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8129     StringRef Name = UserTy->getDecl()->getName();
8130     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8131       .Case("CFIndex", Context.getNSIntegerType())
8132       .Case("NSInteger", Context.getNSIntegerType())
8133       .Case("NSUInteger", Context.getNSUIntegerType())
8134       .Case("SInt32", Context.IntTy)
8135       .Case("UInt32", Context.UnsignedIntTy)
8136       .Default(QualType());
8137 
8138     if (!CastTy.isNull())
8139       return std::make_pair(CastTy, Name);
8140 
8141     TyTy = UserTy->desugar();
8142   }
8143 
8144   // Strip parens if necessary.
8145   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8146     return shouldNotPrintDirectly(Context,
8147                                   PE->getSubExpr()->getType(),
8148                                   PE->getSubExpr());
8149 
8150   // If this is a conditional expression, then its result type is constructed
8151   // via usual arithmetic conversions and thus there might be no necessary
8152   // typedef sugar there.  Recurse to operands to check for NSInteger &
8153   // Co. usage condition.
8154   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8155     QualType TrueTy, FalseTy;
8156     StringRef TrueName, FalseName;
8157 
8158     std::tie(TrueTy, TrueName) =
8159       shouldNotPrintDirectly(Context,
8160                              CO->getTrueExpr()->getType(),
8161                              CO->getTrueExpr());
8162     std::tie(FalseTy, FalseName) =
8163       shouldNotPrintDirectly(Context,
8164                              CO->getFalseExpr()->getType(),
8165                              CO->getFalseExpr());
8166 
8167     if (TrueTy == FalseTy)
8168       return std::make_pair(TrueTy, TrueName);
8169     else if (TrueTy.isNull())
8170       return std::make_pair(FalseTy, FalseName);
8171     else if (FalseTy.isNull())
8172       return std::make_pair(TrueTy, TrueName);
8173   }
8174 
8175   return std::make_pair(QualType(), StringRef());
8176 }
8177 
8178 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8179 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8180 /// type do not count.
8181 static bool
8182 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8183   QualType From = ICE->getSubExpr()->getType();
8184   QualType To = ICE->getType();
8185   // It's an integer promotion if the destination type is the promoted
8186   // source type.
8187   if (ICE->getCastKind() == CK_IntegralCast &&
8188       From->isPromotableIntegerType() &&
8189       S.Context.getPromotedIntegerType(From) == To)
8190     return true;
8191   // Look through vector types, since we do default argument promotion for
8192   // those in OpenCL.
8193   if (const auto *VecTy = From->getAs<ExtVectorType>())
8194     From = VecTy->getElementType();
8195   if (const auto *VecTy = To->getAs<ExtVectorType>())
8196     To = VecTy->getElementType();
8197   // It's a floating promotion if the source type is a lower rank.
8198   return ICE->getCastKind() == CK_FloatingCast &&
8199          S.Context.getFloatingTypeOrder(From, To) < 0;
8200 }
8201 
8202 bool
8203 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8204                                     const char *StartSpecifier,
8205                                     unsigned SpecifierLen,
8206                                     const Expr *E) {
8207   using namespace analyze_format_string;
8208   using namespace analyze_printf;
8209 
8210   // Now type check the data expression that matches the
8211   // format specifier.
8212   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8213   if (!AT.isValid())
8214     return true;
8215 
8216   QualType ExprTy = E->getType();
8217   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8218     ExprTy = TET->getUnderlyingExpr()->getType();
8219   }
8220 
8221   // Diagnose attempts to print a boolean value as a character. Unlike other
8222   // -Wformat diagnostics, this is fine from a type perspective, but it still
8223   // doesn't make sense.
8224   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8225       E->isKnownToHaveBooleanValue()) {
8226     const CharSourceRange &CSR =
8227         getSpecifierRange(StartSpecifier, SpecifierLen);
8228     SmallString<4> FSString;
8229     llvm::raw_svector_ostream os(FSString);
8230     FS.toString(os);
8231     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8232                              << FSString,
8233                          E->getExprLoc(), false, CSR);
8234     return true;
8235   }
8236 
8237   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8238   if (Match == analyze_printf::ArgType::Match)
8239     return true;
8240 
8241   // Look through argument promotions for our error message's reported type.
8242   // This includes the integral and floating promotions, but excludes array
8243   // and function pointer decay (seeing that an argument intended to be a
8244   // string has type 'char [6]' is probably more confusing than 'char *') and
8245   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8246   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8247     if (isArithmeticArgumentPromotion(S, ICE)) {
8248       E = ICE->getSubExpr();
8249       ExprTy = E->getType();
8250 
8251       // Check if we didn't match because of an implicit cast from a 'char'
8252       // or 'short' to an 'int'.  This is done because printf is a varargs
8253       // function.
8254       if (ICE->getType() == S.Context.IntTy ||
8255           ICE->getType() == S.Context.UnsignedIntTy) {
8256         // All further checking is done on the subexpression
8257         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8258             AT.matchesType(S.Context, ExprTy);
8259         if (ImplicitMatch == analyze_printf::ArgType::Match)
8260           return true;
8261         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8262             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8263           Match = ImplicitMatch;
8264       }
8265     }
8266   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8267     // Special case for 'a', which has type 'int' in C.
8268     // Note, however, that we do /not/ want to treat multibyte constants like
8269     // 'MooV' as characters! This form is deprecated but still exists.
8270     if (ExprTy == S.Context.IntTy)
8271       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8272         ExprTy = S.Context.CharTy;
8273   }
8274 
8275   // Look through enums to their underlying type.
8276   bool IsEnum = false;
8277   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8278     ExprTy = EnumTy->getDecl()->getIntegerType();
8279     IsEnum = true;
8280   }
8281 
8282   // %C in an Objective-C context prints a unichar, not a wchar_t.
8283   // If the argument is an integer of some kind, believe the %C and suggest
8284   // a cast instead of changing the conversion specifier.
8285   QualType IntendedTy = ExprTy;
8286   if (isObjCContext() &&
8287       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8288     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8289         !ExprTy->isCharType()) {
8290       // 'unichar' is defined as a typedef of unsigned short, but we should
8291       // prefer using the typedef if it is visible.
8292       IntendedTy = S.Context.UnsignedShortTy;
8293 
8294       // While we are here, check if the value is an IntegerLiteral that happens
8295       // to be within the valid range.
8296       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8297         const llvm::APInt &V = IL->getValue();
8298         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8299           return true;
8300       }
8301 
8302       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8303                           Sema::LookupOrdinaryName);
8304       if (S.LookupName(Result, S.getCurScope())) {
8305         NamedDecl *ND = Result.getFoundDecl();
8306         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8307           if (TD->getUnderlyingType() == IntendedTy)
8308             IntendedTy = S.Context.getTypedefType(TD);
8309       }
8310     }
8311   }
8312 
8313   // Special-case some of Darwin's platform-independence types by suggesting
8314   // casts to primitive types that are known to be large enough.
8315   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8316   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8317     QualType CastTy;
8318     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8319     if (!CastTy.isNull()) {
8320       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8321       // (long in ASTContext). Only complain to pedants.
8322       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8323           (AT.isSizeT() || AT.isPtrdiffT()) &&
8324           AT.matchesType(S.Context, CastTy))
8325         Match = ArgType::NoMatchPedantic;
8326       IntendedTy = CastTy;
8327       ShouldNotPrintDirectly = true;
8328     }
8329   }
8330 
8331   // We may be able to offer a FixItHint if it is a supported type.
8332   PrintfSpecifier fixedFS = FS;
8333   bool Success =
8334       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8335 
8336   if (Success) {
8337     // Get the fix string from the fixed format specifier
8338     SmallString<16> buf;
8339     llvm::raw_svector_ostream os(buf);
8340     fixedFS.toString(os);
8341 
8342     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8343 
8344     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8345       unsigned Diag;
8346       switch (Match) {
8347       case ArgType::Match: llvm_unreachable("expected non-matching");
8348       case ArgType::NoMatchPedantic:
8349         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8350         break;
8351       case ArgType::NoMatchTypeConfusion:
8352         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8353         break;
8354       case ArgType::NoMatch:
8355         Diag = diag::warn_format_conversion_argument_type_mismatch;
8356         break;
8357       }
8358 
8359       // In this case, the specifier is wrong and should be changed to match
8360       // the argument.
8361       EmitFormatDiagnostic(S.PDiag(Diag)
8362                                << AT.getRepresentativeTypeName(S.Context)
8363                                << IntendedTy << IsEnum << E->getSourceRange(),
8364                            E->getBeginLoc(),
8365                            /*IsStringLocation*/ false, SpecRange,
8366                            FixItHint::CreateReplacement(SpecRange, os.str()));
8367     } else {
8368       // The canonical type for formatting this value is different from the
8369       // actual type of the expression. (This occurs, for example, with Darwin's
8370       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8371       // should be printed as 'long' for 64-bit compatibility.)
8372       // Rather than emitting a normal format/argument mismatch, we want to
8373       // add a cast to the recommended type (and correct the format string
8374       // if necessary).
8375       SmallString<16> CastBuf;
8376       llvm::raw_svector_ostream CastFix(CastBuf);
8377       CastFix << "(";
8378       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8379       CastFix << ")";
8380 
8381       SmallVector<FixItHint,4> Hints;
8382       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8383         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8384 
8385       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8386         // If there's already a cast present, just replace it.
8387         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8388         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8389 
8390       } else if (!requiresParensToAddCast(E)) {
8391         // If the expression has high enough precedence,
8392         // just write the C-style cast.
8393         Hints.push_back(
8394             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8395       } else {
8396         // Otherwise, add parens around the expression as well as the cast.
8397         CastFix << "(";
8398         Hints.push_back(
8399             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8400 
8401         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8402         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8403       }
8404 
8405       if (ShouldNotPrintDirectly) {
8406         // The expression has a type that should not be printed directly.
8407         // We extract the name from the typedef because we don't want to show
8408         // the underlying type in the diagnostic.
8409         StringRef Name;
8410         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8411           Name = TypedefTy->getDecl()->getName();
8412         else
8413           Name = CastTyName;
8414         unsigned Diag = Match == ArgType::NoMatchPedantic
8415                             ? diag::warn_format_argument_needs_cast_pedantic
8416                             : diag::warn_format_argument_needs_cast;
8417         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8418                                            << E->getSourceRange(),
8419                              E->getBeginLoc(), /*IsStringLocation=*/false,
8420                              SpecRange, Hints);
8421       } else {
8422         // In this case, the expression could be printed using a different
8423         // specifier, but we've decided that the specifier is probably correct
8424         // and we should cast instead. Just use the normal warning message.
8425         EmitFormatDiagnostic(
8426             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8427                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8428                 << E->getSourceRange(),
8429             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8430       }
8431     }
8432   } else {
8433     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8434                                                    SpecifierLen);
8435     // Since the warning for passing non-POD types to variadic functions
8436     // was deferred until now, we emit a warning for non-POD
8437     // arguments here.
8438     switch (S.isValidVarArgType(ExprTy)) {
8439     case Sema::VAK_Valid:
8440     case Sema::VAK_ValidInCXX11: {
8441       unsigned Diag;
8442       switch (Match) {
8443       case ArgType::Match: llvm_unreachable("expected non-matching");
8444       case ArgType::NoMatchPedantic:
8445         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8446         break;
8447       case ArgType::NoMatchTypeConfusion:
8448         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8449         break;
8450       case ArgType::NoMatch:
8451         Diag = diag::warn_format_conversion_argument_type_mismatch;
8452         break;
8453       }
8454 
8455       EmitFormatDiagnostic(
8456           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8457                         << IsEnum << CSR << E->getSourceRange(),
8458           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8459       break;
8460     }
8461     case Sema::VAK_Undefined:
8462     case Sema::VAK_MSVCUndefined:
8463       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8464                                << S.getLangOpts().CPlusPlus11 << ExprTy
8465                                << CallType
8466                                << AT.getRepresentativeTypeName(S.Context) << CSR
8467                                << E->getSourceRange(),
8468                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8469       checkForCStrMembers(AT, E);
8470       break;
8471 
8472     case Sema::VAK_Invalid:
8473       if (ExprTy->isObjCObjectType())
8474         EmitFormatDiagnostic(
8475             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8476                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8477                 << AT.getRepresentativeTypeName(S.Context) << CSR
8478                 << E->getSourceRange(),
8479             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8480       else
8481         // FIXME: If this is an initializer list, suggest removing the braces
8482         // or inserting a cast to the target type.
8483         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8484             << isa<InitListExpr>(E) << ExprTy << CallType
8485             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8486       break;
8487     }
8488 
8489     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8490            "format string specifier index out of range");
8491     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8492   }
8493 
8494   return true;
8495 }
8496 
8497 //===--- CHECK: Scanf format string checking ------------------------------===//
8498 
8499 namespace {
8500 
8501 class CheckScanfHandler : public CheckFormatHandler {
8502 public:
8503   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8504                     const Expr *origFormatExpr, Sema::FormatStringType type,
8505                     unsigned firstDataArg, unsigned numDataArgs,
8506                     const char *beg, bool hasVAListArg,
8507                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8508                     bool inFunctionCall, Sema::VariadicCallType CallType,
8509                     llvm::SmallBitVector &CheckedVarArgs,
8510                     UncoveredArgHandler &UncoveredArg)
8511       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8512                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8513                            inFunctionCall, CallType, CheckedVarArgs,
8514                            UncoveredArg) {}
8515 
8516   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8517                             const char *startSpecifier,
8518                             unsigned specifierLen) override;
8519 
8520   bool HandleInvalidScanfConversionSpecifier(
8521           const analyze_scanf::ScanfSpecifier &FS,
8522           const char *startSpecifier,
8523           unsigned specifierLen) override;
8524 
8525   void HandleIncompleteScanList(const char *start, const char *end) override;
8526 };
8527 
8528 } // namespace
8529 
8530 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8531                                                  const char *end) {
8532   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8533                        getLocationOfByte(end), /*IsStringLocation*/true,
8534                        getSpecifierRange(start, end - start));
8535 }
8536 
8537 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8538                                         const analyze_scanf::ScanfSpecifier &FS,
8539                                         const char *startSpecifier,
8540                                         unsigned specifierLen) {
8541   const analyze_scanf::ScanfConversionSpecifier &CS =
8542     FS.getConversionSpecifier();
8543 
8544   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8545                                           getLocationOfByte(CS.getStart()),
8546                                           startSpecifier, specifierLen,
8547                                           CS.getStart(), CS.getLength());
8548 }
8549 
8550 bool CheckScanfHandler::HandleScanfSpecifier(
8551                                        const analyze_scanf::ScanfSpecifier &FS,
8552                                        const char *startSpecifier,
8553                                        unsigned specifierLen) {
8554   using namespace analyze_scanf;
8555   using namespace analyze_format_string;
8556 
8557   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8558 
8559   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8560   // be used to decide if we are using positional arguments consistently.
8561   if (FS.consumesDataArgument()) {
8562     if (atFirstArg) {
8563       atFirstArg = false;
8564       usesPositionalArgs = FS.usesPositionalArg();
8565     }
8566     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8567       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8568                                         startSpecifier, specifierLen);
8569       return false;
8570     }
8571   }
8572 
8573   // Check if the field with is non-zero.
8574   const OptionalAmount &Amt = FS.getFieldWidth();
8575   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8576     if (Amt.getConstantAmount() == 0) {
8577       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8578                                                    Amt.getConstantLength());
8579       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8580                            getLocationOfByte(Amt.getStart()),
8581                            /*IsStringLocation*/true, R,
8582                            FixItHint::CreateRemoval(R));
8583     }
8584   }
8585 
8586   if (!FS.consumesDataArgument()) {
8587     // FIXME: Technically specifying a precision or field width here
8588     // makes no sense.  Worth issuing a warning at some point.
8589     return true;
8590   }
8591 
8592   // Consume the argument.
8593   unsigned argIndex = FS.getArgIndex();
8594   if (argIndex < NumDataArgs) {
8595       // The check to see if the argIndex is valid will come later.
8596       // We set the bit here because we may exit early from this
8597       // function if we encounter some other error.
8598     CoveredArgs.set(argIndex);
8599   }
8600 
8601   // Check the length modifier is valid with the given conversion specifier.
8602   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8603                                  S.getLangOpts()))
8604     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8605                                 diag::warn_format_nonsensical_length);
8606   else if (!FS.hasStandardLengthModifier())
8607     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8608   else if (!FS.hasStandardLengthConversionCombination())
8609     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8610                                 diag::warn_format_non_standard_conversion_spec);
8611 
8612   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8613     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8614 
8615   // The remaining checks depend on the data arguments.
8616   if (HasVAListArg)
8617     return true;
8618 
8619   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8620     return false;
8621 
8622   // Check that the argument type matches the format specifier.
8623   const Expr *Ex = getDataArg(argIndex);
8624   if (!Ex)
8625     return true;
8626 
8627   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8628 
8629   if (!AT.isValid()) {
8630     return true;
8631   }
8632 
8633   analyze_format_string::ArgType::MatchKind Match =
8634       AT.matchesType(S.Context, Ex->getType());
8635   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8636   if (Match == analyze_format_string::ArgType::Match)
8637     return true;
8638 
8639   ScanfSpecifier fixedFS = FS;
8640   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8641                                  S.getLangOpts(), S.Context);
8642 
8643   unsigned Diag =
8644       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8645                : diag::warn_format_conversion_argument_type_mismatch;
8646 
8647   if (Success) {
8648     // Get the fix string from the fixed format specifier.
8649     SmallString<128> buf;
8650     llvm::raw_svector_ostream os(buf);
8651     fixedFS.toString(os);
8652 
8653     EmitFormatDiagnostic(
8654         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8655                       << Ex->getType() << false << Ex->getSourceRange(),
8656         Ex->getBeginLoc(),
8657         /*IsStringLocation*/ false,
8658         getSpecifierRange(startSpecifier, specifierLen),
8659         FixItHint::CreateReplacement(
8660             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8661   } else {
8662     EmitFormatDiagnostic(S.PDiag(Diag)
8663                              << AT.getRepresentativeTypeName(S.Context)
8664                              << Ex->getType() << false << Ex->getSourceRange(),
8665                          Ex->getBeginLoc(),
8666                          /*IsStringLocation*/ false,
8667                          getSpecifierRange(startSpecifier, specifierLen));
8668   }
8669 
8670   return true;
8671 }
8672 
8673 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8674                               const Expr *OrigFormatExpr,
8675                               ArrayRef<const Expr *> Args,
8676                               bool HasVAListArg, unsigned format_idx,
8677                               unsigned firstDataArg,
8678                               Sema::FormatStringType Type,
8679                               bool inFunctionCall,
8680                               Sema::VariadicCallType CallType,
8681                               llvm::SmallBitVector &CheckedVarArgs,
8682                               UncoveredArgHandler &UncoveredArg,
8683                               bool IgnoreStringsWithoutSpecifiers) {
8684   // CHECK: is the format string a wide literal?
8685   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8686     CheckFormatHandler::EmitFormatDiagnostic(
8687         S, inFunctionCall, Args[format_idx],
8688         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8689         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8690     return;
8691   }
8692 
8693   // Str - The format string.  NOTE: this is NOT null-terminated!
8694   StringRef StrRef = FExpr->getString();
8695   const char *Str = StrRef.data();
8696   // Account for cases where the string literal is truncated in a declaration.
8697   const ConstantArrayType *T =
8698     S.Context.getAsConstantArrayType(FExpr->getType());
8699   assert(T && "String literal not of constant array type!");
8700   size_t TypeSize = T->getSize().getZExtValue();
8701   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8702   const unsigned numDataArgs = Args.size() - firstDataArg;
8703 
8704   if (IgnoreStringsWithoutSpecifiers &&
8705       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8706           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8707     return;
8708 
8709   // Emit a warning if the string literal is truncated and does not contain an
8710   // embedded null character.
8711   if (TypeSize <= StrRef.size() &&
8712       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8713     CheckFormatHandler::EmitFormatDiagnostic(
8714         S, inFunctionCall, Args[format_idx],
8715         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8716         FExpr->getBeginLoc(),
8717         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8718     return;
8719   }
8720 
8721   // CHECK: empty format string?
8722   if (StrLen == 0 && numDataArgs > 0) {
8723     CheckFormatHandler::EmitFormatDiagnostic(
8724         S, inFunctionCall, Args[format_idx],
8725         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8726         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8727     return;
8728   }
8729 
8730   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8731       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8732       Type == Sema::FST_OSTrace) {
8733     CheckPrintfHandler H(
8734         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8735         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8736         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8737         CheckedVarArgs, UncoveredArg);
8738 
8739     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8740                                                   S.getLangOpts(),
8741                                                   S.Context.getTargetInfo(),
8742                                             Type == Sema::FST_FreeBSDKPrintf))
8743       H.DoneProcessing();
8744   } else if (Type == Sema::FST_Scanf) {
8745     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8746                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8747                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8748 
8749     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8750                                                  S.getLangOpts(),
8751                                                  S.Context.getTargetInfo()))
8752       H.DoneProcessing();
8753   } // TODO: handle other formats
8754 }
8755 
8756 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8757   // Str - The format string.  NOTE: this is NOT null-terminated!
8758   StringRef StrRef = FExpr->getString();
8759   const char *Str = StrRef.data();
8760   // Account for cases where the string literal is truncated in a declaration.
8761   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8762   assert(T && "String literal not of constant array type!");
8763   size_t TypeSize = T->getSize().getZExtValue();
8764   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8765   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8766                                                          getLangOpts(),
8767                                                          Context.getTargetInfo());
8768 }
8769 
8770 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8771 
8772 // Returns the related absolute value function that is larger, of 0 if one
8773 // does not exist.
8774 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8775   switch (AbsFunction) {
8776   default:
8777     return 0;
8778 
8779   case Builtin::BI__builtin_abs:
8780     return Builtin::BI__builtin_labs;
8781   case Builtin::BI__builtin_labs:
8782     return Builtin::BI__builtin_llabs;
8783   case Builtin::BI__builtin_llabs:
8784     return 0;
8785 
8786   case Builtin::BI__builtin_fabsf:
8787     return Builtin::BI__builtin_fabs;
8788   case Builtin::BI__builtin_fabs:
8789     return Builtin::BI__builtin_fabsl;
8790   case Builtin::BI__builtin_fabsl:
8791     return 0;
8792 
8793   case Builtin::BI__builtin_cabsf:
8794     return Builtin::BI__builtin_cabs;
8795   case Builtin::BI__builtin_cabs:
8796     return Builtin::BI__builtin_cabsl;
8797   case Builtin::BI__builtin_cabsl:
8798     return 0;
8799 
8800   case Builtin::BIabs:
8801     return Builtin::BIlabs;
8802   case Builtin::BIlabs:
8803     return Builtin::BIllabs;
8804   case Builtin::BIllabs:
8805     return 0;
8806 
8807   case Builtin::BIfabsf:
8808     return Builtin::BIfabs;
8809   case Builtin::BIfabs:
8810     return Builtin::BIfabsl;
8811   case Builtin::BIfabsl:
8812     return 0;
8813 
8814   case Builtin::BIcabsf:
8815    return Builtin::BIcabs;
8816   case Builtin::BIcabs:
8817     return Builtin::BIcabsl;
8818   case Builtin::BIcabsl:
8819     return 0;
8820   }
8821 }
8822 
8823 // Returns the argument type of the absolute value function.
8824 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8825                                              unsigned AbsType) {
8826   if (AbsType == 0)
8827     return QualType();
8828 
8829   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8830   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8831   if (Error != ASTContext::GE_None)
8832     return QualType();
8833 
8834   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8835   if (!FT)
8836     return QualType();
8837 
8838   if (FT->getNumParams() != 1)
8839     return QualType();
8840 
8841   return FT->getParamType(0);
8842 }
8843 
8844 // Returns the best absolute value function, or zero, based on type and
8845 // current absolute value function.
8846 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8847                                    unsigned AbsFunctionKind) {
8848   unsigned BestKind = 0;
8849   uint64_t ArgSize = Context.getTypeSize(ArgType);
8850   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8851        Kind = getLargerAbsoluteValueFunction(Kind)) {
8852     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8853     if (Context.getTypeSize(ParamType) >= ArgSize) {
8854       if (BestKind == 0)
8855         BestKind = Kind;
8856       else if (Context.hasSameType(ParamType, ArgType)) {
8857         BestKind = Kind;
8858         break;
8859       }
8860     }
8861   }
8862   return BestKind;
8863 }
8864 
8865 enum AbsoluteValueKind {
8866   AVK_Integer,
8867   AVK_Floating,
8868   AVK_Complex
8869 };
8870 
8871 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8872   if (T->isIntegralOrEnumerationType())
8873     return AVK_Integer;
8874   if (T->isRealFloatingType())
8875     return AVK_Floating;
8876   if (T->isAnyComplexType())
8877     return AVK_Complex;
8878 
8879   llvm_unreachable("Type not integer, floating, or complex");
8880 }
8881 
8882 // Changes the absolute value function to a different type.  Preserves whether
8883 // the function is a builtin.
8884 static unsigned changeAbsFunction(unsigned AbsKind,
8885                                   AbsoluteValueKind ValueKind) {
8886   switch (ValueKind) {
8887   case AVK_Integer:
8888     switch (AbsKind) {
8889     default:
8890       return 0;
8891     case Builtin::BI__builtin_fabsf:
8892     case Builtin::BI__builtin_fabs:
8893     case Builtin::BI__builtin_fabsl:
8894     case Builtin::BI__builtin_cabsf:
8895     case Builtin::BI__builtin_cabs:
8896     case Builtin::BI__builtin_cabsl:
8897       return Builtin::BI__builtin_abs;
8898     case Builtin::BIfabsf:
8899     case Builtin::BIfabs:
8900     case Builtin::BIfabsl:
8901     case Builtin::BIcabsf:
8902     case Builtin::BIcabs:
8903     case Builtin::BIcabsl:
8904       return Builtin::BIabs;
8905     }
8906   case AVK_Floating:
8907     switch (AbsKind) {
8908     default:
8909       return 0;
8910     case Builtin::BI__builtin_abs:
8911     case Builtin::BI__builtin_labs:
8912     case Builtin::BI__builtin_llabs:
8913     case Builtin::BI__builtin_cabsf:
8914     case Builtin::BI__builtin_cabs:
8915     case Builtin::BI__builtin_cabsl:
8916       return Builtin::BI__builtin_fabsf;
8917     case Builtin::BIabs:
8918     case Builtin::BIlabs:
8919     case Builtin::BIllabs:
8920     case Builtin::BIcabsf:
8921     case Builtin::BIcabs:
8922     case Builtin::BIcabsl:
8923       return Builtin::BIfabsf;
8924     }
8925   case AVK_Complex:
8926     switch (AbsKind) {
8927     default:
8928       return 0;
8929     case Builtin::BI__builtin_abs:
8930     case Builtin::BI__builtin_labs:
8931     case Builtin::BI__builtin_llabs:
8932     case Builtin::BI__builtin_fabsf:
8933     case Builtin::BI__builtin_fabs:
8934     case Builtin::BI__builtin_fabsl:
8935       return Builtin::BI__builtin_cabsf;
8936     case Builtin::BIabs:
8937     case Builtin::BIlabs:
8938     case Builtin::BIllabs:
8939     case Builtin::BIfabsf:
8940     case Builtin::BIfabs:
8941     case Builtin::BIfabsl:
8942       return Builtin::BIcabsf;
8943     }
8944   }
8945   llvm_unreachable("Unable to convert function");
8946 }
8947 
8948 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8949   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8950   if (!FnInfo)
8951     return 0;
8952 
8953   switch (FDecl->getBuiltinID()) {
8954   default:
8955     return 0;
8956   case Builtin::BI__builtin_abs:
8957   case Builtin::BI__builtin_fabs:
8958   case Builtin::BI__builtin_fabsf:
8959   case Builtin::BI__builtin_fabsl:
8960   case Builtin::BI__builtin_labs:
8961   case Builtin::BI__builtin_llabs:
8962   case Builtin::BI__builtin_cabs:
8963   case Builtin::BI__builtin_cabsf:
8964   case Builtin::BI__builtin_cabsl:
8965   case Builtin::BIabs:
8966   case Builtin::BIlabs:
8967   case Builtin::BIllabs:
8968   case Builtin::BIfabs:
8969   case Builtin::BIfabsf:
8970   case Builtin::BIfabsl:
8971   case Builtin::BIcabs:
8972   case Builtin::BIcabsf:
8973   case Builtin::BIcabsl:
8974     return FDecl->getBuiltinID();
8975   }
8976   llvm_unreachable("Unknown Builtin type");
8977 }
8978 
8979 // If the replacement is valid, emit a note with replacement function.
8980 // Additionally, suggest including the proper header if not already included.
8981 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8982                             unsigned AbsKind, QualType ArgType) {
8983   bool EmitHeaderHint = true;
8984   const char *HeaderName = nullptr;
8985   const char *FunctionName = nullptr;
8986   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8987     FunctionName = "std::abs";
8988     if (ArgType->isIntegralOrEnumerationType()) {
8989       HeaderName = "cstdlib";
8990     } else if (ArgType->isRealFloatingType()) {
8991       HeaderName = "cmath";
8992     } else {
8993       llvm_unreachable("Invalid Type");
8994     }
8995 
8996     // Lookup all std::abs
8997     if (NamespaceDecl *Std = S.getStdNamespace()) {
8998       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8999       R.suppressDiagnostics();
9000       S.LookupQualifiedName(R, Std);
9001 
9002       for (const auto *I : R) {
9003         const FunctionDecl *FDecl = nullptr;
9004         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9005           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9006         } else {
9007           FDecl = dyn_cast<FunctionDecl>(I);
9008         }
9009         if (!FDecl)
9010           continue;
9011 
9012         // Found std::abs(), check that they are the right ones.
9013         if (FDecl->getNumParams() != 1)
9014           continue;
9015 
9016         // Check that the parameter type can handle the argument.
9017         QualType ParamType = FDecl->getParamDecl(0)->getType();
9018         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9019             S.Context.getTypeSize(ArgType) <=
9020                 S.Context.getTypeSize(ParamType)) {
9021           // Found a function, don't need the header hint.
9022           EmitHeaderHint = false;
9023           break;
9024         }
9025       }
9026     }
9027   } else {
9028     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9029     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9030 
9031     if (HeaderName) {
9032       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9033       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9034       R.suppressDiagnostics();
9035       S.LookupName(R, S.getCurScope());
9036 
9037       if (R.isSingleResult()) {
9038         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9039         if (FD && FD->getBuiltinID() == AbsKind) {
9040           EmitHeaderHint = false;
9041         } else {
9042           return;
9043         }
9044       } else if (!R.empty()) {
9045         return;
9046       }
9047     }
9048   }
9049 
9050   S.Diag(Loc, diag::note_replace_abs_function)
9051       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9052 
9053   if (!HeaderName)
9054     return;
9055 
9056   if (!EmitHeaderHint)
9057     return;
9058 
9059   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9060                                                     << FunctionName;
9061 }
9062 
9063 template <std::size_t StrLen>
9064 static bool IsStdFunction(const FunctionDecl *FDecl,
9065                           const char (&Str)[StrLen]) {
9066   if (!FDecl)
9067     return false;
9068   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9069     return false;
9070   if (!FDecl->isInStdNamespace())
9071     return false;
9072 
9073   return true;
9074 }
9075 
9076 // Warn when using the wrong abs() function.
9077 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9078                                       const FunctionDecl *FDecl) {
9079   if (Call->getNumArgs() != 1)
9080     return;
9081 
9082   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9083   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9084   if (AbsKind == 0 && !IsStdAbs)
9085     return;
9086 
9087   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9088   QualType ParamType = Call->getArg(0)->getType();
9089 
9090   // Unsigned types cannot be negative.  Suggest removing the absolute value
9091   // function call.
9092   if (ArgType->isUnsignedIntegerType()) {
9093     const char *FunctionName =
9094         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9095     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9096     Diag(Call->getExprLoc(), diag::note_remove_abs)
9097         << FunctionName
9098         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9099     return;
9100   }
9101 
9102   // Taking the absolute value of a pointer is very suspicious, they probably
9103   // wanted to index into an array, dereference a pointer, call a function, etc.
9104   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9105     unsigned DiagType = 0;
9106     if (ArgType->isFunctionType())
9107       DiagType = 1;
9108     else if (ArgType->isArrayType())
9109       DiagType = 2;
9110 
9111     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9112     return;
9113   }
9114 
9115   // std::abs has overloads which prevent most of the absolute value problems
9116   // from occurring.
9117   if (IsStdAbs)
9118     return;
9119 
9120   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9121   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9122 
9123   // The argument and parameter are the same kind.  Check if they are the right
9124   // size.
9125   if (ArgValueKind == ParamValueKind) {
9126     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9127       return;
9128 
9129     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9130     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9131         << FDecl << ArgType << ParamType;
9132 
9133     if (NewAbsKind == 0)
9134       return;
9135 
9136     emitReplacement(*this, Call->getExprLoc(),
9137                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9138     return;
9139   }
9140 
9141   // ArgValueKind != ParamValueKind
9142   // The wrong type of absolute value function was used.  Attempt to find the
9143   // proper one.
9144   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9145   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9146   if (NewAbsKind == 0)
9147     return;
9148 
9149   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9150       << FDecl << ParamValueKind << ArgValueKind;
9151 
9152   emitReplacement(*this, Call->getExprLoc(),
9153                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9154 }
9155 
9156 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9157 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9158                                 const FunctionDecl *FDecl) {
9159   if (!Call || !FDecl) return;
9160 
9161   // Ignore template specializations and macros.
9162   if (inTemplateInstantiation()) return;
9163   if (Call->getExprLoc().isMacroID()) return;
9164 
9165   // Only care about the one template argument, two function parameter std::max
9166   if (Call->getNumArgs() != 2) return;
9167   if (!IsStdFunction(FDecl, "max")) return;
9168   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9169   if (!ArgList) return;
9170   if (ArgList->size() != 1) return;
9171 
9172   // Check that template type argument is unsigned integer.
9173   const auto& TA = ArgList->get(0);
9174   if (TA.getKind() != TemplateArgument::Type) return;
9175   QualType ArgType = TA.getAsType();
9176   if (!ArgType->isUnsignedIntegerType()) return;
9177 
9178   // See if either argument is a literal zero.
9179   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9180     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9181     if (!MTE) return false;
9182     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9183     if (!Num) return false;
9184     if (Num->getValue() != 0) return false;
9185     return true;
9186   };
9187 
9188   const Expr *FirstArg = Call->getArg(0);
9189   const Expr *SecondArg = Call->getArg(1);
9190   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9191   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9192 
9193   // Only warn when exactly one argument is zero.
9194   if (IsFirstArgZero == IsSecondArgZero) return;
9195 
9196   SourceRange FirstRange = FirstArg->getSourceRange();
9197   SourceRange SecondRange = SecondArg->getSourceRange();
9198 
9199   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9200 
9201   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9202       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9203 
9204   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9205   SourceRange RemovalRange;
9206   if (IsFirstArgZero) {
9207     RemovalRange = SourceRange(FirstRange.getBegin(),
9208                                SecondRange.getBegin().getLocWithOffset(-1));
9209   } else {
9210     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9211                                SecondRange.getEnd());
9212   }
9213 
9214   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9215         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9216         << FixItHint::CreateRemoval(RemovalRange);
9217 }
9218 
9219 //===--- CHECK: Standard memory functions ---------------------------------===//
9220 
9221 /// Takes the expression passed to the size_t parameter of functions
9222 /// such as memcmp, strncat, etc and warns if it's a comparison.
9223 ///
9224 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9225 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9226                                            IdentifierInfo *FnName,
9227                                            SourceLocation FnLoc,
9228                                            SourceLocation RParenLoc) {
9229   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9230   if (!Size)
9231     return false;
9232 
9233   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9234   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9235     return false;
9236 
9237   SourceRange SizeRange = Size->getSourceRange();
9238   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9239       << SizeRange << FnName;
9240   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9241       << FnName
9242       << FixItHint::CreateInsertion(
9243              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9244       << FixItHint::CreateRemoval(RParenLoc);
9245   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9246       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9247       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9248                                     ")");
9249 
9250   return true;
9251 }
9252 
9253 /// Determine whether the given type is or contains a dynamic class type
9254 /// (e.g., whether it has a vtable).
9255 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9256                                                      bool &IsContained) {
9257   // Look through array types while ignoring qualifiers.
9258   const Type *Ty = T->getBaseElementTypeUnsafe();
9259   IsContained = false;
9260 
9261   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9262   RD = RD ? RD->getDefinition() : nullptr;
9263   if (!RD || RD->isInvalidDecl())
9264     return nullptr;
9265 
9266   if (RD->isDynamicClass())
9267     return RD;
9268 
9269   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9270   // It's impossible for a class to transitively contain itself by value, so
9271   // infinite recursion is impossible.
9272   for (auto *FD : RD->fields()) {
9273     bool SubContained;
9274     if (const CXXRecordDecl *ContainedRD =
9275             getContainedDynamicClass(FD->getType(), SubContained)) {
9276       IsContained = true;
9277       return ContainedRD;
9278     }
9279   }
9280 
9281   return nullptr;
9282 }
9283 
9284 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9285   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9286     if (Unary->getKind() == UETT_SizeOf)
9287       return Unary;
9288   return nullptr;
9289 }
9290 
9291 /// If E is a sizeof expression, returns its argument expression,
9292 /// otherwise returns NULL.
9293 static const Expr *getSizeOfExprArg(const Expr *E) {
9294   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9295     if (!SizeOf->isArgumentType())
9296       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9297   return nullptr;
9298 }
9299 
9300 /// If E is a sizeof expression, returns its argument type.
9301 static QualType getSizeOfArgType(const Expr *E) {
9302   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9303     return SizeOf->getTypeOfArgument();
9304   return QualType();
9305 }
9306 
9307 namespace {
9308 
9309 struct SearchNonTrivialToInitializeField
9310     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9311   using Super =
9312       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9313 
9314   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9315 
9316   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9317                      SourceLocation SL) {
9318     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9319       asDerived().visitArray(PDIK, AT, SL);
9320       return;
9321     }
9322 
9323     Super::visitWithKind(PDIK, FT, SL);
9324   }
9325 
9326   void visitARCStrong(QualType FT, SourceLocation SL) {
9327     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9328   }
9329   void visitARCWeak(QualType FT, SourceLocation SL) {
9330     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9331   }
9332   void visitStruct(QualType FT, SourceLocation SL) {
9333     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9334       visit(FD->getType(), FD->getLocation());
9335   }
9336   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9337                   const ArrayType *AT, SourceLocation SL) {
9338     visit(getContext().getBaseElementType(AT), SL);
9339   }
9340   void visitTrivial(QualType FT, SourceLocation SL) {}
9341 
9342   static void diag(QualType RT, const Expr *E, Sema &S) {
9343     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9344   }
9345 
9346   ASTContext &getContext() { return S.getASTContext(); }
9347 
9348   const Expr *E;
9349   Sema &S;
9350 };
9351 
9352 struct SearchNonTrivialToCopyField
9353     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9354   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9355 
9356   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9357 
9358   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9359                      SourceLocation SL) {
9360     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9361       asDerived().visitArray(PCK, AT, SL);
9362       return;
9363     }
9364 
9365     Super::visitWithKind(PCK, FT, SL);
9366   }
9367 
9368   void visitARCStrong(QualType FT, SourceLocation SL) {
9369     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9370   }
9371   void visitARCWeak(QualType FT, SourceLocation SL) {
9372     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9373   }
9374   void visitStruct(QualType FT, SourceLocation SL) {
9375     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9376       visit(FD->getType(), FD->getLocation());
9377   }
9378   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9379                   SourceLocation SL) {
9380     visit(getContext().getBaseElementType(AT), SL);
9381   }
9382   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9383                 SourceLocation SL) {}
9384   void visitTrivial(QualType FT, SourceLocation SL) {}
9385   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9386 
9387   static void diag(QualType RT, const Expr *E, Sema &S) {
9388     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9389   }
9390 
9391   ASTContext &getContext() { return S.getASTContext(); }
9392 
9393   const Expr *E;
9394   Sema &S;
9395 };
9396 
9397 }
9398 
9399 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9400 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9401   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9402 
9403   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9404     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9405       return false;
9406 
9407     return doesExprLikelyComputeSize(BO->getLHS()) ||
9408            doesExprLikelyComputeSize(BO->getRHS());
9409   }
9410 
9411   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9412 }
9413 
9414 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9415 ///
9416 /// \code
9417 ///   #define MACRO 0
9418 ///   foo(MACRO);
9419 ///   foo(0);
9420 /// \endcode
9421 ///
9422 /// This should return true for the first call to foo, but not for the second
9423 /// (regardless of whether foo is a macro or function).
9424 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9425                                         SourceLocation CallLoc,
9426                                         SourceLocation ArgLoc) {
9427   if (!CallLoc.isMacroID())
9428     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9429 
9430   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9431          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9432 }
9433 
9434 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9435 /// last two arguments transposed.
9436 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9437   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9438     return;
9439 
9440   const Expr *SizeArg =
9441     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9442 
9443   auto isLiteralZero = [](const Expr *E) {
9444     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9445   };
9446 
9447   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9448   SourceLocation CallLoc = Call->getRParenLoc();
9449   SourceManager &SM = S.getSourceManager();
9450   if (isLiteralZero(SizeArg) &&
9451       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9452 
9453     SourceLocation DiagLoc = SizeArg->getExprLoc();
9454 
9455     // Some platforms #define bzero to __builtin_memset. See if this is the
9456     // case, and if so, emit a better diagnostic.
9457     if (BId == Builtin::BIbzero ||
9458         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9459                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9460       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9461       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9462     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9463       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9464       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9465     }
9466     return;
9467   }
9468 
9469   // If the second argument to a memset is a sizeof expression and the third
9470   // isn't, this is also likely an error. This should catch
9471   // 'memset(buf, sizeof(buf), 0xff)'.
9472   if (BId == Builtin::BImemset &&
9473       doesExprLikelyComputeSize(Call->getArg(1)) &&
9474       !doesExprLikelyComputeSize(Call->getArg(2))) {
9475     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9476     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9477     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9478     return;
9479   }
9480 }
9481 
9482 /// Check for dangerous or invalid arguments to memset().
9483 ///
9484 /// This issues warnings on known problematic, dangerous or unspecified
9485 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9486 /// function calls.
9487 ///
9488 /// \param Call The call expression to diagnose.
9489 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9490                                    unsigned BId,
9491                                    IdentifierInfo *FnName) {
9492   assert(BId != 0);
9493 
9494   // It is possible to have a non-standard definition of memset.  Validate
9495   // we have enough arguments, and if not, abort further checking.
9496   unsigned ExpectedNumArgs =
9497       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9498   if (Call->getNumArgs() < ExpectedNumArgs)
9499     return;
9500 
9501   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9502                       BId == Builtin::BIstrndup ? 1 : 2);
9503   unsigned LenArg =
9504       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9505   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9506 
9507   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9508                                      Call->getBeginLoc(), Call->getRParenLoc()))
9509     return;
9510 
9511   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9512   CheckMemaccessSize(*this, BId, Call);
9513 
9514   // We have special checking when the length is a sizeof expression.
9515   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9516   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9517   llvm::FoldingSetNodeID SizeOfArgID;
9518 
9519   // Although widely used, 'bzero' is not a standard function. Be more strict
9520   // with the argument types before allowing diagnostics and only allow the
9521   // form bzero(ptr, sizeof(...)).
9522   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9523   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9524     return;
9525 
9526   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9527     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9528     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9529 
9530     QualType DestTy = Dest->getType();
9531     QualType PointeeTy;
9532     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9533       PointeeTy = DestPtrTy->getPointeeType();
9534 
9535       // Never warn about void type pointers. This can be used to suppress
9536       // false positives.
9537       if (PointeeTy->isVoidType())
9538         continue;
9539 
9540       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9541       // actually comparing the expressions for equality. Because computing the
9542       // expression IDs can be expensive, we only do this if the diagnostic is
9543       // enabled.
9544       if (SizeOfArg &&
9545           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9546                            SizeOfArg->getExprLoc())) {
9547         // We only compute IDs for expressions if the warning is enabled, and
9548         // cache the sizeof arg's ID.
9549         if (SizeOfArgID == llvm::FoldingSetNodeID())
9550           SizeOfArg->Profile(SizeOfArgID, Context, true);
9551         llvm::FoldingSetNodeID DestID;
9552         Dest->Profile(DestID, Context, true);
9553         if (DestID == SizeOfArgID) {
9554           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9555           //       over sizeof(src) as well.
9556           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9557           StringRef ReadableName = FnName->getName();
9558 
9559           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9560             if (UnaryOp->getOpcode() == UO_AddrOf)
9561               ActionIdx = 1; // If its an address-of operator, just remove it.
9562           if (!PointeeTy->isIncompleteType() &&
9563               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9564             ActionIdx = 2; // If the pointee's size is sizeof(char),
9565                            // suggest an explicit length.
9566 
9567           // If the function is defined as a builtin macro, do not show macro
9568           // expansion.
9569           SourceLocation SL = SizeOfArg->getExprLoc();
9570           SourceRange DSR = Dest->getSourceRange();
9571           SourceRange SSR = SizeOfArg->getSourceRange();
9572           SourceManager &SM = getSourceManager();
9573 
9574           if (SM.isMacroArgExpansion(SL)) {
9575             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9576             SL = SM.getSpellingLoc(SL);
9577             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9578                              SM.getSpellingLoc(DSR.getEnd()));
9579             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9580                              SM.getSpellingLoc(SSR.getEnd()));
9581           }
9582 
9583           DiagRuntimeBehavior(SL, SizeOfArg,
9584                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9585                                 << ReadableName
9586                                 << PointeeTy
9587                                 << DestTy
9588                                 << DSR
9589                                 << SSR);
9590           DiagRuntimeBehavior(SL, SizeOfArg,
9591                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9592                                 << ActionIdx
9593                                 << SSR);
9594 
9595           break;
9596         }
9597       }
9598 
9599       // Also check for cases where the sizeof argument is the exact same
9600       // type as the memory argument, and where it points to a user-defined
9601       // record type.
9602       if (SizeOfArgTy != QualType()) {
9603         if (PointeeTy->isRecordType() &&
9604             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9605           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9606                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9607                                 << FnName << SizeOfArgTy << ArgIdx
9608                                 << PointeeTy << Dest->getSourceRange()
9609                                 << LenExpr->getSourceRange());
9610           break;
9611         }
9612       }
9613     } else if (DestTy->isArrayType()) {
9614       PointeeTy = DestTy;
9615     }
9616 
9617     if (PointeeTy == QualType())
9618       continue;
9619 
9620     // Always complain about dynamic classes.
9621     bool IsContained;
9622     if (const CXXRecordDecl *ContainedRD =
9623             getContainedDynamicClass(PointeeTy, IsContained)) {
9624 
9625       unsigned OperationType = 0;
9626       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9627       // "overwritten" if we're warning about the destination for any call
9628       // but memcmp; otherwise a verb appropriate to the call.
9629       if (ArgIdx != 0 || IsCmp) {
9630         if (BId == Builtin::BImemcpy)
9631           OperationType = 1;
9632         else if(BId == Builtin::BImemmove)
9633           OperationType = 2;
9634         else if (IsCmp)
9635           OperationType = 3;
9636       }
9637 
9638       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9639                           PDiag(diag::warn_dyn_class_memaccess)
9640                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9641                               << IsContained << ContainedRD << OperationType
9642                               << Call->getCallee()->getSourceRange());
9643     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9644              BId != Builtin::BImemset)
9645       DiagRuntimeBehavior(
9646         Dest->getExprLoc(), Dest,
9647         PDiag(diag::warn_arc_object_memaccess)
9648           << ArgIdx << FnName << PointeeTy
9649           << Call->getCallee()->getSourceRange());
9650     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9651       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9652           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9653         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9654                             PDiag(diag::warn_cstruct_memaccess)
9655                                 << ArgIdx << FnName << PointeeTy << 0);
9656         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9657       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9658                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9659         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9660                             PDiag(diag::warn_cstruct_memaccess)
9661                                 << ArgIdx << FnName << PointeeTy << 1);
9662         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9663       } else {
9664         continue;
9665       }
9666     } else
9667       continue;
9668 
9669     DiagRuntimeBehavior(
9670       Dest->getExprLoc(), Dest,
9671       PDiag(diag::note_bad_memaccess_silence)
9672         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9673     break;
9674   }
9675 }
9676 
9677 // A little helper routine: ignore addition and subtraction of integer literals.
9678 // This intentionally does not ignore all integer constant expressions because
9679 // we don't want to remove sizeof().
9680 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9681   Ex = Ex->IgnoreParenCasts();
9682 
9683   while (true) {
9684     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9685     if (!BO || !BO->isAdditiveOp())
9686       break;
9687 
9688     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9689     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9690 
9691     if (isa<IntegerLiteral>(RHS))
9692       Ex = LHS;
9693     else if (isa<IntegerLiteral>(LHS))
9694       Ex = RHS;
9695     else
9696       break;
9697   }
9698 
9699   return Ex;
9700 }
9701 
9702 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9703                                                       ASTContext &Context) {
9704   // Only handle constant-sized or VLAs, but not flexible members.
9705   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9706     // Only issue the FIXIT for arrays of size > 1.
9707     if (CAT->getSize().getSExtValue() <= 1)
9708       return false;
9709   } else if (!Ty->isVariableArrayType()) {
9710     return false;
9711   }
9712   return true;
9713 }
9714 
9715 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9716 // be the size of the source, instead of the destination.
9717 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9718                                     IdentifierInfo *FnName) {
9719 
9720   // Don't crash if the user has the wrong number of arguments
9721   unsigned NumArgs = Call->getNumArgs();
9722   if ((NumArgs != 3) && (NumArgs != 4))
9723     return;
9724 
9725   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9726   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9727   const Expr *CompareWithSrc = nullptr;
9728 
9729   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9730                                      Call->getBeginLoc(), Call->getRParenLoc()))
9731     return;
9732 
9733   // Look for 'strlcpy(dst, x, sizeof(x))'
9734   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9735     CompareWithSrc = Ex;
9736   else {
9737     // Look for 'strlcpy(dst, x, strlen(x))'
9738     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9739       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9740           SizeCall->getNumArgs() == 1)
9741         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9742     }
9743   }
9744 
9745   if (!CompareWithSrc)
9746     return;
9747 
9748   // Determine if the argument to sizeof/strlen is equal to the source
9749   // argument.  In principle there's all kinds of things you could do
9750   // here, for instance creating an == expression and evaluating it with
9751   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9752   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9753   if (!SrcArgDRE)
9754     return;
9755 
9756   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9757   if (!CompareWithSrcDRE ||
9758       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9759     return;
9760 
9761   const Expr *OriginalSizeArg = Call->getArg(2);
9762   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9763       << OriginalSizeArg->getSourceRange() << FnName;
9764 
9765   // Output a FIXIT hint if the destination is an array (rather than a
9766   // pointer to an array).  This could be enhanced to handle some
9767   // pointers if we know the actual size, like if DstArg is 'array+2'
9768   // we could say 'sizeof(array)-2'.
9769   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9770   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9771     return;
9772 
9773   SmallString<128> sizeString;
9774   llvm::raw_svector_ostream OS(sizeString);
9775   OS << "sizeof(";
9776   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9777   OS << ")";
9778 
9779   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9780       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9781                                       OS.str());
9782 }
9783 
9784 /// Check if two expressions refer to the same declaration.
9785 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9786   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9787     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9788       return D1->getDecl() == D2->getDecl();
9789   return false;
9790 }
9791 
9792 static const Expr *getStrlenExprArg(const Expr *E) {
9793   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9794     const FunctionDecl *FD = CE->getDirectCallee();
9795     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9796       return nullptr;
9797     return CE->getArg(0)->IgnoreParenCasts();
9798   }
9799   return nullptr;
9800 }
9801 
9802 // Warn on anti-patterns as the 'size' argument to strncat.
9803 // The correct size argument should look like following:
9804 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9805 void Sema::CheckStrncatArguments(const CallExpr *CE,
9806                                  IdentifierInfo *FnName) {
9807   // Don't crash if the user has the wrong number of arguments.
9808   if (CE->getNumArgs() < 3)
9809     return;
9810   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9811   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9812   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9813 
9814   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9815                                      CE->getRParenLoc()))
9816     return;
9817 
9818   // Identify common expressions, which are wrongly used as the size argument
9819   // to strncat and may lead to buffer overflows.
9820   unsigned PatternType = 0;
9821   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9822     // - sizeof(dst)
9823     if (referToTheSameDecl(SizeOfArg, DstArg))
9824       PatternType = 1;
9825     // - sizeof(src)
9826     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9827       PatternType = 2;
9828   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9829     if (BE->getOpcode() == BO_Sub) {
9830       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9831       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9832       // - sizeof(dst) - strlen(dst)
9833       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9834           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9835         PatternType = 1;
9836       // - sizeof(src) - (anything)
9837       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9838         PatternType = 2;
9839     }
9840   }
9841 
9842   if (PatternType == 0)
9843     return;
9844 
9845   // Generate the diagnostic.
9846   SourceLocation SL = LenArg->getBeginLoc();
9847   SourceRange SR = LenArg->getSourceRange();
9848   SourceManager &SM = getSourceManager();
9849 
9850   // If the function is defined as a builtin macro, do not show macro expansion.
9851   if (SM.isMacroArgExpansion(SL)) {
9852     SL = SM.getSpellingLoc(SL);
9853     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9854                      SM.getSpellingLoc(SR.getEnd()));
9855   }
9856 
9857   // Check if the destination is an array (rather than a pointer to an array).
9858   QualType DstTy = DstArg->getType();
9859   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9860                                                                     Context);
9861   if (!isKnownSizeArray) {
9862     if (PatternType == 1)
9863       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9864     else
9865       Diag(SL, diag::warn_strncat_src_size) << SR;
9866     return;
9867   }
9868 
9869   if (PatternType == 1)
9870     Diag(SL, diag::warn_strncat_large_size) << SR;
9871   else
9872     Diag(SL, diag::warn_strncat_src_size) << SR;
9873 
9874   SmallString<128> sizeString;
9875   llvm::raw_svector_ostream OS(sizeString);
9876   OS << "sizeof(";
9877   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9878   OS << ") - ";
9879   OS << "strlen(";
9880   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9881   OS << ") - 1";
9882 
9883   Diag(SL, diag::note_strncat_wrong_size)
9884     << FixItHint::CreateReplacement(SR, OS.str());
9885 }
9886 
9887 void
9888 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9889                          SourceLocation ReturnLoc,
9890                          bool isObjCMethod,
9891                          const AttrVec *Attrs,
9892                          const FunctionDecl *FD) {
9893   // Check if the return value is null but should not be.
9894   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9895        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9896       CheckNonNullExpr(*this, RetValExp))
9897     Diag(ReturnLoc, diag::warn_null_ret)
9898       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9899 
9900   // C++11 [basic.stc.dynamic.allocation]p4:
9901   //   If an allocation function declared with a non-throwing
9902   //   exception-specification fails to allocate storage, it shall return
9903   //   a null pointer. Any other allocation function that fails to allocate
9904   //   storage shall indicate failure only by throwing an exception [...]
9905   if (FD) {
9906     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9907     if (Op == OO_New || Op == OO_Array_New) {
9908       const FunctionProtoType *Proto
9909         = FD->getType()->castAs<FunctionProtoType>();
9910       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9911           CheckNonNullExpr(*this, RetValExp))
9912         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9913           << FD << getLangOpts().CPlusPlus11;
9914     }
9915   }
9916 }
9917 
9918 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9919 
9920 /// Check for comparisons of floating point operands using != and ==.
9921 /// Issue a warning if these are no self-comparisons, as they are not likely
9922 /// to do what the programmer intended.
9923 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9924   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9925   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9926 
9927   // Special case: check for x == x (which is OK).
9928   // Do not emit warnings for such cases.
9929   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9930     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9931       if (DRL->getDecl() == DRR->getDecl())
9932         return;
9933 
9934   // Special case: check for comparisons against literals that can be exactly
9935   //  represented by APFloat.  In such cases, do not emit a warning.  This
9936   //  is a heuristic: often comparison against such literals are used to
9937   //  detect if a value in a variable has not changed.  This clearly can
9938   //  lead to false negatives.
9939   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9940     if (FLL->isExact())
9941       return;
9942   } else
9943     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9944       if (FLR->isExact())
9945         return;
9946 
9947   // Check for comparisons with builtin types.
9948   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9949     if (CL->getBuiltinCallee())
9950       return;
9951 
9952   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9953     if (CR->getBuiltinCallee())
9954       return;
9955 
9956   // Emit the diagnostic.
9957   Diag(Loc, diag::warn_floatingpoint_eq)
9958     << LHS->getSourceRange() << RHS->getSourceRange();
9959 }
9960 
9961 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9962 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9963 
9964 namespace {
9965 
9966 /// Structure recording the 'active' range of an integer-valued
9967 /// expression.
9968 struct IntRange {
9969   /// The number of bits active in the int.
9970   unsigned Width;
9971 
9972   /// True if the int is known not to have negative values.
9973   bool NonNegative;
9974 
9975   IntRange(unsigned Width, bool NonNegative)
9976       : Width(Width), NonNegative(NonNegative) {}
9977 
9978   /// Returns the range of the bool type.
9979   static IntRange forBoolType() {
9980     return IntRange(1, true);
9981   }
9982 
9983   /// Returns the range of an opaque value of the given integral type.
9984   static IntRange forValueOfType(ASTContext &C, QualType T) {
9985     return forValueOfCanonicalType(C,
9986                           T->getCanonicalTypeInternal().getTypePtr());
9987   }
9988 
9989   /// Returns the range of an opaque value of a canonical integral type.
9990   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9991     assert(T->isCanonicalUnqualified());
9992 
9993     if (const VectorType *VT = dyn_cast<VectorType>(T))
9994       T = VT->getElementType().getTypePtr();
9995     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9996       T = CT->getElementType().getTypePtr();
9997     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9998       T = AT->getValueType().getTypePtr();
9999 
10000     if (!C.getLangOpts().CPlusPlus) {
10001       // For enum types in C code, use the underlying datatype.
10002       if (const EnumType *ET = dyn_cast<EnumType>(T))
10003         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10004     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10005       // For enum types in C++, use the known bit width of the enumerators.
10006       EnumDecl *Enum = ET->getDecl();
10007       // In C++11, enums can have a fixed underlying type. Use this type to
10008       // compute the range.
10009       if (Enum->isFixed()) {
10010         return IntRange(C.getIntWidth(QualType(T, 0)),
10011                         !ET->isSignedIntegerOrEnumerationType());
10012       }
10013 
10014       unsigned NumPositive = Enum->getNumPositiveBits();
10015       unsigned NumNegative = Enum->getNumNegativeBits();
10016 
10017       if (NumNegative == 0)
10018         return IntRange(NumPositive, true/*NonNegative*/);
10019       else
10020         return IntRange(std::max(NumPositive + 1, NumNegative),
10021                         false/*NonNegative*/);
10022     }
10023 
10024     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10025       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10026 
10027     const BuiltinType *BT = cast<BuiltinType>(T);
10028     assert(BT->isInteger());
10029 
10030     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10031   }
10032 
10033   /// Returns the "target" range of a canonical integral type, i.e.
10034   /// the range of values expressible in the type.
10035   ///
10036   /// This matches forValueOfCanonicalType except that enums have the
10037   /// full range of their type, not the range of their enumerators.
10038   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10039     assert(T->isCanonicalUnqualified());
10040 
10041     if (const VectorType *VT = dyn_cast<VectorType>(T))
10042       T = VT->getElementType().getTypePtr();
10043     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10044       T = CT->getElementType().getTypePtr();
10045     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10046       T = AT->getValueType().getTypePtr();
10047     if (const EnumType *ET = dyn_cast<EnumType>(T))
10048       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10049 
10050     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10051       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10052 
10053     const BuiltinType *BT = cast<BuiltinType>(T);
10054     assert(BT->isInteger());
10055 
10056     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10057   }
10058 
10059   /// Returns the supremum of two ranges: i.e. their conservative merge.
10060   static IntRange join(IntRange L, IntRange R) {
10061     return IntRange(std::max(L.Width, R.Width),
10062                     L.NonNegative && R.NonNegative);
10063   }
10064 
10065   /// Returns the infinum of two ranges: i.e. their aggressive merge.
10066   static IntRange meet(IntRange L, IntRange R) {
10067     return IntRange(std::min(L.Width, R.Width),
10068                     L.NonNegative || R.NonNegative);
10069   }
10070 };
10071 
10072 } // namespace
10073 
10074 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10075                               unsigned MaxWidth) {
10076   if (value.isSigned() && value.isNegative())
10077     return IntRange(value.getMinSignedBits(), false);
10078 
10079   if (value.getBitWidth() > MaxWidth)
10080     value = value.trunc(MaxWidth);
10081 
10082   // isNonNegative() just checks the sign bit without considering
10083   // signedness.
10084   return IntRange(value.getActiveBits(), true);
10085 }
10086 
10087 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10088                               unsigned MaxWidth) {
10089   if (result.isInt())
10090     return GetValueRange(C, result.getInt(), MaxWidth);
10091 
10092   if (result.isVector()) {
10093     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10094     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10095       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10096       R = IntRange::join(R, El);
10097     }
10098     return R;
10099   }
10100 
10101   if (result.isComplexInt()) {
10102     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10103     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10104     return IntRange::join(R, I);
10105   }
10106 
10107   // This can happen with lossless casts to intptr_t of "based" lvalues.
10108   // Assume it might use arbitrary bits.
10109   // FIXME: The only reason we need to pass the type in here is to get
10110   // the sign right on this one case.  It would be nice if APValue
10111   // preserved this.
10112   assert(result.isLValue() || result.isAddrLabelDiff());
10113   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10114 }
10115 
10116 static QualType GetExprType(const Expr *E) {
10117   QualType Ty = E->getType();
10118   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10119     Ty = AtomicRHS->getValueType();
10120   return Ty;
10121 }
10122 
10123 /// Pseudo-evaluate the given integer expression, estimating the
10124 /// range of values it might take.
10125 ///
10126 /// \param MaxWidth - the width to which the value will be truncated
10127 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10128                              bool InConstantContext) {
10129   E = E->IgnoreParens();
10130 
10131   // Try a full evaluation first.
10132   Expr::EvalResult result;
10133   if (E->EvaluateAsRValue(result, C, InConstantContext))
10134     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10135 
10136   // I think we only want to look through implicit casts here; if the
10137   // user has an explicit widening cast, we should treat the value as
10138   // being of the new, wider type.
10139   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10140     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10141       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10142 
10143     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10144 
10145     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10146                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10147 
10148     // Assume that non-integer casts can span the full range of the type.
10149     if (!isIntegerCast)
10150       return OutputTypeRange;
10151 
10152     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10153                                      std::min(MaxWidth, OutputTypeRange.Width),
10154                                      InConstantContext);
10155 
10156     // Bail out if the subexpr's range is as wide as the cast type.
10157     if (SubRange.Width >= OutputTypeRange.Width)
10158       return OutputTypeRange;
10159 
10160     // Otherwise, we take the smaller width, and we're non-negative if
10161     // either the output type or the subexpr is.
10162     return IntRange(SubRange.Width,
10163                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10164   }
10165 
10166   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10167     // If we can fold the condition, just take that operand.
10168     bool CondResult;
10169     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10170       return GetExprRange(C,
10171                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10172                           MaxWidth, InConstantContext);
10173 
10174     // Otherwise, conservatively merge.
10175     IntRange L =
10176         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10177     IntRange R =
10178         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10179     return IntRange::join(L, R);
10180   }
10181 
10182   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10183     switch (BO->getOpcode()) {
10184     case BO_Cmp:
10185       llvm_unreachable("builtin <=> should have class type");
10186 
10187     // Boolean-valued operations are single-bit and positive.
10188     case BO_LAnd:
10189     case BO_LOr:
10190     case BO_LT:
10191     case BO_GT:
10192     case BO_LE:
10193     case BO_GE:
10194     case BO_EQ:
10195     case BO_NE:
10196       return IntRange::forBoolType();
10197 
10198     // The type of the assignments is the type of the LHS, so the RHS
10199     // is not necessarily the same type.
10200     case BO_MulAssign:
10201     case BO_DivAssign:
10202     case BO_RemAssign:
10203     case BO_AddAssign:
10204     case BO_SubAssign:
10205     case BO_XorAssign:
10206     case BO_OrAssign:
10207       // TODO: bitfields?
10208       return IntRange::forValueOfType(C, GetExprType(E));
10209 
10210     // Simple assignments just pass through the RHS, which will have
10211     // been coerced to the LHS type.
10212     case BO_Assign:
10213       // TODO: bitfields?
10214       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10215 
10216     // Operations with opaque sources are black-listed.
10217     case BO_PtrMemD:
10218     case BO_PtrMemI:
10219       return IntRange::forValueOfType(C, GetExprType(E));
10220 
10221     // Bitwise-and uses the *infinum* of the two source ranges.
10222     case BO_And:
10223     case BO_AndAssign:
10224       return IntRange::meet(
10225           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10226           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10227 
10228     // Left shift gets black-listed based on a judgement call.
10229     case BO_Shl:
10230       // ...except that we want to treat '1 << (blah)' as logically
10231       // positive.  It's an important idiom.
10232       if (IntegerLiteral *I
10233             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10234         if (I->getValue() == 1) {
10235           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10236           return IntRange(R.Width, /*NonNegative*/ true);
10237         }
10238       }
10239       LLVM_FALLTHROUGH;
10240 
10241     case BO_ShlAssign:
10242       return IntRange::forValueOfType(C, GetExprType(E));
10243 
10244     // Right shift by a constant can narrow its left argument.
10245     case BO_Shr:
10246     case BO_ShrAssign: {
10247       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10248 
10249       // If the shift amount is a positive constant, drop the width by
10250       // that much.
10251       llvm::APSInt shift;
10252       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10253           shift.isNonNegative()) {
10254         unsigned zext = shift.getZExtValue();
10255         if (zext >= L.Width)
10256           L.Width = (L.NonNegative ? 0 : 1);
10257         else
10258           L.Width -= zext;
10259       }
10260 
10261       return L;
10262     }
10263 
10264     // Comma acts as its right operand.
10265     case BO_Comma:
10266       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10267 
10268     // Black-list pointer subtractions.
10269     case BO_Sub:
10270       if (BO->getLHS()->getType()->isPointerType())
10271         return IntRange::forValueOfType(C, GetExprType(E));
10272       break;
10273 
10274     // The width of a division result is mostly determined by the size
10275     // of the LHS.
10276     case BO_Div: {
10277       // Don't 'pre-truncate' the operands.
10278       unsigned opWidth = C.getIntWidth(GetExprType(E));
10279       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10280 
10281       // If the divisor is constant, use that.
10282       llvm::APSInt divisor;
10283       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10284         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10285         if (log2 >= L.Width)
10286           L.Width = (L.NonNegative ? 0 : 1);
10287         else
10288           L.Width = std::min(L.Width - log2, MaxWidth);
10289         return L;
10290       }
10291 
10292       // Otherwise, just use the LHS's width.
10293       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10294       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10295     }
10296 
10297     // The result of a remainder can't be larger than the result of
10298     // either side.
10299     case BO_Rem: {
10300       // Don't 'pre-truncate' the operands.
10301       unsigned opWidth = C.getIntWidth(GetExprType(E));
10302       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10303       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10304 
10305       IntRange meet = IntRange::meet(L, R);
10306       meet.Width = std::min(meet.Width, MaxWidth);
10307       return meet;
10308     }
10309 
10310     // The default behavior is okay for these.
10311     case BO_Mul:
10312     case BO_Add:
10313     case BO_Xor:
10314     case BO_Or:
10315       break;
10316     }
10317 
10318     // The default case is to treat the operation as if it were closed
10319     // on the narrowest type that encompasses both operands.
10320     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10321     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10322     return IntRange::join(L, R);
10323   }
10324 
10325   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10326     switch (UO->getOpcode()) {
10327     // Boolean-valued operations are white-listed.
10328     case UO_LNot:
10329       return IntRange::forBoolType();
10330 
10331     // Operations with opaque sources are black-listed.
10332     case UO_Deref:
10333     case UO_AddrOf: // should be impossible
10334       return IntRange::forValueOfType(C, GetExprType(E));
10335 
10336     default:
10337       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10338     }
10339   }
10340 
10341   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10342     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10343 
10344   if (const auto *BitField = E->getSourceBitField())
10345     return IntRange(BitField->getBitWidthValue(C),
10346                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10347 
10348   return IntRange::forValueOfType(C, GetExprType(E));
10349 }
10350 
10351 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10352                              bool InConstantContext) {
10353   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10354 }
10355 
10356 /// Checks whether the given value, which currently has the given
10357 /// source semantics, has the same value when coerced through the
10358 /// target semantics.
10359 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10360                                  const llvm::fltSemantics &Src,
10361                                  const llvm::fltSemantics &Tgt) {
10362   llvm::APFloat truncated = value;
10363 
10364   bool ignored;
10365   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10366   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10367 
10368   return truncated.bitwiseIsEqual(value);
10369 }
10370 
10371 /// Checks whether the given value, which currently has the given
10372 /// source semantics, has the same value when coerced through the
10373 /// target semantics.
10374 ///
10375 /// The value might be a vector of floats (or a complex number).
10376 static bool IsSameFloatAfterCast(const APValue &value,
10377                                  const llvm::fltSemantics &Src,
10378                                  const llvm::fltSemantics &Tgt) {
10379   if (value.isFloat())
10380     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10381 
10382   if (value.isVector()) {
10383     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10384       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10385         return false;
10386     return true;
10387   }
10388 
10389   assert(value.isComplexFloat());
10390   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10391           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10392 }
10393 
10394 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10395                                        bool IsListInit = false);
10396 
10397 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10398   // Suppress cases where we are comparing against an enum constant.
10399   if (const DeclRefExpr *DR =
10400       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10401     if (isa<EnumConstantDecl>(DR->getDecl()))
10402       return true;
10403 
10404   // Suppress cases where the value is expanded from a macro, unless that macro
10405   // is how a language represents a boolean literal. This is the case in both C
10406   // and Objective-C.
10407   SourceLocation BeginLoc = E->getBeginLoc();
10408   if (BeginLoc.isMacroID()) {
10409     StringRef MacroName = Lexer::getImmediateMacroName(
10410         BeginLoc, S.getSourceManager(), S.getLangOpts());
10411     return MacroName != "YES" && MacroName != "NO" &&
10412            MacroName != "true" && MacroName != "false";
10413   }
10414 
10415   return false;
10416 }
10417 
10418 static bool isKnownToHaveUnsignedValue(Expr *E) {
10419   return E->getType()->isIntegerType() &&
10420          (!E->getType()->isSignedIntegerType() ||
10421           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10422 }
10423 
10424 namespace {
10425 /// The promoted range of values of a type. In general this has the
10426 /// following structure:
10427 ///
10428 ///     |-----------| . . . |-----------|
10429 ///     ^           ^       ^           ^
10430 ///    Min       HoleMin  HoleMax      Max
10431 ///
10432 /// ... where there is only a hole if a signed type is promoted to unsigned
10433 /// (in which case Min and Max are the smallest and largest representable
10434 /// values).
10435 struct PromotedRange {
10436   // Min, or HoleMax if there is a hole.
10437   llvm::APSInt PromotedMin;
10438   // Max, or HoleMin if there is a hole.
10439   llvm::APSInt PromotedMax;
10440 
10441   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10442     if (R.Width == 0)
10443       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10444     else if (R.Width >= BitWidth && !Unsigned) {
10445       // Promotion made the type *narrower*. This happens when promoting
10446       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10447       // Treat all values of 'signed int' as being in range for now.
10448       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10449       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10450     } else {
10451       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10452                         .extOrTrunc(BitWidth);
10453       PromotedMin.setIsUnsigned(Unsigned);
10454 
10455       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10456                         .extOrTrunc(BitWidth);
10457       PromotedMax.setIsUnsigned(Unsigned);
10458     }
10459   }
10460 
10461   // Determine whether this range is contiguous (has no hole).
10462   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10463 
10464   // Where a constant value is within the range.
10465   enum ComparisonResult {
10466     LT = 0x1,
10467     LE = 0x2,
10468     GT = 0x4,
10469     GE = 0x8,
10470     EQ = 0x10,
10471     NE = 0x20,
10472     InRangeFlag = 0x40,
10473 
10474     Less = LE | LT | NE,
10475     Min = LE | InRangeFlag,
10476     InRange = InRangeFlag,
10477     Max = GE | InRangeFlag,
10478     Greater = GE | GT | NE,
10479 
10480     OnlyValue = LE | GE | EQ | InRangeFlag,
10481     InHole = NE
10482   };
10483 
10484   ComparisonResult compare(const llvm::APSInt &Value) const {
10485     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10486            Value.isUnsigned() == PromotedMin.isUnsigned());
10487     if (!isContiguous()) {
10488       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10489       if (Value.isMinValue()) return Min;
10490       if (Value.isMaxValue()) return Max;
10491       if (Value >= PromotedMin) return InRange;
10492       if (Value <= PromotedMax) return InRange;
10493       return InHole;
10494     }
10495 
10496     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10497     case -1: return Less;
10498     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10499     case 1:
10500       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10501       case -1: return InRange;
10502       case 0: return Max;
10503       case 1: return Greater;
10504       }
10505     }
10506 
10507     llvm_unreachable("impossible compare result");
10508   }
10509 
10510   static llvm::Optional<StringRef>
10511   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10512     if (Op == BO_Cmp) {
10513       ComparisonResult LTFlag = LT, GTFlag = GT;
10514       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10515 
10516       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10517       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10518       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10519       return llvm::None;
10520     }
10521 
10522     ComparisonResult TrueFlag, FalseFlag;
10523     if (Op == BO_EQ) {
10524       TrueFlag = EQ;
10525       FalseFlag = NE;
10526     } else if (Op == BO_NE) {
10527       TrueFlag = NE;
10528       FalseFlag = EQ;
10529     } else {
10530       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10531         TrueFlag = LT;
10532         FalseFlag = GE;
10533       } else {
10534         TrueFlag = GT;
10535         FalseFlag = LE;
10536       }
10537       if (Op == BO_GE || Op == BO_LE)
10538         std::swap(TrueFlag, FalseFlag);
10539     }
10540     if (R & TrueFlag)
10541       return StringRef("true");
10542     if (R & FalseFlag)
10543       return StringRef("false");
10544     return llvm::None;
10545   }
10546 };
10547 }
10548 
10549 static bool HasEnumType(Expr *E) {
10550   // Strip off implicit integral promotions.
10551   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10552     if (ICE->getCastKind() != CK_IntegralCast &&
10553         ICE->getCastKind() != CK_NoOp)
10554       break;
10555     E = ICE->getSubExpr();
10556   }
10557 
10558   return E->getType()->isEnumeralType();
10559 }
10560 
10561 static int classifyConstantValue(Expr *Constant) {
10562   // The values of this enumeration are used in the diagnostics
10563   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10564   enum ConstantValueKind {
10565     Miscellaneous = 0,
10566     LiteralTrue,
10567     LiteralFalse
10568   };
10569   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10570     return BL->getValue() ? ConstantValueKind::LiteralTrue
10571                           : ConstantValueKind::LiteralFalse;
10572   return ConstantValueKind::Miscellaneous;
10573 }
10574 
10575 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10576                                         Expr *Constant, Expr *Other,
10577                                         const llvm::APSInt &Value,
10578                                         bool RhsConstant) {
10579   if (S.inTemplateInstantiation())
10580     return false;
10581 
10582   Expr *OriginalOther = Other;
10583 
10584   Constant = Constant->IgnoreParenImpCasts();
10585   Other = Other->IgnoreParenImpCasts();
10586 
10587   // Suppress warnings on tautological comparisons between values of the same
10588   // enumeration type. There are only two ways we could warn on this:
10589   //  - If the constant is outside the range of representable values of
10590   //    the enumeration. In such a case, we should warn about the cast
10591   //    to enumeration type, not about the comparison.
10592   //  - If the constant is the maximum / minimum in-range value. For an
10593   //    enumeratin type, such comparisons can be meaningful and useful.
10594   if (Constant->getType()->isEnumeralType() &&
10595       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10596     return false;
10597 
10598   // TODO: Investigate using GetExprRange() to get tighter bounds
10599   // on the bit ranges.
10600   QualType OtherT = Other->getType();
10601   if (const auto *AT = OtherT->getAs<AtomicType>())
10602     OtherT = AT->getValueType();
10603   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10604 
10605   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10606   // (Namely, macOS).
10607   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10608                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10609                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10610 
10611   // Whether we're treating Other as being a bool because of the form of
10612   // expression despite it having another type (typically 'int' in C).
10613   bool OtherIsBooleanDespiteType =
10614       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10615   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10616     OtherRange = IntRange::forBoolType();
10617 
10618   // Determine the promoted range of the other type and see if a comparison of
10619   // the constant against that range is tautological.
10620   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10621                                    Value.isUnsigned());
10622   auto Cmp = OtherPromotedRange.compare(Value);
10623   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10624   if (!Result)
10625     return false;
10626 
10627   // Suppress the diagnostic for an in-range comparison if the constant comes
10628   // from a macro or enumerator. We don't want to diagnose
10629   //
10630   //   some_long_value <= INT_MAX
10631   //
10632   // when sizeof(int) == sizeof(long).
10633   bool InRange = Cmp & PromotedRange::InRangeFlag;
10634   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10635     return false;
10636 
10637   // If this is a comparison to an enum constant, include that
10638   // constant in the diagnostic.
10639   const EnumConstantDecl *ED = nullptr;
10640   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10641     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10642 
10643   // Should be enough for uint128 (39 decimal digits)
10644   SmallString<64> PrettySourceValue;
10645   llvm::raw_svector_ostream OS(PrettySourceValue);
10646   if (ED) {
10647     OS << '\'' << *ED << "' (" << Value << ")";
10648   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10649                Constant->IgnoreParenImpCasts())) {
10650     OS << (BL->getValue() ? "YES" : "NO");
10651   } else {
10652     OS << Value;
10653   }
10654 
10655   if (IsObjCSignedCharBool) {
10656     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10657                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10658                               << OS.str() << *Result);
10659     return true;
10660   }
10661 
10662   // FIXME: We use a somewhat different formatting for the in-range cases and
10663   // cases involving boolean values for historical reasons. We should pick a
10664   // consistent way of presenting these diagnostics.
10665   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10666 
10667     S.DiagRuntimeBehavior(
10668         E->getOperatorLoc(), E,
10669         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10670                          : diag::warn_tautological_bool_compare)
10671             << OS.str() << classifyConstantValue(Constant) << OtherT
10672             << OtherIsBooleanDespiteType << *Result
10673             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10674   } else {
10675     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10676                         ? (HasEnumType(OriginalOther)
10677                                ? diag::warn_unsigned_enum_always_true_comparison
10678                                : diag::warn_unsigned_always_true_comparison)
10679                         : diag::warn_tautological_constant_compare;
10680 
10681     S.Diag(E->getOperatorLoc(), Diag)
10682         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10683         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10684   }
10685 
10686   return true;
10687 }
10688 
10689 /// Analyze the operands of the given comparison.  Implements the
10690 /// fallback case from AnalyzeComparison.
10691 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10692   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10693   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10694 }
10695 
10696 /// Implements -Wsign-compare.
10697 ///
10698 /// \param E the binary operator to check for warnings
10699 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10700   // The type the comparison is being performed in.
10701   QualType T = E->getLHS()->getType();
10702 
10703   // Only analyze comparison operators where both sides have been converted to
10704   // the same type.
10705   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10706     return AnalyzeImpConvsInComparison(S, E);
10707 
10708   // Don't analyze value-dependent comparisons directly.
10709   if (E->isValueDependent())
10710     return AnalyzeImpConvsInComparison(S, E);
10711 
10712   Expr *LHS = E->getLHS();
10713   Expr *RHS = E->getRHS();
10714 
10715   if (T->isIntegralType(S.Context)) {
10716     llvm::APSInt RHSValue;
10717     llvm::APSInt LHSValue;
10718 
10719     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10720     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10721 
10722     // We don't care about expressions whose result is a constant.
10723     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10724       return AnalyzeImpConvsInComparison(S, E);
10725 
10726     // We only care about expressions where just one side is literal
10727     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10728       // Is the constant on the RHS or LHS?
10729       const bool RhsConstant = IsRHSIntegralLiteral;
10730       Expr *Const = RhsConstant ? RHS : LHS;
10731       Expr *Other = RhsConstant ? LHS : RHS;
10732       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10733 
10734       // Check whether an integer constant comparison results in a value
10735       // of 'true' or 'false'.
10736       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10737         return AnalyzeImpConvsInComparison(S, E);
10738     }
10739   }
10740 
10741   if (!T->hasUnsignedIntegerRepresentation()) {
10742     // We don't do anything special if this isn't an unsigned integral
10743     // comparison:  we're only interested in integral comparisons, and
10744     // signed comparisons only happen in cases we don't care to warn about.
10745     return AnalyzeImpConvsInComparison(S, E);
10746   }
10747 
10748   LHS = LHS->IgnoreParenImpCasts();
10749   RHS = RHS->IgnoreParenImpCasts();
10750 
10751   if (!S.getLangOpts().CPlusPlus) {
10752     // Avoid warning about comparison of integers with different signs when
10753     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10754     // the type of `E`.
10755     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10756       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10757     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10758       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10759   }
10760 
10761   // Check to see if one of the (unmodified) operands is of different
10762   // signedness.
10763   Expr *signedOperand, *unsignedOperand;
10764   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10765     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10766            "unsigned comparison between two signed integer expressions?");
10767     signedOperand = LHS;
10768     unsignedOperand = RHS;
10769   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10770     signedOperand = RHS;
10771     unsignedOperand = LHS;
10772   } else {
10773     return AnalyzeImpConvsInComparison(S, E);
10774   }
10775 
10776   // Otherwise, calculate the effective range of the signed operand.
10777   IntRange signedRange =
10778       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10779 
10780   // Go ahead and analyze implicit conversions in the operands.  Note
10781   // that we skip the implicit conversions on both sides.
10782   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10783   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10784 
10785   // If the signed range is non-negative, -Wsign-compare won't fire.
10786   if (signedRange.NonNegative)
10787     return;
10788 
10789   // For (in)equality comparisons, if the unsigned operand is a
10790   // constant which cannot collide with a overflowed signed operand,
10791   // then reinterpreting the signed operand as unsigned will not
10792   // change the result of the comparison.
10793   if (E->isEqualityOp()) {
10794     unsigned comparisonWidth = S.Context.getIntWidth(T);
10795     IntRange unsignedRange =
10796         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10797 
10798     // We should never be unable to prove that the unsigned operand is
10799     // non-negative.
10800     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10801 
10802     if (unsignedRange.Width < comparisonWidth)
10803       return;
10804   }
10805 
10806   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10807                         S.PDiag(diag::warn_mixed_sign_comparison)
10808                             << LHS->getType() << RHS->getType()
10809                             << LHS->getSourceRange() << RHS->getSourceRange());
10810 }
10811 
10812 /// Analyzes an attempt to assign the given value to a bitfield.
10813 ///
10814 /// Returns true if there was something fishy about the attempt.
10815 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10816                                       SourceLocation InitLoc) {
10817   assert(Bitfield->isBitField());
10818   if (Bitfield->isInvalidDecl())
10819     return false;
10820 
10821   // White-list bool bitfields.
10822   QualType BitfieldType = Bitfield->getType();
10823   if (BitfieldType->isBooleanType())
10824      return false;
10825 
10826   if (BitfieldType->isEnumeralType()) {
10827     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10828     // If the underlying enum type was not explicitly specified as an unsigned
10829     // type and the enum contain only positive values, MSVC++ will cause an
10830     // inconsistency by storing this as a signed type.
10831     if (S.getLangOpts().CPlusPlus11 &&
10832         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10833         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10834         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10835       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10836         << BitfieldEnumDecl->getNameAsString();
10837     }
10838   }
10839 
10840   if (Bitfield->getType()->isBooleanType())
10841     return false;
10842 
10843   // Ignore value- or type-dependent expressions.
10844   if (Bitfield->getBitWidth()->isValueDependent() ||
10845       Bitfield->getBitWidth()->isTypeDependent() ||
10846       Init->isValueDependent() ||
10847       Init->isTypeDependent())
10848     return false;
10849 
10850   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10851   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10852 
10853   Expr::EvalResult Result;
10854   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10855                                    Expr::SE_AllowSideEffects)) {
10856     // The RHS is not constant.  If the RHS has an enum type, make sure the
10857     // bitfield is wide enough to hold all the values of the enum without
10858     // truncation.
10859     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10860       EnumDecl *ED = EnumTy->getDecl();
10861       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10862 
10863       // Enum types are implicitly signed on Windows, so check if there are any
10864       // negative enumerators to see if the enum was intended to be signed or
10865       // not.
10866       bool SignedEnum = ED->getNumNegativeBits() > 0;
10867 
10868       // Check for surprising sign changes when assigning enum values to a
10869       // bitfield of different signedness.  If the bitfield is signed and we
10870       // have exactly the right number of bits to store this unsigned enum,
10871       // suggest changing the enum to an unsigned type. This typically happens
10872       // on Windows where unfixed enums always use an underlying type of 'int'.
10873       unsigned DiagID = 0;
10874       if (SignedEnum && !SignedBitfield) {
10875         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10876       } else if (SignedBitfield && !SignedEnum &&
10877                  ED->getNumPositiveBits() == FieldWidth) {
10878         DiagID = diag::warn_signed_bitfield_enum_conversion;
10879       }
10880 
10881       if (DiagID) {
10882         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10883         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10884         SourceRange TypeRange =
10885             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10886         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10887             << SignedEnum << TypeRange;
10888       }
10889 
10890       // Compute the required bitwidth. If the enum has negative values, we need
10891       // one more bit than the normal number of positive bits to represent the
10892       // sign bit.
10893       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10894                                                   ED->getNumNegativeBits())
10895                                        : ED->getNumPositiveBits();
10896 
10897       // Check the bitwidth.
10898       if (BitsNeeded > FieldWidth) {
10899         Expr *WidthExpr = Bitfield->getBitWidth();
10900         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10901             << Bitfield << ED;
10902         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10903             << BitsNeeded << ED << WidthExpr->getSourceRange();
10904       }
10905     }
10906 
10907     return false;
10908   }
10909 
10910   llvm::APSInt Value = Result.Val.getInt();
10911 
10912   unsigned OriginalWidth = Value.getBitWidth();
10913 
10914   if (!Value.isSigned() || Value.isNegative())
10915     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10916       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10917         OriginalWidth = Value.getMinSignedBits();
10918 
10919   if (OriginalWidth <= FieldWidth)
10920     return false;
10921 
10922   // Compute the value which the bitfield will contain.
10923   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10924   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10925 
10926   // Check whether the stored value is equal to the original value.
10927   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10928   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10929     return false;
10930 
10931   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10932   // therefore don't strictly fit into a signed bitfield of width 1.
10933   if (FieldWidth == 1 && Value == 1)
10934     return false;
10935 
10936   std::string PrettyValue = Value.toString(10);
10937   std::string PrettyTrunc = TruncatedValue.toString(10);
10938 
10939   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10940     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10941     << Init->getSourceRange();
10942 
10943   return true;
10944 }
10945 
10946 /// Analyze the given simple or compound assignment for warning-worthy
10947 /// operations.
10948 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10949   // Just recurse on the LHS.
10950   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10951 
10952   // We want to recurse on the RHS as normal unless we're assigning to
10953   // a bitfield.
10954   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10955     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10956                                   E->getOperatorLoc())) {
10957       // Recurse, ignoring any implicit conversions on the RHS.
10958       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10959                                         E->getOperatorLoc());
10960     }
10961   }
10962 
10963   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10964 
10965   // Diagnose implicitly sequentially-consistent atomic assignment.
10966   if (E->getLHS()->getType()->isAtomicType())
10967     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10968 }
10969 
10970 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10971 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10972                             SourceLocation CContext, unsigned diag,
10973                             bool pruneControlFlow = false) {
10974   if (pruneControlFlow) {
10975     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10976                           S.PDiag(diag)
10977                               << SourceType << T << E->getSourceRange()
10978                               << SourceRange(CContext));
10979     return;
10980   }
10981   S.Diag(E->getExprLoc(), diag)
10982     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10983 }
10984 
10985 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10986 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10987                             SourceLocation CContext,
10988                             unsigned diag, bool pruneControlFlow = false) {
10989   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10990 }
10991 
10992 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10993   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10994       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10995 }
10996 
10997 static void adornObjCBoolConversionDiagWithTernaryFixit(
10998     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10999   Expr *Ignored = SourceExpr->IgnoreImplicit();
11000   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11001     Ignored = OVE->getSourceExpr();
11002   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11003                      isa<BinaryOperator>(Ignored) ||
11004                      isa<CXXOperatorCallExpr>(Ignored);
11005   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11006   if (NeedsParens)
11007     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11008             << FixItHint::CreateInsertion(EndLoc, ")");
11009   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11010 }
11011 
11012 /// Diagnose an implicit cast from a floating point value to an integer value.
11013 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11014                                     SourceLocation CContext) {
11015   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11016   const bool PruneWarnings = S.inTemplateInstantiation();
11017 
11018   Expr *InnerE = E->IgnoreParenImpCasts();
11019   // We also want to warn on, e.g., "int i = -1.234"
11020   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11021     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11022       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11023 
11024   const bool IsLiteral =
11025       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11026 
11027   llvm::APFloat Value(0.0);
11028   bool IsConstant =
11029     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11030   if (!IsConstant) {
11031     if (isObjCSignedCharBool(S, T)) {
11032       return adornObjCBoolConversionDiagWithTernaryFixit(
11033           S, E,
11034           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11035               << E->getType());
11036     }
11037 
11038     return DiagnoseImpCast(S, E, T, CContext,
11039                            diag::warn_impcast_float_integer, PruneWarnings);
11040   }
11041 
11042   bool isExact = false;
11043 
11044   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11045                             T->hasUnsignedIntegerRepresentation());
11046   llvm::APFloat::opStatus Result = Value.convertToInteger(
11047       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11048 
11049   // FIXME: Force the precision of the source value down so we don't print
11050   // digits which are usually useless (we don't really care here if we
11051   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11052   // would automatically print the shortest representation, but it's a bit
11053   // tricky to implement.
11054   SmallString<16> PrettySourceValue;
11055   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11056   precision = (precision * 59 + 195) / 196;
11057   Value.toString(PrettySourceValue, precision);
11058 
11059   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11060     return adornObjCBoolConversionDiagWithTernaryFixit(
11061         S, E,
11062         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11063             << PrettySourceValue);
11064   }
11065 
11066   if (Result == llvm::APFloat::opOK && isExact) {
11067     if (IsLiteral) return;
11068     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11069                            PruneWarnings);
11070   }
11071 
11072   // Conversion of a floating-point value to a non-bool integer where the
11073   // integral part cannot be represented by the integer type is undefined.
11074   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11075     return DiagnoseImpCast(
11076         S, E, T, CContext,
11077         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11078                   : diag::warn_impcast_float_to_integer_out_of_range,
11079         PruneWarnings);
11080 
11081   unsigned DiagID = 0;
11082   if (IsLiteral) {
11083     // Warn on floating point literal to integer.
11084     DiagID = diag::warn_impcast_literal_float_to_integer;
11085   } else if (IntegerValue == 0) {
11086     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11087       return DiagnoseImpCast(S, E, T, CContext,
11088                              diag::warn_impcast_float_integer, PruneWarnings);
11089     }
11090     // Warn on non-zero to zero conversion.
11091     DiagID = diag::warn_impcast_float_to_integer_zero;
11092   } else {
11093     if (IntegerValue.isUnsigned()) {
11094       if (!IntegerValue.isMaxValue()) {
11095         return DiagnoseImpCast(S, E, T, CContext,
11096                                diag::warn_impcast_float_integer, PruneWarnings);
11097       }
11098     } else {  // IntegerValue.isSigned()
11099       if (!IntegerValue.isMaxSignedValue() &&
11100           !IntegerValue.isMinSignedValue()) {
11101         return DiagnoseImpCast(S, E, T, CContext,
11102                                diag::warn_impcast_float_integer, PruneWarnings);
11103       }
11104     }
11105     // Warn on evaluatable floating point expression to integer conversion.
11106     DiagID = diag::warn_impcast_float_to_integer;
11107   }
11108 
11109   SmallString<16> PrettyTargetValue;
11110   if (IsBool)
11111     PrettyTargetValue = Value.isZero() ? "false" : "true";
11112   else
11113     IntegerValue.toString(PrettyTargetValue);
11114 
11115   if (PruneWarnings) {
11116     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11117                           S.PDiag(DiagID)
11118                               << E->getType() << T.getUnqualifiedType()
11119                               << PrettySourceValue << PrettyTargetValue
11120                               << E->getSourceRange() << SourceRange(CContext));
11121   } else {
11122     S.Diag(E->getExprLoc(), DiagID)
11123         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11124         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11125   }
11126 }
11127 
11128 /// Analyze the given compound assignment for the possible losing of
11129 /// floating-point precision.
11130 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11131   assert(isa<CompoundAssignOperator>(E) &&
11132          "Must be compound assignment operation");
11133   // Recurse on the LHS and RHS in here
11134   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11135   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11136 
11137   if (E->getLHS()->getType()->isAtomicType())
11138     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11139 
11140   // Now check the outermost expression
11141   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11142   const auto *RBT = cast<CompoundAssignOperator>(E)
11143                         ->getComputationResultType()
11144                         ->getAs<BuiltinType>();
11145 
11146   // The below checks assume source is floating point.
11147   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11148 
11149   // If source is floating point but target is an integer.
11150   if (ResultBT->isInteger())
11151     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11152                            E->getExprLoc(), diag::warn_impcast_float_integer);
11153 
11154   if (!ResultBT->isFloatingPoint())
11155     return;
11156 
11157   // If both source and target are floating points, warn about losing precision.
11158   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11159       QualType(ResultBT, 0), QualType(RBT, 0));
11160   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11161     // warn about dropping FP rank.
11162     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11163                     diag::warn_impcast_float_result_precision);
11164 }
11165 
11166 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11167                                       IntRange Range) {
11168   if (!Range.Width) return "0";
11169 
11170   llvm::APSInt ValueInRange = Value;
11171   ValueInRange.setIsSigned(!Range.NonNegative);
11172   ValueInRange = ValueInRange.trunc(Range.Width);
11173   return ValueInRange.toString(10);
11174 }
11175 
11176 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11177   if (!isa<ImplicitCastExpr>(Ex))
11178     return false;
11179 
11180   Expr *InnerE = Ex->IgnoreParenImpCasts();
11181   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11182   const Type *Source =
11183     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11184   if (Target->isDependentType())
11185     return false;
11186 
11187   const BuiltinType *FloatCandidateBT =
11188     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11189   const Type *BoolCandidateType = ToBool ? Target : Source;
11190 
11191   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11192           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11193 }
11194 
11195 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11196                                              SourceLocation CC) {
11197   unsigned NumArgs = TheCall->getNumArgs();
11198   for (unsigned i = 0; i < NumArgs; ++i) {
11199     Expr *CurrA = TheCall->getArg(i);
11200     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11201       continue;
11202 
11203     bool IsSwapped = ((i > 0) &&
11204         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11205     IsSwapped |= ((i < (NumArgs - 1)) &&
11206         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11207     if (IsSwapped) {
11208       // Warn on this floating-point to bool conversion.
11209       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11210                       CurrA->getType(), CC,
11211                       diag::warn_impcast_floating_point_to_bool);
11212     }
11213   }
11214 }
11215 
11216 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11217                                    SourceLocation CC) {
11218   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11219                         E->getExprLoc()))
11220     return;
11221 
11222   // Don't warn on functions which have return type nullptr_t.
11223   if (isa<CallExpr>(E))
11224     return;
11225 
11226   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11227   const Expr::NullPointerConstantKind NullKind =
11228       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11229   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11230     return;
11231 
11232   // Return if target type is a safe conversion.
11233   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11234       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11235     return;
11236 
11237   SourceLocation Loc = E->getSourceRange().getBegin();
11238 
11239   // Venture through the macro stacks to get to the source of macro arguments.
11240   // The new location is a better location than the complete location that was
11241   // passed in.
11242   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11243   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11244 
11245   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11246   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11247     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11248         Loc, S.SourceMgr, S.getLangOpts());
11249     if (MacroName == "NULL")
11250       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11251   }
11252 
11253   // Only warn if the null and context location are in the same macro expansion.
11254   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11255     return;
11256 
11257   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11258       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11259       << FixItHint::CreateReplacement(Loc,
11260                                       S.getFixItZeroLiteralForType(T, Loc));
11261 }
11262 
11263 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11264                                   ObjCArrayLiteral *ArrayLiteral);
11265 
11266 static void
11267 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11268                            ObjCDictionaryLiteral *DictionaryLiteral);
11269 
11270 /// Check a single element within a collection literal against the
11271 /// target element type.
11272 static void checkObjCCollectionLiteralElement(Sema &S,
11273                                               QualType TargetElementType,
11274                                               Expr *Element,
11275                                               unsigned ElementKind) {
11276   // Skip a bitcast to 'id' or qualified 'id'.
11277   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11278     if (ICE->getCastKind() == CK_BitCast &&
11279         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11280       Element = ICE->getSubExpr();
11281   }
11282 
11283   QualType ElementType = Element->getType();
11284   ExprResult ElementResult(Element);
11285   if (ElementType->getAs<ObjCObjectPointerType>() &&
11286       S.CheckSingleAssignmentConstraints(TargetElementType,
11287                                          ElementResult,
11288                                          false, false)
11289         != Sema::Compatible) {
11290     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11291         << ElementType << ElementKind << TargetElementType
11292         << Element->getSourceRange();
11293   }
11294 
11295   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11296     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11297   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11298     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11299 }
11300 
11301 /// Check an Objective-C array literal being converted to the given
11302 /// target type.
11303 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11304                                   ObjCArrayLiteral *ArrayLiteral) {
11305   if (!S.NSArrayDecl)
11306     return;
11307 
11308   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11309   if (!TargetObjCPtr)
11310     return;
11311 
11312   if (TargetObjCPtr->isUnspecialized() ||
11313       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11314         != S.NSArrayDecl->getCanonicalDecl())
11315     return;
11316 
11317   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11318   if (TypeArgs.size() != 1)
11319     return;
11320 
11321   QualType TargetElementType = TypeArgs[0];
11322   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11323     checkObjCCollectionLiteralElement(S, TargetElementType,
11324                                       ArrayLiteral->getElement(I),
11325                                       0);
11326   }
11327 }
11328 
11329 /// Check an Objective-C dictionary literal being converted to the given
11330 /// target type.
11331 static void
11332 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11333                            ObjCDictionaryLiteral *DictionaryLiteral) {
11334   if (!S.NSDictionaryDecl)
11335     return;
11336 
11337   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11338   if (!TargetObjCPtr)
11339     return;
11340 
11341   if (TargetObjCPtr->isUnspecialized() ||
11342       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11343         != S.NSDictionaryDecl->getCanonicalDecl())
11344     return;
11345 
11346   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11347   if (TypeArgs.size() != 2)
11348     return;
11349 
11350   QualType TargetKeyType = TypeArgs[0];
11351   QualType TargetObjectType = TypeArgs[1];
11352   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11353     auto Element = DictionaryLiteral->getKeyValueElement(I);
11354     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11355     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11356   }
11357 }
11358 
11359 // Helper function to filter out cases for constant width constant conversion.
11360 // Don't warn on char array initialization or for non-decimal values.
11361 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11362                                           SourceLocation CC) {
11363   // If initializing from a constant, and the constant starts with '0',
11364   // then it is a binary, octal, or hexadecimal.  Allow these constants
11365   // to fill all the bits, even if there is a sign change.
11366   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11367     const char FirstLiteralCharacter =
11368         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11369     if (FirstLiteralCharacter == '0')
11370       return false;
11371   }
11372 
11373   // If the CC location points to a '{', and the type is char, then assume
11374   // assume it is an array initialization.
11375   if (CC.isValid() && T->isCharType()) {
11376     const char FirstContextCharacter =
11377         S.getSourceManager().getCharacterData(CC)[0];
11378     if (FirstContextCharacter == '{')
11379       return false;
11380   }
11381 
11382   return true;
11383 }
11384 
11385 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11386   const auto *IL = dyn_cast<IntegerLiteral>(E);
11387   if (!IL) {
11388     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11389       if (UO->getOpcode() == UO_Minus)
11390         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11391     }
11392   }
11393 
11394   return IL;
11395 }
11396 
11397 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11398   E = E->IgnoreParenImpCasts();
11399   SourceLocation ExprLoc = E->getExprLoc();
11400 
11401   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11402     BinaryOperator::Opcode Opc = BO->getOpcode();
11403     Expr::EvalResult Result;
11404     // Do not diagnose unsigned shifts.
11405     if (Opc == BO_Shl) {
11406       const auto *LHS = getIntegerLiteral(BO->getLHS());
11407       const auto *RHS = getIntegerLiteral(BO->getRHS());
11408       if (LHS && LHS->getValue() == 0)
11409         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11410       else if (!E->isValueDependent() && LHS && RHS &&
11411                RHS->getValue().isNonNegative() &&
11412                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11413         S.Diag(ExprLoc, diag::warn_left_shift_always)
11414             << (Result.Val.getInt() != 0);
11415       else if (E->getType()->isSignedIntegerType())
11416         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11417     }
11418   }
11419 
11420   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11421     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11422     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11423     if (!LHS || !RHS)
11424       return;
11425     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11426         (RHS->getValue() == 0 || RHS->getValue() == 1))
11427       // Do not diagnose common idioms.
11428       return;
11429     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11430       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11431   }
11432 }
11433 
11434 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11435                                     SourceLocation CC,
11436                                     bool *ICContext = nullptr,
11437                                     bool IsListInit = false) {
11438   if (E->isTypeDependent() || E->isValueDependent()) return;
11439 
11440   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11441   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11442   if (Source == Target) return;
11443   if (Target->isDependentType()) return;
11444 
11445   // If the conversion context location is invalid don't complain. We also
11446   // don't want to emit a warning if the issue occurs from the expansion of
11447   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11448   // delay this check as long as possible. Once we detect we are in that
11449   // scenario, we just return.
11450   if (CC.isInvalid())
11451     return;
11452 
11453   if (Source->isAtomicType())
11454     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11455 
11456   // Diagnose implicit casts to bool.
11457   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11458     if (isa<StringLiteral>(E))
11459       // Warn on string literal to bool.  Checks for string literals in logical
11460       // and expressions, for instance, assert(0 && "error here"), are
11461       // prevented by a check in AnalyzeImplicitConversions().
11462       return DiagnoseImpCast(S, E, T, CC,
11463                              diag::warn_impcast_string_literal_to_bool);
11464     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11465         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11466       // This covers the literal expressions that evaluate to Objective-C
11467       // objects.
11468       return DiagnoseImpCast(S, E, T, CC,
11469                              diag::warn_impcast_objective_c_literal_to_bool);
11470     }
11471     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11472       // Warn on pointer to bool conversion that is always true.
11473       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11474                                      SourceRange(CC));
11475     }
11476   }
11477 
11478   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11479   // is a typedef for signed char (macOS), then that constant value has to be 1
11480   // or 0.
11481   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11482     Expr::EvalResult Result;
11483     if (E->EvaluateAsInt(Result, S.getASTContext(),
11484                          Expr::SE_AllowSideEffects)) {
11485       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11486         adornObjCBoolConversionDiagWithTernaryFixit(
11487             S, E,
11488             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11489                 << Result.Val.getInt().toString(10));
11490       }
11491       return;
11492     }
11493   }
11494 
11495   // Check implicit casts from Objective-C collection literals to specialized
11496   // collection types, e.g., NSArray<NSString *> *.
11497   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11498     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11499   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11500     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11501 
11502   // Strip vector types.
11503   if (isa<VectorType>(Source)) {
11504     if (!isa<VectorType>(Target)) {
11505       if (S.SourceMgr.isInSystemMacro(CC))
11506         return;
11507       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11508     }
11509 
11510     // If the vector cast is cast between two vectors of the same size, it is
11511     // a bitcast, not a conversion.
11512     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11513       return;
11514 
11515     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11516     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11517   }
11518   if (auto VecTy = dyn_cast<VectorType>(Target))
11519     Target = VecTy->getElementType().getTypePtr();
11520 
11521   // Strip complex types.
11522   if (isa<ComplexType>(Source)) {
11523     if (!isa<ComplexType>(Target)) {
11524       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11525         return;
11526 
11527       return DiagnoseImpCast(S, E, T, CC,
11528                              S.getLangOpts().CPlusPlus
11529                                  ? diag::err_impcast_complex_scalar
11530                                  : diag::warn_impcast_complex_scalar);
11531     }
11532 
11533     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11534     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11535   }
11536 
11537   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11538   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11539 
11540   // If the source is floating point...
11541   if (SourceBT && SourceBT->isFloatingPoint()) {
11542     // ...and the target is floating point...
11543     if (TargetBT && TargetBT->isFloatingPoint()) {
11544       // ...then warn if we're dropping FP rank.
11545 
11546       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11547           QualType(SourceBT, 0), QualType(TargetBT, 0));
11548       if (Order > 0) {
11549         // Don't warn about float constants that are precisely
11550         // representable in the target type.
11551         Expr::EvalResult result;
11552         if (E->EvaluateAsRValue(result, S.Context)) {
11553           // Value might be a float, a float vector, or a float complex.
11554           if (IsSameFloatAfterCast(result.Val,
11555                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11556                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11557             return;
11558         }
11559 
11560         if (S.SourceMgr.isInSystemMacro(CC))
11561           return;
11562 
11563         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11564       }
11565       // ... or possibly if we're increasing rank, too
11566       else if (Order < 0) {
11567         if (S.SourceMgr.isInSystemMacro(CC))
11568           return;
11569 
11570         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11571       }
11572       return;
11573     }
11574 
11575     // If the target is integral, always warn.
11576     if (TargetBT && TargetBT->isInteger()) {
11577       if (S.SourceMgr.isInSystemMacro(CC))
11578         return;
11579 
11580       DiagnoseFloatingImpCast(S, E, T, CC);
11581     }
11582 
11583     // Detect the case where a call result is converted from floating-point to
11584     // to bool, and the final argument to the call is converted from bool, to
11585     // discover this typo:
11586     //
11587     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11588     //
11589     // FIXME: This is an incredibly special case; is there some more general
11590     // way to detect this class of misplaced-parentheses bug?
11591     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11592       // Check last argument of function call to see if it is an
11593       // implicit cast from a type matching the type the result
11594       // is being cast to.
11595       CallExpr *CEx = cast<CallExpr>(E);
11596       if (unsigned NumArgs = CEx->getNumArgs()) {
11597         Expr *LastA = CEx->getArg(NumArgs - 1);
11598         Expr *InnerE = LastA->IgnoreParenImpCasts();
11599         if (isa<ImplicitCastExpr>(LastA) &&
11600             InnerE->getType()->isBooleanType()) {
11601           // Warn on this floating-point to bool conversion
11602           DiagnoseImpCast(S, E, T, CC,
11603                           diag::warn_impcast_floating_point_to_bool);
11604         }
11605       }
11606     }
11607     return;
11608   }
11609 
11610   // Valid casts involving fixed point types should be accounted for here.
11611   if (Source->isFixedPointType()) {
11612     if (Target->isUnsaturatedFixedPointType()) {
11613       Expr::EvalResult Result;
11614       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11615                                   S.isConstantEvaluated())) {
11616         APFixedPoint Value = Result.Val.getFixedPoint();
11617         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11618         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11619         if (Value > MaxVal || Value < MinVal) {
11620           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11621                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11622                                     << Value.toString() << T
11623                                     << E->getSourceRange()
11624                                     << clang::SourceRange(CC));
11625           return;
11626         }
11627       }
11628     } else if (Target->isIntegerType()) {
11629       Expr::EvalResult Result;
11630       if (!S.isConstantEvaluated() &&
11631           E->EvaluateAsFixedPoint(Result, S.Context,
11632                                   Expr::SE_AllowSideEffects)) {
11633         APFixedPoint FXResult = Result.Val.getFixedPoint();
11634 
11635         bool Overflowed;
11636         llvm::APSInt IntResult = FXResult.convertToInt(
11637             S.Context.getIntWidth(T),
11638             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11639 
11640         if (Overflowed) {
11641           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11642                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11643                                     << FXResult.toString() << T
11644                                     << E->getSourceRange()
11645                                     << clang::SourceRange(CC));
11646           return;
11647         }
11648       }
11649     }
11650   } else if (Target->isUnsaturatedFixedPointType()) {
11651     if (Source->isIntegerType()) {
11652       Expr::EvalResult Result;
11653       if (!S.isConstantEvaluated() &&
11654           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11655         llvm::APSInt Value = Result.Val.getInt();
11656 
11657         bool Overflowed;
11658         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11659             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11660 
11661         if (Overflowed) {
11662           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11663                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11664                                     << Value.toString(/*Radix=*/10) << T
11665                                     << E->getSourceRange()
11666                                     << clang::SourceRange(CC));
11667           return;
11668         }
11669       }
11670     }
11671   }
11672 
11673   // If we are casting an integer type to a floating point type without
11674   // initialization-list syntax, we might lose accuracy if the floating
11675   // point type has a narrower significand than the integer type.
11676   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11677       TargetBT->isFloatingType() && !IsListInit) {
11678     // Determine the number of precision bits in the source integer type.
11679     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11680     unsigned int SourcePrecision = SourceRange.Width;
11681 
11682     // Determine the number of precision bits in the
11683     // target floating point type.
11684     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11685         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11686 
11687     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11688         SourcePrecision > TargetPrecision) {
11689 
11690       llvm::APSInt SourceInt;
11691       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11692         // If the source integer is a constant, convert it to the target
11693         // floating point type. Issue a warning if the value changes
11694         // during the whole conversion.
11695         llvm::APFloat TargetFloatValue(
11696             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11697         llvm::APFloat::opStatus ConversionStatus =
11698             TargetFloatValue.convertFromAPInt(
11699                 SourceInt, SourceBT->isSignedInteger(),
11700                 llvm::APFloat::rmNearestTiesToEven);
11701 
11702         if (ConversionStatus != llvm::APFloat::opOK) {
11703           std::string PrettySourceValue = SourceInt.toString(10);
11704           SmallString<32> PrettyTargetValue;
11705           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11706 
11707           S.DiagRuntimeBehavior(
11708               E->getExprLoc(), E,
11709               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11710                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11711                   << E->getSourceRange() << clang::SourceRange(CC));
11712         }
11713       } else {
11714         // Otherwise, the implicit conversion may lose precision.
11715         DiagnoseImpCast(S, E, T, CC,
11716                         diag::warn_impcast_integer_float_precision);
11717       }
11718     }
11719   }
11720 
11721   DiagnoseNullConversion(S, E, T, CC);
11722 
11723   S.DiscardMisalignedMemberAddress(Target, E);
11724 
11725   if (Target->isBooleanType())
11726     DiagnoseIntInBoolContext(S, E);
11727 
11728   if (!Source->isIntegerType() || !Target->isIntegerType())
11729     return;
11730 
11731   // TODO: remove this early return once the false positives for constant->bool
11732   // in templates, macros, etc, are reduced or removed.
11733   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11734     return;
11735 
11736   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11737       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11738     return adornObjCBoolConversionDiagWithTernaryFixit(
11739         S, E,
11740         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11741             << E->getType());
11742   }
11743 
11744   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11745   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11746 
11747   if (SourceRange.Width > TargetRange.Width) {
11748     // If the source is a constant, use a default-on diagnostic.
11749     // TODO: this should happen for bitfield stores, too.
11750     Expr::EvalResult Result;
11751     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11752                          S.isConstantEvaluated())) {
11753       llvm::APSInt Value(32);
11754       Value = Result.Val.getInt();
11755 
11756       if (S.SourceMgr.isInSystemMacro(CC))
11757         return;
11758 
11759       std::string PrettySourceValue = Value.toString(10);
11760       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11761 
11762       S.DiagRuntimeBehavior(
11763           E->getExprLoc(), E,
11764           S.PDiag(diag::warn_impcast_integer_precision_constant)
11765               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11766               << E->getSourceRange() << clang::SourceRange(CC));
11767       return;
11768     }
11769 
11770     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11771     if (S.SourceMgr.isInSystemMacro(CC))
11772       return;
11773 
11774     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11775       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11776                              /* pruneControlFlow */ true);
11777     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11778   }
11779 
11780   if (TargetRange.Width > SourceRange.Width) {
11781     if (auto *UO = dyn_cast<UnaryOperator>(E))
11782       if (UO->getOpcode() == UO_Minus)
11783         if (Source->isUnsignedIntegerType()) {
11784           if (Target->isUnsignedIntegerType())
11785             return DiagnoseImpCast(S, E, T, CC,
11786                                    diag::warn_impcast_high_order_zero_bits);
11787           if (Target->isSignedIntegerType())
11788             return DiagnoseImpCast(S, E, T, CC,
11789                                    diag::warn_impcast_nonnegative_result);
11790         }
11791   }
11792 
11793   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11794       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11795     // Warn when doing a signed to signed conversion, warn if the positive
11796     // source value is exactly the width of the target type, which will
11797     // cause a negative value to be stored.
11798 
11799     Expr::EvalResult Result;
11800     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11801         !S.SourceMgr.isInSystemMacro(CC)) {
11802       llvm::APSInt Value = Result.Val.getInt();
11803       if (isSameWidthConstantConversion(S, E, T, CC)) {
11804         std::string PrettySourceValue = Value.toString(10);
11805         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11806 
11807         S.DiagRuntimeBehavior(
11808             E->getExprLoc(), E,
11809             S.PDiag(diag::warn_impcast_integer_precision_constant)
11810                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11811                 << E->getSourceRange() << clang::SourceRange(CC));
11812         return;
11813       }
11814     }
11815 
11816     // Fall through for non-constants to give a sign conversion warning.
11817   }
11818 
11819   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11820       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11821        SourceRange.Width == TargetRange.Width)) {
11822     if (S.SourceMgr.isInSystemMacro(CC))
11823       return;
11824 
11825     unsigned DiagID = diag::warn_impcast_integer_sign;
11826 
11827     // Traditionally, gcc has warned about this under -Wsign-compare.
11828     // We also want to warn about it in -Wconversion.
11829     // So if -Wconversion is off, use a completely identical diagnostic
11830     // in the sign-compare group.
11831     // The conditional-checking code will
11832     if (ICContext) {
11833       DiagID = diag::warn_impcast_integer_sign_conditional;
11834       *ICContext = true;
11835     }
11836 
11837     return DiagnoseImpCast(S, E, T, CC, DiagID);
11838   }
11839 
11840   // Diagnose conversions between different enumeration types.
11841   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11842   // type, to give us better diagnostics.
11843   QualType SourceType = E->getType();
11844   if (!S.getLangOpts().CPlusPlus) {
11845     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11846       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11847         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11848         SourceType = S.Context.getTypeDeclType(Enum);
11849         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11850       }
11851   }
11852 
11853   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11854     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11855       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11856           TargetEnum->getDecl()->hasNameForLinkage() &&
11857           SourceEnum != TargetEnum) {
11858         if (S.SourceMgr.isInSystemMacro(CC))
11859           return;
11860 
11861         return DiagnoseImpCast(S, E, SourceType, T, CC,
11862                                diag::warn_impcast_different_enum_types);
11863       }
11864 }
11865 
11866 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11867                                      SourceLocation CC, QualType T);
11868 
11869 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11870                                     SourceLocation CC, bool &ICContext) {
11871   E = E->IgnoreParenImpCasts();
11872 
11873   if (isa<ConditionalOperator>(E))
11874     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11875 
11876   AnalyzeImplicitConversions(S, E, CC);
11877   if (E->getType() != T)
11878     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11879 }
11880 
11881 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11882                                      SourceLocation CC, QualType T) {
11883   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11884 
11885   bool Suspicious = false;
11886   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11887   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11888 
11889   if (T->isBooleanType())
11890     DiagnoseIntInBoolContext(S, E);
11891 
11892   // If -Wconversion would have warned about either of the candidates
11893   // for a signedness conversion to the context type...
11894   if (!Suspicious) return;
11895 
11896   // ...but it's currently ignored...
11897   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11898     return;
11899 
11900   // ...then check whether it would have warned about either of the
11901   // candidates for a signedness conversion to the condition type.
11902   if (E->getType() == T) return;
11903 
11904   Suspicious = false;
11905   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11906                           E->getType(), CC, &Suspicious);
11907   if (!Suspicious)
11908     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11909                             E->getType(), CC, &Suspicious);
11910 }
11911 
11912 /// Check conversion of given expression to boolean.
11913 /// Input argument E is a logical expression.
11914 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11915   if (S.getLangOpts().Bool)
11916     return;
11917   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11918     return;
11919   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11920 }
11921 
11922 namespace {
11923 struct AnalyzeImplicitConversionsWorkItem {
11924   Expr *E;
11925   SourceLocation CC;
11926   bool IsListInit;
11927 };
11928 }
11929 
11930 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
11931 /// that should be visited are added to WorkList.
11932 static void AnalyzeImplicitConversions(
11933     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
11934     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
11935   Expr *OrigE = Item.E;
11936   SourceLocation CC = Item.CC;
11937 
11938   QualType T = OrigE->getType();
11939   Expr *E = OrigE->IgnoreParenImpCasts();
11940 
11941   // Propagate whether we are in a C++ list initialization expression.
11942   // If so, we do not issue warnings for implicit int-float conversion
11943   // precision loss, because C++11 narrowing already handles it.
11944   bool IsListInit = Item.IsListInit ||
11945                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11946 
11947   if (E->isTypeDependent() || E->isValueDependent())
11948     return;
11949 
11950   Expr *SourceExpr = E;
11951   // Examine, but don't traverse into the source expression of an
11952   // OpaqueValueExpr, since it may have multiple parents and we don't want to
11953   // emit duplicate diagnostics. Its fine to examine the form or attempt to
11954   // evaluate it in the context of checking the specific conversion to T though.
11955   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11956     if (auto *Src = OVE->getSourceExpr())
11957       SourceExpr = Src;
11958 
11959   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
11960     if (UO->getOpcode() == UO_Not &&
11961         UO->getSubExpr()->isKnownToHaveBooleanValue())
11962       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11963           << OrigE->getSourceRange() << T->isBooleanType()
11964           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11965 
11966   // For conditional operators, we analyze the arguments as if they
11967   // were being fed directly into the output.
11968   if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) {
11969     CheckConditionalOperator(S, CO, CC, T);
11970     return;
11971   }
11972 
11973   // Check implicit argument conversions for function calls.
11974   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
11975     CheckImplicitArgumentConversions(S, Call, CC);
11976 
11977   // Go ahead and check any implicit conversions we might have skipped.
11978   // The non-canonical typecheck is just an optimization;
11979   // CheckImplicitConversion will filter out dead implicit conversions.
11980   if (SourceExpr->getType() != T)
11981     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
11982 
11983   // Now continue drilling into this expression.
11984 
11985   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11986     // The bound subexpressions in a PseudoObjectExpr are not reachable
11987     // as transitive children.
11988     // FIXME: Use a more uniform representation for this.
11989     for (auto *SE : POE->semantics())
11990       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11991         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
11992   }
11993 
11994   // Skip past explicit casts.
11995   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11996     E = CE->getSubExpr()->IgnoreParenImpCasts();
11997     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11998       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11999     WorkList.push_back({E, CC, IsListInit});
12000     return;
12001   }
12002 
12003   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12004     // Do a somewhat different check with comparison operators.
12005     if (BO->isComparisonOp())
12006       return AnalyzeComparison(S, BO);
12007 
12008     // And with simple assignments.
12009     if (BO->getOpcode() == BO_Assign)
12010       return AnalyzeAssignment(S, BO);
12011     // And with compound assignments.
12012     if (BO->isAssignmentOp())
12013       return AnalyzeCompoundAssignment(S, BO);
12014   }
12015 
12016   // These break the otherwise-useful invariant below.  Fortunately,
12017   // we don't really need to recurse into them, because any internal
12018   // expressions should have been analyzed already when they were
12019   // built into statements.
12020   if (isa<StmtExpr>(E)) return;
12021 
12022   // Don't descend into unevaluated contexts.
12023   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12024 
12025   // Now just recurse over the expression's children.
12026   CC = E->getExprLoc();
12027   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12028   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12029   for (Stmt *SubStmt : E->children()) {
12030     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12031     if (!ChildExpr)
12032       continue;
12033 
12034     if (IsLogicalAndOperator &&
12035         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12036       // Ignore checking string literals that are in logical and operators.
12037       // This is a common pattern for asserts.
12038       continue;
12039     WorkList.push_back({ChildExpr, CC, IsListInit});
12040   }
12041 
12042   if (BO && BO->isLogicalOp()) {
12043     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12044     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12045       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12046 
12047     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12048     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12049       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12050   }
12051 
12052   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12053     if (U->getOpcode() == UO_LNot) {
12054       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12055     } else if (U->getOpcode() != UO_AddrOf) {
12056       if (U->getSubExpr()->getType()->isAtomicType())
12057         S.Diag(U->getSubExpr()->getBeginLoc(),
12058                diag::warn_atomic_implicit_seq_cst);
12059     }
12060   }
12061 }
12062 
12063 /// AnalyzeImplicitConversions - Find and report any interesting
12064 /// implicit conversions in the given expression.  There are a couple
12065 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12066 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12067                                        bool IsListInit/*= false*/) {
12068   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12069   WorkList.push_back({OrigE, CC, IsListInit});
12070   while (!WorkList.empty())
12071     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12072 }
12073 
12074 /// Diagnose integer type and any valid implicit conversion to it.
12075 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12076   // Taking into account implicit conversions,
12077   // allow any integer.
12078   if (!E->getType()->isIntegerType()) {
12079     S.Diag(E->getBeginLoc(),
12080            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12081     return true;
12082   }
12083   // Potentially emit standard warnings for implicit conversions if enabled
12084   // using -Wconversion.
12085   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12086   return false;
12087 }
12088 
12089 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12090 // Returns true when emitting a warning about taking the address of a reference.
12091 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12092                               const PartialDiagnostic &PD) {
12093   E = E->IgnoreParenImpCasts();
12094 
12095   const FunctionDecl *FD = nullptr;
12096 
12097   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12098     if (!DRE->getDecl()->getType()->isReferenceType())
12099       return false;
12100   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12101     if (!M->getMemberDecl()->getType()->isReferenceType())
12102       return false;
12103   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12104     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12105       return false;
12106     FD = Call->getDirectCallee();
12107   } else {
12108     return false;
12109   }
12110 
12111   SemaRef.Diag(E->getExprLoc(), PD);
12112 
12113   // If possible, point to location of function.
12114   if (FD) {
12115     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12116   }
12117 
12118   return true;
12119 }
12120 
12121 // Returns true if the SourceLocation is expanded from any macro body.
12122 // Returns false if the SourceLocation is invalid, is from not in a macro
12123 // expansion, or is from expanded from a top-level macro argument.
12124 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12125   if (Loc.isInvalid())
12126     return false;
12127 
12128   while (Loc.isMacroID()) {
12129     if (SM.isMacroBodyExpansion(Loc))
12130       return true;
12131     Loc = SM.getImmediateMacroCallerLoc(Loc);
12132   }
12133 
12134   return false;
12135 }
12136 
12137 /// Diagnose pointers that are always non-null.
12138 /// \param E the expression containing the pointer
12139 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12140 /// compared to a null pointer
12141 /// \param IsEqual True when the comparison is equal to a null pointer
12142 /// \param Range Extra SourceRange to highlight in the diagnostic
12143 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12144                                         Expr::NullPointerConstantKind NullKind,
12145                                         bool IsEqual, SourceRange Range) {
12146   if (!E)
12147     return;
12148 
12149   // Don't warn inside macros.
12150   if (E->getExprLoc().isMacroID()) {
12151     const SourceManager &SM = getSourceManager();
12152     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12153         IsInAnyMacroBody(SM, Range.getBegin()))
12154       return;
12155   }
12156   E = E->IgnoreImpCasts();
12157 
12158   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12159 
12160   if (isa<CXXThisExpr>(E)) {
12161     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12162                                 : diag::warn_this_bool_conversion;
12163     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12164     return;
12165   }
12166 
12167   bool IsAddressOf = false;
12168 
12169   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12170     if (UO->getOpcode() != UO_AddrOf)
12171       return;
12172     IsAddressOf = true;
12173     E = UO->getSubExpr();
12174   }
12175 
12176   if (IsAddressOf) {
12177     unsigned DiagID = IsCompare
12178                           ? diag::warn_address_of_reference_null_compare
12179                           : diag::warn_address_of_reference_bool_conversion;
12180     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12181                                          << IsEqual;
12182     if (CheckForReference(*this, E, PD)) {
12183       return;
12184     }
12185   }
12186 
12187   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12188     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12189     std::string Str;
12190     llvm::raw_string_ostream S(Str);
12191     E->printPretty(S, nullptr, getPrintingPolicy());
12192     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12193                                 : diag::warn_cast_nonnull_to_bool;
12194     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12195       << E->getSourceRange() << Range << IsEqual;
12196     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12197   };
12198 
12199   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12200   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12201     if (auto *Callee = Call->getDirectCallee()) {
12202       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12203         ComplainAboutNonnullParamOrCall(A);
12204         return;
12205       }
12206     }
12207   }
12208 
12209   // Expect to find a single Decl.  Skip anything more complicated.
12210   ValueDecl *D = nullptr;
12211   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12212     D = R->getDecl();
12213   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12214     D = M->getMemberDecl();
12215   }
12216 
12217   // Weak Decls can be null.
12218   if (!D || D->isWeak())
12219     return;
12220 
12221   // Check for parameter decl with nonnull attribute
12222   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12223     if (getCurFunction() &&
12224         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12225       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12226         ComplainAboutNonnullParamOrCall(A);
12227         return;
12228       }
12229 
12230       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12231         // Skip function template not specialized yet.
12232         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12233           return;
12234         auto ParamIter = llvm::find(FD->parameters(), PV);
12235         assert(ParamIter != FD->param_end());
12236         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12237 
12238         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12239           if (!NonNull->args_size()) {
12240               ComplainAboutNonnullParamOrCall(NonNull);
12241               return;
12242           }
12243 
12244           for (const ParamIdx &ArgNo : NonNull->args()) {
12245             if (ArgNo.getASTIndex() == ParamNo) {
12246               ComplainAboutNonnullParamOrCall(NonNull);
12247               return;
12248             }
12249           }
12250         }
12251       }
12252     }
12253   }
12254 
12255   QualType T = D->getType();
12256   const bool IsArray = T->isArrayType();
12257   const bool IsFunction = T->isFunctionType();
12258 
12259   // Address of function is used to silence the function warning.
12260   if (IsAddressOf && IsFunction) {
12261     return;
12262   }
12263 
12264   // Found nothing.
12265   if (!IsAddressOf && !IsFunction && !IsArray)
12266     return;
12267 
12268   // Pretty print the expression for the diagnostic.
12269   std::string Str;
12270   llvm::raw_string_ostream S(Str);
12271   E->printPretty(S, nullptr, getPrintingPolicy());
12272 
12273   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12274                               : diag::warn_impcast_pointer_to_bool;
12275   enum {
12276     AddressOf,
12277     FunctionPointer,
12278     ArrayPointer
12279   } DiagType;
12280   if (IsAddressOf)
12281     DiagType = AddressOf;
12282   else if (IsFunction)
12283     DiagType = FunctionPointer;
12284   else if (IsArray)
12285     DiagType = ArrayPointer;
12286   else
12287     llvm_unreachable("Could not determine diagnostic.");
12288   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12289                                 << Range << IsEqual;
12290 
12291   if (!IsFunction)
12292     return;
12293 
12294   // Suggest '&' to silence the function warning.
12295   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12296       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12297 
12298   // Check to see if '()' fixit should be emitted.
12299   QualType ReturnType;
12300   UnresolvedSet<4> NonTemplateOverloads;
12301   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12302   if (ReturnType.isNull())
12303     return;
12304 
12305   if (IsCompare) {
12306     // There are two cases here.  If there is null constant, the only suggest
12307     // for a pointer return type.  If the null is 0, then suggest if the return
12308     // type is a pointer or an integer type.
12309     if (!ReturnType->isPointerType()) {
12310       if (NullKind == Expr::NPCK_ZeroExpression ||
12311           NullKind == Expr::NPCK_ZeroLiteral) {
12312         if (!ReturnType->isIntegerType())
12313           return;
12314       } else {
12315         return;
12316       }
12317     }
12318   } else { // !IsCompare
12319     // For function to bool, only suggest if the function pointer has bool
12320     // return type.
12321     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12322       return;
12323   }
12324   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12325       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12326 }
12327 
12328 /// Diagnoses "dangerous" implicit conversions within the given
12329 /// expression (which is a full expression).  Implements -Wconversion
12330 /// and -Wsign-compare.
12331 ///
12332 /// \param CC the "context" location of the implicit conversion, i.e.
12333 ///   the most location of the syntactic entity requiring the implicit
12334 ///   conversion
12335 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12336   // Don't diagnose in unevaluated contexts.
12337   if (isUnevaluatedContext())
12338     return;
12339 
12340   // Don't diagnose for value- or type-dependent expressions.
12341   if (E->isTypeDependent() || E->isValueDependent())
12342     return;
12343 
12344   // Check for array bounds violations in cases where the check isn't triggered
12345   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12346   // ArraySubscriptExpr is on the RHS of a variable initialization.
12347   CheckArrayAccess(E);
12348 
12349   // This is not the right CC for (e.g.) a variable initialization.
12350   AnalyzeImplicitConversions(*this, E, CC);
12351 }
12352 
12353 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12354 /// Input argument E is a logical expression.
12355 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12356   ::CheckBoolLikeConversion(*this, E, CC);
12357 }
12358 
12359 /// Diagnose when expression is an integer constant expression and its evaluation
12360 /// results in integer overflow
12361 void Sema::CheckForIntOverflow (Expr *E) {
12362   // Use a work list to deal with nested struct initializers.
12363   SmallVector<Expr *, 2> Exprs(1, E);
12364 
12365   do {
12366     Expr *OriginalE = Exprs.pop_back_val();
12367     Expr *E = OriginalE->IgnoreParenCasts();
12368 
12369     if (isa<BinaryOperator>(E)) {
12370       E->EvaluateForOverflow(Context);
12371       continue;
12372     }
12373 
12374     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12375       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12376     else if (isa<ObjCBoxedExpr>(OriginalE))
12377       E->EvaluateForOverflow(Context);
12378     else if (auto Call = dyn_cast<CallExpr>(E))
12379       Exprs.append(Call->arg_begin(), Call->arg_end());
12380     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12381       Exprs.append(Message->arg_begin(), Message->arg_end());
12382   } while (!Exprs.empty());
12383 }
12384 
12385 namespace {
12386 
12387 /// Visitor for expressions which looks for unsequenced operations on the
12388 /// same object.
12389 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12390   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12391 
12392   /// A tree of sequenced regions within an expression. Two regions are
12393   /// unsequenced if one is an ancestor or a descendent of the other. When we
12394   /// finish processing an expression with sequencing, such as a comma
12395   /// expression, we fold its tree nodes into its parent, since they are
12396   /// unsequenced with respect to nodes we will visit later.
12397   class SequenceTree {
12398     struct Value {
12399       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12400       unsigned Parent : 31;
12401       unsigned Merged : 1;
12402     };
12403     SmallVector<Value, 8> Values;
12404 
12405   public:
12406     /// A region within an expression which may be sequenced with respect
12407     /// to some other region.
12408     class Seq {
12409       friend class SequenceTree;
12410 
12411       unsigned Index;
12412 
12413       explicit Seq(unsigned N) : Index(N) {}
12414 
12415     public:
12416       Seq() : Index(0) {}
12417     };
12418 
12419     SequenceTree() { Values.push_back(Value(0)); }
12420     Seq root() const { return Seq(0); }
12421 
12422     /// Create a new sequence of operations, which is an unsequenced
12423     /// subset of \p Parent. This sequence of operations is sequenced with
12424     /// respect to other children of \p Parent.
12425     Seq allocate(Seq Parent) {
12426       Values.push_back(Value(Parent.Index));
12427       return Seq(Values.size() - 1);
12428     }
12429 
12430     /// Merge a sequence of operations into its parent.
12431     void merge(Seq S) {
12432       Values[S.Index].Merged = true;
12433     }
12434 
12435     /// Determine whether two operations are unsequenced. This operation
12436     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12437     /// should have been merged into its parent as appropriate.
12438     bool isUnsequenced(Seq Cur, Seq Old) {
12439       unsigned C = representative(Cur.Index);
12440       unsigned Target = representative(Old.Index);
12441       while (C >= Target) {
12442         if (C == Target)
12443           return true;
12444         C = Values[C].Parent;
12445       }
12446       return false;
12447     }
12448 
12449   private:
12450     /// Pick a representative for a sequence.
12451     unsigned representative(unsigned K) {
12452       if (Values[K].Merged)
12453         // Perform path compression as we go.
12454         return Values[K].Parent = representative(Values[K].Parent);
12455       return K;
12456     }
12457   };
12458 
12459   /// An object for which we can track unsequenced uses.
12460   using Object = const NamedDecl *;
12461 
12462   /// Different flavors of object usage which we track. We only track the
12463   /// least-sequenced usage of each kind.
12464   enum UsageKind {
12465     /// A read of an object. Multiple unsequenced reads are OK.
12466     UK_Use,
12467 
12468     /// A modification of an object which is sequenced before the value
12469     /// computation of the expression, such as ++n in C++.
12470     UK_ModAsValue,
12471 
12472     /// A modification of an object which is not sequenced before the value
12473     /// computation of the expression, such as n++.
12474     UK_ModAsSideEffect,
12475 
12476     UK_Count = UK_ModAsSideEffect + 1
12477   };
12478 
12479   /// Bundle together a sequencing region and the expression corresponding
12480   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12481   struct Usage {
12482     const Expr *UsageExpr;
12483     SequenceTree::Seq Seq;
12484 
12485     Usage() : UsageExpr(nullptr), Seq() {}
12486   };
12487 
12488   struct UsageInfo {
12489     Usage Uses[UK_Count];
12490 
12491     /// Have we issued a diagnostic for this object already?
12492     bool Diagnosed;
12493 
12494     UsageInfo() : Uses(), Diagnosed(false) {}
12495   };
12496   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12497 
12498   Sema &SemaRef;
12499 
12500   /// Sequenced regions within the expression.
12501   SequenceTree Tree;
12502 
12503   /// Declaration modifications and references which we have seen.
12504   UsageInfoMap UsageMap;
12505 
12506   /// The region we are currently within.
12507   SequenceTree::Seq Region;
12508 
12509   /// Filled in with declarations which were modified as a side-effect
12510   /// (that is, post-increment operations).
12511   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12512 
12513   /// Expressions to check later. We defer checking these to reduce
12514   /// stack usage.
12515   SmallVectorImpl<const Expr *> &WorkList;
12516 
12517   /// RAII object wrapping the visitation of a sequenced subexpression of an
12518   /// expression. At the end of this process, the side-effects of the evaluation
12519   /// become sequenced with respect to the value computation of the result, so
12520   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12521   /// UK_ModAsValue.
12522   struct SequencedSubexpression {
12523     SequencedSubexpression(SequenceChecker &Self)
12524       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12525       Self.ModAsSideEffect = &ModAsSideEffect;
12526     }
12527 
12528     ~SequencedSubexpression() {
12529       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12530         // Add a new usage with usage kind UK_ModAsValue, and then restore
12531         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12532         // the previous one was empty).
12533         UsageInfo &UI = Self.UsageMap[M.first];
12534         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12535         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12536         SideEffectUsage = M.second;
12537       }
12538       Self.ModAsSideEffect = OldModAsSideEffect;
12539     }
12540 
12541     SequenceChecker &Self;
12542     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12543     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12544   };
12545 
12546   /// RAII object wrapping the visitation of a subexpression which we might
12547   /// choose to evaluate as a constant. If any subexpression is evaluated and
12548   /// found to be non-constant, this allows us to suppress the evaluation of
12549   /// the outer expression.
12550   class EvaluationTracker {
12551   public:
12552     EvaluationTracker(SequenceChecker &Self)
12553         : Self(Self), Prev(Self.EvalTracker) {
12554       Self.EvalTracker = this;
12555     }
12556 
12557     ~EvaluationTracker() {
12558       Self.EvalTracker = Prev;
12559       if (Prev)
12560         Prev->EvalOK &= EvalOK;
12561     }
12562 
12563     bool evaluate(const Expr *E, bool &Result) {
12564       if (!EvalOK || E->isValueDependent())
12565         return false;
12566       EvalOK = E->EvaluateAsBooleanCondition(
12567           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12568       return EvalOK;
12569     }
12570 
12571   private:
12572     SequenceChecker &Self;
12573     EvaluationTracker *Prev;
12574     bool EvalOK = true;
12575   } *EvalTracker = nullptr;
12576 
12577   /// Find the object which is produced by the specified expression,
12578   /// if any.
12579   Object getObject(const Expr *E, bool Mod) const {
12580     E = E->IgnoreParenCasts();
12581     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12582       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12583         return getObject(UO->getSubExpr(), Mod);
12584     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12585       if (BO->getOpcode() == BO_Comma)
12586         return getObject(BO->getRHS(), Mod);
12587       if (Mod && BO->isAssignmentOp())
12588         return getObject(BO->getLHS(), Mod);
12589     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12590       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12591       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12592         return ME->getMemberDecl();
12593     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12594       // FIXME: If this is a reference, map through to its value.
12595       return DRE->getDecl();
12596     return nullptr;
12597   }
12598 
12599   /// Note that an object \p O was modified or used by an expression
12600   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12601   /// the object \p O as obtained via the \p UsageMap.
12602   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12603     // Get the old usage for the given object and usage kind.
12604     Usage &U = UI.Uses[UK];
12605     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12606       // If we have a modification as side effect and are in a sequenced
12607       // subexpression, save the old Usage so that we can restore it later
12608       // in SequencedSubexpression::~SequencedSubexpression.
12609       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12610         ModAsSideEffect->push_back(std::make_pair(O, U));
12611       // Then record the new usage with the current sequencing region.
12612       U.UsageExpr = UsageExpr;
12613       U.Seq = Region;
12614     }
12615   }
12616 
12617   /// Check whether a modification or use of an object \p O in an expression
12618   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12619   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12620   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12621   /// usage and false we are checking for a mod-use unsequenced usage.
12622   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12623                   UsageKind OtherKind, bool IsModMod) {
12624     if (UI.Diagnosed)
12625       return;
12626 
12627     const Usage &U = UI.Uses[OtherKind];
12628     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12629       return;
12630 
12631     const Expr *Mod = U.UsageExpr;
12632     const Expr *ModOrUse = UsageExpr;
12633     if (OtherKind == UK_Use)
12634       std::swap(Mod, ModOrUse);
12635 
12636     SemaRef.DiagRuntimeBehavior(
12637         Mod->getExprLoc(), {Mod, ModOrUse},
12638         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12639                                : diag::warn_unsequenced_mod_use)
12640             << O << SourceRange(ModOrUse->getExprLoc()));
12641     UI.Diagnosed = true;
12642   }
12643 
12644   // A note on note{Pre, Post}{Use, Mod}:
12645   //
12646   // (It helps to follow the algorithm with an expression such as
12647   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12648   //  operations before C++17 and both are well-defined in C++17).
12649   //
12650   // When visiting a node which uses/modify an object we first call notePreUse
12651   // or notePreMod before visiting its sub-expression(s). At this point the
12652   // children of the current node have not yet been visited and so the eventual
12653   // uses/modifications resulting from the children of the current node have not
12654   // been recorded yet.
12655   //
12656   // We then visit the children of the current node. After that notePostUse or
12657   // notePostMod is called. These will 1) detect an unsequenced modification
12658   // as side effect (as in "k++ + k") and 2) add a new usage with the
12659   // appropriate usage kind.
12660   //
12661   // We also have to be careful that some operation sequences modification as
12662   // side effect as well (for example: || or ,). To account for this we wrap
12663   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12664   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12665   // which record usages which are modifications as side effect, and then
12666   // downgrade them (or more accurately restore the previous usage which was a
12667   // modification as side effect) when exiting the scope of the sequenced
12668   // subexpression.
12669 
12670   void notePreUse(Object O, const Expr *UseExpr) {
12671     UsageInfo &UI = UsageMap[O];
12672     // Uses conflict with other modifications.
12673     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12674   }
12675 
12676   void notePostUse(Object O, const Expr *UseExpr) {
12677     UsageInfo &UI = UsageMap[O];
12678     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12679                /*IsModMod=*/false);
12680     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12681   }
12682 
12683   void notePreMod(Object O, const Expr *ModExpr) {
12684     UsageInfo &UI = UsageMap[O];
12685     // Modifications conflict with other modifications and with uses.
12686     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12687     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12688   }
12689 
12690   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12691     UsageInfo &UI = UsageMap[O];
12692     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12693                /*IsModMod=*/true);
12694     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12695   }
12696 
12697 public:
12698   SequenceChecker(Sema &S, const Expr *E,
12699                   SmallVectorImpl<const Expr *> &WorkList)
12700       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12701     Visit(E);
12702     // Silence a -Wunused-private-field since WorkList is now unused.
12703     // TODO: Evaluate if it can be used, and if not remove it.
12704     (void)this->WorkList;
12705   }
12706 
12707   void VisitStmt(const Stmt *S) {
12708     // Skip all statements which aren't expressions for now.
12709   }
12710 
12711   void VisitExpr(const Expr *E) {
12712     // By default, just recurse to evaluated subexpressions.
12713     Base::VisitStmt(E);
12714   }
12715 
12716   void VisitCastExpr(const CastExpr *E) {
12717     Object O = Object();
12718     if (E->getCastKind() == CK_LValueToRValue)
12719       O = getObject(E->getSubExpr(), false);
12720 
12721     if (O)
12722       notePreUse(O, E);
12723     VisitExpr(E);
12724     if (O)
12725       notePostUse(O, E);
12726   }
12727 
12728   void VisitSequencedExpressions(const Expr *SequencedBefore,
12729                                  const Expr *SequencedAfter) {
12730     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12731     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12732     SequenceTree::Seq OldRegion = Region;
12733 
12734     {
12735       SequencedSubexpression SeqBefore(*this);
12736       Region = BeforeRegion;
12737       Visit(SequencedBefore);
12738     }
12739 
12740     Region = AfterRegion;
12741     Visit(SequencedAfter);
12742 
12743     Region = OldRegion;
12744 
12745     Tree.merge(BeforeRegion);
12746     Tree.merge(AfterRegion);
12747   }
12748 
12749   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12750     // C++17 [expr.sub]p1:
12751     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12752     //   expression E1 is sequenced before the expression E2.
12753     if (SemaRef.getLangOpts().CPlusPlus17)
12754       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12755     else {
12756       Visit(ASE->getLHS());
12757       Visit(ASE->getRHS());
12758     }
12759   }
12760 
12761   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12762   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12763   void VisitBinPtrMem(const BinaryOperator *BO) {
12764     // C++17 [expr.mptr.oper]p4:
12765     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12766     //  the expression E1 is sequenced before the expression E2.
12767     if (SemaRef.getLangOpts().CPlusPlus17)
12768       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12769     else {
12770       Visit(BO->getLHS());
12771       Visit(BO->getRHS());
12772     }
12773   }
12774 
12775   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12776   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12777   void VisitBinShlShr(const BinaryOperator *BO) {
12778     // C++17 [expr.shift]p4:
12779     //  The expression E1 is sequenced before the expression E2.
12780     if (SemaRef.getLangOpts().CPlusPlus17)
12781       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12782     else {
12783       Visit(BO->getLHS());
12784       Visit(BO->getRHS());
12785     }
12786   }
12787 
12788   void VisitBinComma(const BinaryOperator *BO) {
12789     // C++11 [expr.comma]p1:
12790     //   Every value computation and side effect associated with the left
12791     //   expression is sequenced before every value computation and side
12792     //   effect associated with the right expression.
12793     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12794   }
12795 
12796   void VisitBinAssign(const BinaryOperator *BO) {
12797     SequenceTree::Seq RHSRegion;
12798     SequenceTree::Seq LHSRegion;
12799     if (SemaRef.getLangOpts().CPlusPlus17) {
12800       RHSRegion = Tree.allocate(Region);
12801       LHSRegion = Tree.allocate(Region);
12802     } else {
12803       RHSRegion = Region;
12804       LHSRegion = Region;
12805     }
12806     SequenceTree::Seq OldRegion = Region;
12807 
12808     // C++11 [expr.ass]p1:
12809     //  [...] the assignment is sequenced after the value computation
12810     //  of the right and left operands, [...]
12811     //
12812     // so check it before inspecting the operands and update the
12813     // map afterwards.
12814     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12815     if (O)
12816       notePreMod(O, BO);
12817 
12818     if (SemaRef.getLangOpts().CPlusPlus17) {
12819       // C++17 [expr.ass]p1:
12820       //  [...] The right operand is sequenced before the left operand. [...]
12821       {
12822         SequencedSubexpression SeqBefore(*this);
12823         Region = RHSRegion;
12824         Visit(BO->getRHS());
12825       }
12826 
12827       Region = LHSRegion;
12828       Visit(BO->getLHS());
12829 
12830       if (O && isa<CompoundAssignOperator>(BO))
12831         notePostUse(O, BO);
12832 
12833     } else {
12834       // C++11 does not specify any sequencing between the LHS and RHS.
12835       Region = LHSRegion;
12836       Visit(BO->getLHS());
12837 
12838       if (O && isa<CompoundAssignOperator>(BO))
12839         notePostUse(O, BO);
12840 
12841       Region = RHSRegion;
12842       Visit(BO->getRHS());
12843     }
12844 
12845     // C++11 [expr.ass]p1:
12846     //  the assignment is sequenced [...] before the value computation of the
12847     //  assignment expression.
12848     // C11 6.5.16/3 has no such rule.
12849     Region = OldRegion;
12850     if (O)
12851       notePostMod(O, BO,
12852                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12853                                                   : UK_ModAsSideEffect);
12854     if (SemaRef.getLangOpts().CPlusPlus17) {
12855       Tree.merge(RHSRegion);
12856       Tree.merge(LHSRegion);
12857     }
12858   }
12859 
12860   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12861     VisitBinAssign(CAO);
12862   }
12863 
12864   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12865   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12866   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12867     Object O = getObject(UO->getSubExpr(), true);
12868     if (!O)
12869       return VisitExpr(UO);
12870 
12871     notePreMod(O, UO);
12872     Visit(UO->getSubExpr());
12873     // C++11 [expr.pre.incr]p1:
12874     //   the expression ++x is equivalent to x+=1
12875     notePostMod(O, UO,
12876                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12877                                                 : UK_ModAsSideEffect);
12878   }
12879 
12880   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12881   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12882   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12883     Object O = getObject(UO->getSubExpr(), true);
12884     if (!O)
12885       return VisitExpr(UO);
12886 
12887     notePreMod(O, UO);
12888     Visit(UO->getSubExpr());
12889     notePostMod(O, UO, UK_ModAsSideEffect);
12890   }
12891 
12892   void VisitBinLOr(const BinaryOperator *BO) {
12893     // C++11 [expr.log.or]p2:
12894     //  If the second expression is evaluated, every value computation and
12895     //  side effect associated with the first expression is sequenced before
12896     //  every value computation and side effect associated with the
12897     //  second expression.
12898     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12899     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12900     SequenceTree::Seq OldRegion = Region;
12901 
12902     EvaluationTracker Eval(*this);
12903     {
12904       SequencedSubexpression Sequenced(*this);
12905       Region = LHSRegion;
12906       Visit(BO->getLHS());
12907     }
12908 
12909     // C++11 [expr.log.or]p1:
12910     //  [...] the second operand is not evaluated if the first operand
12911     //  evaluates to true.
12912     bool EvalResult = false;
12913     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12914     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
12915     if (ShouldVisitRHS) {
12916       Region = RHSRegion;
12917       Visit(BO->getRHS());
12918     }
12919 
12920     Region = OldRegion;
12921     Tree.merge(LHSRegion);
12922     Tree.merge(RHSRegion);
12923   }
12924 
12925   void VisitBinLAnd(const BinaryOperator *BO) {
12926     // C++11 [expr.log.and]p2:
12927     //  If the second expression is evaluated, every value computation and
12928     //  side effect associated with the first expression is sequenced before
12929     //  every value computation and side effect associated with the
12930     //  second expression.
12931     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12932     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12933     SequenceTree::Seq OldRegion = Region;
12934 
12935     EvaluationTracker Eval(*this);
12936     {
12937       SequencedSubexpression Sequenced(*this);
12938       Region = LHSRegion;
12939       Visit(BO->getLHS());
12940     }
12941 
12942     // C++11 [expr.log.and]p1:
12943     //  [...] the second operand is not evaluated if the first operand is false.
12944     bool EvalResult = false;
12945     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12946     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
12947     if (ShouldVisitRHS) {
12948       Region = RHSRegion;
12949       Visit(BO->getRHS());
12950     }
12951 
12952     Region = OldRegion;
12953     Tree.merge(LHSRegion);
12954     Tree.merge(RHSRegion);
12955   }
12956 
12957   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12958     // C++11 [expr.cond]p1:
12959     //  [...] Every value computation and side effect associated with the first
12960     //  expression is sequenced before every value computation and side effect
12961     //  associated with the second or third expression.
12962     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12963 
12964     // No sequencing is specified between the true and false expression.
12965     // However since exactly one of both is going to be evaluated we can
12966     // consider them to be sequenced. This is needed to avoid warning on
12967     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12968     // both the true and false expressions because we can't evaluate x.
12969     // This will still allow us to detect an expression like (pre C++17)
12970     // "(x ? y += 1 : y += 2) = y".
12971     //
12972     // We don't wrap the visitation of the true and false expression with
12973     // SequencedSubexpression because we don't want to downgrade modifications
12974     // as side effect in the true and false expressions after the visition
12975     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12976     // not warn between the two "y++", but we should warn between the "y++"
12977     // and the "y".
12978     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12979     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12980     SequenceTree::Seq OldRegion = Region;
12981 
12982     EvaluationTracker Eval(*this);
12983     {
12984       SequencedSubexpression Sequenced(*this);
12985       Region = ConditionRegion;
12986       Visit(CO->getCond());
12987     }
12988 
12989     // C++11 [expr.cond]p1:
12990     // [...] The first expression is contextually converted to bool (Clause 4).
12991     // It is evaluated and if it is true, the result of the conditional
12992     // expression is the value of the second expression, otherwise that of the
12993     // third expression. Only one of the second and third expressions is
12994     // evaluated. [...]
12995     bool EvalResult = false;
12996     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12997     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
12998     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
12999     if (ShouldVisitTrueExpr) {
13000       Region = TrueRegion;
13001       Visit(CO->getTrueExpr());
13002     }
13003     if (ShouldVisitFalseExpr) {
13004       Region = FalseRegion;
13005       Visit(CO->getFalseExpr());
13006     }
13007 
13008     Region = OldRegion;
13009     Tree.merge(ConditionRegion);
13010     Tree.merge(TrueRegion);
13011     Tree.merge(FalseRegion);
13012   }
13013 
13014   void VisitCallExpr(const CallExpr *CE) {
13015     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13016 
13017     if (CE->isUnevaluatedBuiltinCall(Context))
13018       return;
13019 
13020     // C++11 [intro.execution]p15:
13021     //   When calling a function [...], every value computation and side effect
13022     //   associated with any argument expression, or with the postfix expression
13023     //   designating the called function, is sequenced before execution of every
13024     //   expression or statement in the body of the function [and thus before
13025     //   the value computation of its result].
13026     SequencedSubexpression Sequenced(*this);
13027     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13028       // C++17 [expr.call]p5
13029       //   The postfix-expression is sequenced before each expression in the
13030       //   expression-list and any default argument. [...]
13031       SequenceTree::Seq CalleeRegion;
13032       SequenceTree::Seq OtherRegion;
13033       if (SemaRef.getLangOpts().CPlusPlus17) {
13034         CalleeRegion = Tree.allocate(Region);
13035         OtherRegion = Tree.allocate(Region);
13036       } else {
13037         CalleeRegion = Region;
13038         OtherRegion = Region;
13039       }
13040       SequenceTree::Seq OldRegion = Region;
13041 
13042       // Visit the callee expression first.
13043       Region = CalleeRegion;
13044       if (SemaRef.getLangOpts().CPlusPlus17) {
13045         SequencedSubexpression Sequenced(*this);
13046         Visit(CE->getCallee());
13047       } else {
13048         Visit(CE->getCallee());
13049       }
13050 
13051       // Then visit the argument expressions.
13052       Region = OtherRegion;
13053       for (const Expr *Argument : CE->arguments())
13054         Visit(Argument);
13055 
13056       Region = OldRegion;
13057       if (SemaRef.getLangOpts().CPlusPlus17) {
13058         Tree.merge(CalleeRegion);
13059         Tree.merge(OtherRegion);
13060       }
13061     });
13062   }
13063 
13064   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13065     // C++17 [over.match.oper]p2:
13066     //   [...] the operator notation is first transformed to the equivalent
13067     //   function-call notation as summarized in Table 12 (where @ denotes one
13068     //   of the operators covered in the specified subclause). However, the
13069     //   operands are sequenced in the order prescribed for the built-in
13070     //   operator (Clause 8).
13071     //
13072     // From the above only overloaded binary operators and overloaded call
13073     // operators have sequencing rules in C++17 that we need to handle
13074     // separately.
13075     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13076         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13077       return VisitCallExpr(CXXOCE);
13078 
13079     enum {
13080       NoSequencing,
13081       LHSBeforeRHS,
13082       RHSBeforeLHS,
13083       LHSBeforeRest
13084     } SequencingKind;
13085     switch (CXXOCE->getOperator()) {
13086     case OO_Equal:
13087     case OO_PlusEqual:
13088     case OO_MinusEqual:
13089     case OO_StarEqual:
13090     case OO_SlashEqual:
13091     case OO_PercentEqual:
13092     case OO_CaretEqual:
13093     case OO_AmpEqual:
13094     case OO_PipeEqual:
13095     case OO_LessLessEqual:
13096     case OO_GreaterGreaterEqual:
13097       SequencingKind = RHSBeforeLHS;
13098       break;
13099 
13100     case OO_LessLess:
13101     case OO_GreaterGreater:
13102     case OO_AmpAmp:
13103     case OO_PipePipe:
13104     case OO_Comma:
13105     case OO_ArrowStar:
13106     case OO_Subscript:
13107       SequencingKind = LHSBeforeRHS;
13108       break;
13109 
13110     case OO_Call:
13111       SequencingKind = LHSBeforeRest;
13112       break;
13113 
13114     default:
13115       SequencingKind = NoSequencing;
13116       break;
13117     }
13118 
13119     if (SequencingKind == NoSequencing)
13120       return VisitCallExpr(CXXOCE);
13121 
13122     // This is a call, so all subexpressions are sequenced before the result.
13123     SequencedSubexpression Sequenced(*this);
13124 
13125     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13126       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13127              "Should only get there with C++17 and above!");
13128       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13129              "Should only get there with an overloaded binary operator"
13130              " or an overloaded call operator!");
13131 
13132       if (SequencingKind == LHSBeforeRest) {
13133         assert(CXXOCE->getOperator() == OO_Call &&
13134                "We should only have an overloaded call operator here!");
13135 
13136         // This is very similar to VisitCallExpr, except that we only have the
13137         // C++17 case. The postfix-expression is the first argument of the
13138         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13139         // are in the following arguments.
13140         //
13141         // Note that we intentionally do not visit the callee expression since
13142         // it is just a decayed reference to a function.
13143         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13144         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13145         SequenceTree::Seq OldRegion = Region;
13146 
13147         assert(CXXOCE->getNumArgs() >= 1 &&
13148                "An overloaded call operator must have at least one argument"
13149                " for the postfix-expression!");
13150         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13151         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13152                                           CXXOCE->getNumArgs() - 1);
13153 
13154         // Visit the postfix-expression first.
13155         {
13156           Region = PostfixExprRegion;
13157           SequencedSubexpression Sequenced(*this);
13158           Visit(PostfixExpr);
13159         }
13160 
13161         // Then visit the argument expressions.
13162         Region = ArgsRegion;
13163         for (const Expr *Arg : Args)
13164           Visit(Arg);
13165 
13166         Region = OldRegion;
13167         Tree.merge(PostfixExprRegion);
13168         Tree.merge(ArgsRegion);
13169       } else {
13170         assert(CXXOCE->getNumArgs() == 2 &&
13171                "Should only have two arguments here!");
13172         assert((SequencingKind == LHSBeforeRHS ||
13173                 SequencingKind == RHSBeforeLHS) &&
13174                "Unexpected sequencing kind!");
13175 
13176         // We do not visit the callee expression since it is just a decayed
13177         // reference to a function.
13178         const Expr *E1 = CXXOCE->getArg(0);
13179         const Expr *E2 = CXXOCE->getArg(1);
13180         if (SequencingKind == RHSBeforeLHS)
13181           std::swap(E1, E2);
13182 
13183         return VisitSequencedExpressions(E1, E2);
13184       }
13185     });
13186   }
13187 
13188   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13189     // This is a call, so all subexpressions are sequenced before the result.
13190     SequencedSubexpression Sequenced(*this);
13191 
13192     if (!CCE->isListInitialization())
13193       return VisitExpr(CCE);
13194 
13195     // In C++11, list initializations are sequenced.
13196     SmallVector<SequenceTree::Seq, 32> Elts;
13197     SequenceTree::Seq Parent = Region;
13198     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13199                                               E = CCE->arg_end();
13200          I != E; ++I) {
13201       Region = Tree.allocate(Parent);
13202       Elts.push_back(Region);
13203       Visit(*I);
13204     }
13205 
13206     // Forget that the initializers are sequenced.
13207     Region = Parent;
13208     for (unsigned I = 0; I < Elts.size(); ++I)
13209       Tree.merge(Elts[I]);
13210   }
13211 
13212   void VisitInitListExpr(const InitListExpr *ILE) {
13213     if (!SemaRef.getLangOpts().CPlusPlus11)
13214       return VisitExpr(ILE);
13215 
13216     // In C++11, list initializations are sequenced.
13217     SmallVector<SequenceTree::Seq, 32> Elts;
13218     SequenceTree::Seq Parent = Region;
13219     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13220       const Expr *E = ILE->getInit(I);
13221       if (!E)
13222         continue;
13223       Region = Tree.allocate(Parent);
13224       Elts.push_back(Region);
13225       Visit(E);
13226     }
13227 
13228     // Forget that the initializers are sequenced.
13229     Region = Parent;
13230     for (unsigned I = 0; I < Elts.size(); ++I)
13231       Tree.merge(Elts[I]);
13232   }
13233 };
13234 
13235 } // namespace
13236 
13237 void Sema::CheckUnsequencedOperations(const Expr *E) {
13238   SmallVector<const Expr *, 8> WorkList;
13239   WorkList.push_back(E);
13240   while (!WorkList.empty()) {
13241     const Expr *Item = WorkList.pop_back_val();
13242     SequenceChecker(*this, Item, WorkList);
13243   }
13244 }
13245 
13246 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13247                               bool IsConstexpr) {
13248   llvm::SaveAndRestore<bool> ConstantContext(
13249       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13250   CheckImplicitConversions(E, CheckLoc);
13251   if (!E->isInstantiationDependent())
13252     CheckUnsequencedOperations(E);
13253   if (!IsConstexpr && !E->isValueDependent())
13254     CheckForIntOverflow(E);
13255   DiagnoseMisalignedMembers();
13256 }
13257 
13258 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13259                                        FieldDecl *BitField,
13260                                        Expr *Init) {
13261   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13262 }
13263 
13264 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13265                                          SourceLocation Loc) {
13266   if (!PType->isVariablyModifiedType())
13267     return;
13268   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13269     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13270     return;
13271   }
13272   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13273     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13274     return;
13275   }
13276   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13277     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13278     return;
13279   }
13280 
13281   const ArrayType *AT = S.Context.getAsArrayType(PType);
13282   if (!AT)
13283     return;
13284 
13285   if (AT->getSizeModifier() != ArrayType::Star) {
13286     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13287     return;
13288   }
13289 
13290   S.Diag(Loc, diag::err_array_star_in_function_definition);
13291 }
13292 
13293 /// CheckParmsForFunctionDef - Check that the parameters of the given
13294 /// function are appropriate for the definition of a function. This
13295 /// takes care of any checks that cannot be performed on the
13296 /// declaration itself, e.g., that the types of each of the function
13297 /// parameters are complete.
13298 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13299                                     bool CheckParameterNames) {
13300   bool HasInvalidParm = false;
13301   for (ParmVarDecl *Param : Parameters) {
13302     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13303     // function declarator that is part of a function definition of
13304     // that function shall not have incomplete type.
13305     //
13306     // This is also C++ [dcl.fct]p6.
13307     if (!Param->isInvalidDecl() &&
13308         RequireCompleteType(Param->getLocation(), Param->getType(),
13309                             diag::err_typecheck_decl_incomplete_type)) {
13310       Param->setInvalidDecl();
13311       HasInvalidParm = true;
13312     }
13313 
13314     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13315     // declaration of each parameter shall include an identifier.
13316     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13317         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13318       // Diagnose this as an extension in C17 and earlier.
13319       if (!getLangOpts().C2x)
13320         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13321     }
13322 
13323     // C99 6.7.5.3p12:
13324     //   If the function declarator is not part of a definition of that
13325     //   function, parameters may have incomplete type and may use the [*]
13326     //   notation in their sequences of declarator specifiers to specify
13327     //   variable length array types.
13328     QualType PType = Param->getOriginalType();
13329     // FIXME: This diagnostic should point the '[*]' if source-location
13330     // information is added for it.
13331     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13332 
13333     // If the parameter is a c++ class type and it has to be destructed in the
13334     // callee function, declare the destructor so that it can be called by the
13335     // callee function. Do not perform any direct access check on the dtor here.
13336     if (!Param->isInvalidDecl()) {
13337       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13338         if (!ClassDecl->isInvalidDecl() &&
13339             !ClassDecl->hasIrrelevantDestructor() &&
13340             !ClassDecl->isDependentContext() &&
13341             ClassDecl->isParamDestroyedInCallee()) {
13342           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13343           MarkFunctionReferenced(Param->getLocation(), Destructor);
13344           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13345         }
13346       }
13347     }
13348 
13349     // Parameters with the pass_object_size attribute only need to be marked
13350     // constant at function definitions. Because we lack information about
13351     // whether we're on a declaration or definition when we're instantiating the
13352     // attribute, we need to check for constness here.
13353     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13354       if (!Param->getType().isConstQualified())
13355         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13356             << Attr->getSpelling() << 1;
13357 
13358     // Check for parameter names shadowing fields from the class.
13359     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13360       // The owning context for the parameter should be the function, but we
13361       // want to see if this function's declaration context is a record.
13362       DeclContext *DC = Param->getDeclContext();
13363       if (DC && DC->isFunctionOrMethod()) {
13364         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13365           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13366                                      RD, /*DeclIsField*/ false);
13367       }
13368     }
13369   }
13370 
13371   return HasInvalidParm;
13372 }
13373 
13374 Optional<std::pair<CharUnits, CharUnits>>
13375 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13376 
13377 /// Compute the alignment and offset of the base class object given the
13378 /// derived-to-base cast expression and the alignment and offset of the derived
13379 /// class object.
13380 static std::pair<CharUnits, CharUnits>
13381 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13382                                    CharUnits BaseAlignment, CharUnits Offset,
13383                                    ASTContext &Ctx) {
13384   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13385        ++PathI) {
13386     const CXXBaseSpecifier *Base = *PathI;
13387     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13388     if (Base->isVirtual()) {
13389       // The complete object may have a lower alignment than the non-virtual
13390       // alignment of the base, in which case the base may be misaligned. Choose
13391       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13392       // conservative lower bound of the complete object alignment.
13393       CharUnits NonVirtualAlignment =
13394           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13395       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13396       Offset = CharUnits::Zero();
13397     } else {
13398       const ASTRecordLayout &RL =
13399           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13400       Offset += RL.getBaseClassOffset(BaseDecl);
13401     }
13402     DerivedType = Base->getType();
13403   }
13404 
13405   return std::make_pair(BaseAlignment, Offset);
13406 }
13407 
13408 /// Compute the alignment and offset of a binary additive operator.
13409 static Optional<std::pair<CharUnits, CharUnits>>
13410 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13411                                      bool IsSub, ASTContext &Ctx) {
13412   QualType PointeeType = PtrE->getType()->getPointeeType();
13413 
13414   if (!PointeeType->isConstantSizeType())
13415     return llvm::None;
13416 
13417   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13418 
13419   if (!P)
13420     return llvm::None;
13421 
13422   llvm::APSInt IdxRes;
13423   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13424   if (IntE->isIntegerConstantExpr(IdxRes, Ctx)) {
13425     CharUnits Offset = EltSize * IdxRes.getExtValue();
13426     if (IsSub)
13427       Offset = -Offset;
13428     return std::make_pair(P->first, P->second + Offset);
13429   }
13430 
13431   // If the integer expression isn't a constant expression, compute the lower
13432   // bound of the alignment using the alignment and offset of the pointer
13433   // expression and the element size.
13434   return std::make_pair(
13435       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13436       CharUnits::Zero());
13437 }
13438 
13439 /// This helper function takes an lvalue expression and returns the alignment of
13440 /// a VarDecl and a constant offset from the VarDecl.
13441 Optional<std::pair<CharUnits, CharUnits>>
13442 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
13443   E = E->IgnoreParens();
13444   switch (E->getStmtClass()) {
13445   default:
13446     break;
13447   case Stmt::CStyleCastExprClass:
13448   case Stmt::CXXStaticCastExprClass:
13449   case Stmt::ImplicitCastExprClass: {
13450     auto *CE = cast<CastExpr>(E);
13451     const Expr *From = CE->getSubExpr();
13452     switch (CE->getCastKind()) {
13453     default:
13454       break;
13455     case CK_NoOp:
13456       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13457     case CK_UncheckedDerivedToBase:
13458     case CK_DerivedToBase: {
13459       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13460       if (!P)
13461         break;
13462       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13463                                                 P->second, Ctx);
13464     }
13465     }
13466     break;
13467   }
13468   case Stmt::ArraySubscriptExprClass: {
13469     auto *ASE = cast<ArraySubscriptExpr>(E);
13470     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
13471                                                 false, Ctx);
13472   }
13473   case Stmt::DeclRefExprClass: {
13474     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13475       // FIXME: If VD is captured by copy or is an escaping __block variable,
13476       // use the alignment of VD's type.
13477       if (!VD->getType()->isReferenceType())
13478         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
13479       if (VD->hasInit())
13480         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13481     }
13482     break;
13483   }
13484   case Stmt::MemberExprClass: {
13485     auto *ME = cast<MemberExpr>(E);
13486     if (ME->isArrow())
13487       break;
13488     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13489     if (!FD || FD->getType()->isReferenceType())
13490       break;
13491     auto P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13492     if (!P)
13493       break;
13494     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13495     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13496     return std::make_pair(P->first,
13497                           P->second + CharUnits::fromQuantity(Offset));
13498   }
13499   case Stmt::UnaryOperatorClass: {
13500     auto *UO = cast<UnaryOperator>(E);
13501     switch (UO->getOpcode()) {
13502     default:
13503       break;
13504     case UO_Deref:
13505       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
13506     }
13507     break;
13508   }
13509   case Stmt::BinaryOperatorClass: {
13510     auto *BO = cast<BinaryOperator>(E);
13511     auto Opcode = BO->getOpcode();
13512     switch (Opcode) {
13513     default:
13514       break;
13515     case BO_Comma:
13516       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
13517     }
13518     break;
13519   }
13520   }
13521   return llvm::None;
13522 }
13523 
13524 /// This helper function takes a pointer expression and returns the alignment of
13525 /// a VarDecl and a constant offset from the VarDecl.
13526 Optional<std::pair<CharUnits, CharUnits>>
13527 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
13528   E = E->IgnoreParens();
13529   switch (E->getStmtClass()) {
13530   default:
13531     break;
13532   case Stmt::CStyleCastExprClass:
13533   case Stmt::CXXStaticCastExprClass:
13534   case Stmt::ImplicitCastExprClass: {
13535     auto *CE = cast<CastExpr>(E);
13536     const Expr *From = CE->getSubExpr();
13537     switch (CE->getCastKind()) {
13538     default:
13539       break;
13540     case CK_NoOp:
13541       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13542     case CK_ArrayToPointerDecay:
13543       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13544     case CK_UncheckedDerivedToBase:
13545     case CK_DerivedToBase: {
13546       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13547       if (!P)
13548         break;
13549       return getDerivedToBaseAlignmentAndOffset(
13550           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13551     }
13552     }
13553     break;
13554   }
13555   case Stmt::UnaryOperatorClass: {
13556     auto *UO = cast<UnaryOperator>(E);
13557     if (UO->getOpcode() == UO_AddrOf)
13558       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
13559     break;
13560   }
13561   case Stmt::BinaryOperatorClass: {
13562     auto *BO = cast<BinaryOperator>(E);
13563     auto Opcode = BO->getOpcode();
13564     switch (Opcode) {
13565     default:
13566       break;
13567     case BO_Add:
13568     case BO_Sub: {
13569       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13570       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13571         std::swap(LHS, RHS);
13572       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13573                                                   Ctx);
13574     }
13575     case BO_Comma:
13576       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13577     }
13578     break;
13579   }
13580   }
13581   return llvm::None;
13582 }
13583 
13584 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
13585   // See if we can compute the alignment of a VarDecl and an offset from it.
13586   Optional<std::pair<CharUnits, CharUnits>> P =
13587       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
13588 
13589   if (P)
13590     return P->first.alignmentAtOffset(P->second);
13591 
13592   // If that failed, return the type's alignment.
13593   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
13594 }
13595 
13596 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13597 /// pointer cast increases the alignment requirements.
13598 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13599   // This is actually a lot of work to potentially be doing on every
13600   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13601   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13602     return;
13603 
13604   // Ignore dependent types.
13605   if (T->isDependentType() || Op->getType()->isDependentType())
13606     return;
13607 
13608   // Require that the destination be a pointer type.
13609   const PointerType *DestPtr = T->getAs<PointerType>();
13610   if (!DestPtr) return;
13611 
13612   // If the destination has alignment 1, we're done.
13613   QualType DestPointee = DestPtr->getPointeeType();
13614   if (DestPointee->isIncompleteType()) return;
13615   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13616   if (DestAlign.isOne()) return;
13617 
13618   // Require that the source be a pointer type.
13619   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13620   if (!SrcPtr) return;
13621   QualType SrcPointee = SrcPtr->getPointeeType();
13622 
13623   // Explicitly allow casts from cv void*.  We already implicitly
13624   // allowed casts to cv void*, since they have alignment 1.
13625   // Also allow casts involving incomplete types, which implicitly
13626   // includes 'void'.
13627   if (SrcPointee->isIncompleteType()) return;
13628 
13629   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
13630 
13631   if (SrcAlign >= DestAlign) return;
13632 
13633   Diag(TRange.getBegin(), diag::warn_cast_align)
13634     << Op->getType() << T
13635     << static_cast<unsigned>(SrcAlign.getQuantity())
13636     << static_cast<unsigned>(DestAlign.getQuantity())
13637     << TRange << Op->getSourceRange();
13638 }
13639 
13640 /// Check whether this array fits the idiom of a size-one tail padded
13641 /// array member of a struct.
13642 ///
13643 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13644 /// commonly used to emulate flexible arrays in C89 code.
13645 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13646                                     const NamedDecl *ND) {
13647   if (Size != 1 || !ND) return false;
13648 
13649   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13650   if (!FD) return false;
13651 
13652   // Don't consider sizes resulting from macro expansions or template argument
13653   // substitution to form C89 tail-padded arrays.
13654 
13655   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13656   while (TInfo) {
13657     TypeLoc TL = TInfo->getTypeLoc();
13658     // Look through typedefs.
13659     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13660       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13661       TInfo = TDL->getTypeSourceInfo();
13662       continue;
13663     }
13664     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13665       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13666       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13667         return false;
13668     }
13669     break;
13670   }
13671 
13672   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13673   if (!RD) return false;
13674   if (RD->isUnion()) return false;
13675   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13676     if (!CRD->isStandardLayout()) return false;
13677   }
13678 
13679   // See if this is the last field decl in the record.
13680   const Decl *D = FD;
13681   while ((D = D->getNextDeclInContext()))
13682     if (isa<FieldDecl>(D))
13683       return false;
13684   return true;
13685 }
13686 
13687 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13688                             const ArraySubscriptExpr *ASE,
13689                             bool AllowOnePastEnd, bool IndexNegated) {
13690   // Already diagnosed by the constant evaluator.
13691   if (isConstantEvaluated())
13692     return;
13693 
13694   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13695   if (IndexExpr->isValueDependent())
13696     return;
13697 
13698   const Type *EffectiveType =
13699       BaseExpr->getType()->getPointeeOrArrayElementType();
13700   BaseExpr = BaseExpr->IgnoreParenCasts();
13701   const ConstantArrayType *ArrayTy =
13702       Context.getAsConstantArrayType(BaseExpr->getType());
13703 
13704   if (!ArrayTy)
13705     return;
13706 
13707   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13708   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13709     return;
13710 
13711   Expr::EvalResult Result;
13712   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13713     return;
13714 
13715   llvm::APSInt index = Result.Val.getInt();
13716   if (IndexNegated)
13717     index = -index;
13718 
13719   const NamedDecl *ND = nullptr;
13720   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13721     ND = DRE->getDecl();
13722   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13723     ND = ME->getMemberDecl();
13724 
13725   if (index.isUnsigned() || !index.isNegative()) {
13726     // It is possible that the type of the base expression after
13727     // IgnoreParenCasts is incomplete, even though the type of the base
13728     // expression before IgnoreParenCasts is complete (see PR39746 for an
13729     // example). In this case we have no information about whether the array
13730     // access exceeds the array bounds. However we can still diagnose an array
13731     // access which precedes the array bounds.
13732     if (BaseType->isIncompleteType())
13733       return;
13734 
13735     llvm::APInt size = ArrayTy->getSize();
13736     if (!size.isStrictlyPositive())
13737       return;
13738 
13739     if (BaseType != EffectiveType) {
13740       // Make sure we're comparing apples to apples when comparing index to size
13741       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13742       uint64_t array_typesize = Context.getTypeSize(BaseType);
13743       // Handle ptrarith_typesize being zero, such as when casting to void*
13744       if (!ptrarith_typesize) ptrarith_typesize = 1;
13745       if (ptrarith_typesize != array_typesize) {
13746         // There's a cast to a different size type involved
13747         uint64_t ratio = array_typesize / ptrarith_typesize;
13748         // TODO: Be smarter about handling cases where array_typesize is not a
13749         // multiple of ptrarith_typesize
13750         if (ptrarith_typesize * ratio == array_typesize)
13751           size *= llvm::APInt(size.getBitWidth(), ratio);
13752       }
13753     }
13754 
13755     if (size.getBitWidth() > index.getBitWidth())
13756       index = index.zext(size.getBitWidth());
13757     else if (size.getBitWidth() < index.getBitWidth())
13758       size = size.zext(index.getBitWidth());
13759 
13760     // For array subscripting the index must be less than size, but for pointer
13761     // arithmetic also allow the index (offset) to be equal to size since
13762     // computing the next address after the end of the array is legal and
13763     // commonly done e.g. in C++ iterators and range-based for loops.
13764     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13765       return;
13766 
13767     // Also don't warn for arrays of size 1 which are members of some
13768     // structure. These are often used to approximate flexible arrays in C89
13769     // code.
13770     if (IsTailPaddedMemberArray(*this, size, ND))
13771       return;
13772 
13773     // Suppress the warning if the subscript expression (as identified by the
13774     // ']' location) and the index expression are both from macro expansions
13775     // within a system header.
13776     if (ASE) {
13777       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13778           ASE->getRBracketLoc());
13779       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13780         SourceLocation IndexLoc =
13781             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13782         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13783           return;
13784       }
13785     }
13786 
13787     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13788     if (ASE)
13789       DiagID = diag::warn_array_index_exceeds_bounds;
13790 
13791     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13792                         PDiag(DiagID) << index.toString(10, true)
13793                                       << size.toString(10, true)
13794                                       << (unsigned)size.getLimitedValue(~0U)
13795                                       << IndexExpr->getSourceRange());
13796   } else {
13797     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13798     if (!ASE) {
13799       DiagID = diag::warn_ptr_arith_precedes_bounds;
13800       if (index.isNegative()) index = -index;
13801     }
13802 
13803     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13804                         PDiag(DiagID) << index.toString(10, true)
13805                                       << IndexExpr->getSourceRange());
13806   }
13807 
13808   if (!ND) {
13809     // Try harder to find a NamedDecl to point at in the note.
13810     while (const ArraySubscriptExpr *ASE =
13811            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13812       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13813     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13814       ND = DRE->getDecl();
13815     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13816       ND = ME->getMemberDecl();
13817   }
13818 
13819   if (ND)
13820     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13821                         PDiag(diag::note_array_declared_here)
13822                             << ND->getDeclName());
13823 }
13824 
13825 void Sema::CheckArrayAccess(const Expr *expr) {
13826   int AllowOnePastEnd = 0;
13827   while (expr) {
13828     expr = expr->IgnoreParenImpCasts();
13829     switch (expr->getStmtClass()) {
13830       case Stmt::ArraySubscriptExprClass: {
13831         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13832         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13833                          AllowOnePastEnd > 0);
13834         expr = ASE->getBase();
13835         break;
13836       }
13837       case Stmt::MemberExprClass: {
13838         expr = cast<MemberExpr>(expr)->getBase();
13839         break;
13840       }
13841       case Stmt::OMPArraySectionExprClass: {
13842         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13843         if (ASE->getLowerBound())
13844           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13845                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13846         return;
13847       }
13848       case Stmt::UnaryOperatorClass: {
13849         // Only unwrap the * and & unary operators
13850         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13851         expr = UO->getSubExpr();
13852         switch (UO->getOpcode()) {
13853           case UO_AddrOf:
13854             AllowOnePastEnd++;
13855             break;
13856           case UO_Deref:
13857             AllowOnePastEnd--;
13858             break;
13859           default:
13860             return;
13861         }
13862         break;
13863       }
13864       case Stmt::ConditionalOperatorClass: {
13865         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13866         if (const Expr *lhs = cond->getLHS())
13867           CheckArrayAccess(lhs);
13868         if (const Expr *rhs = cond->getRHS())
13869           CheckArrayAccess(rhs);
13870         return;
13871       }
13872       case Stmt::CXXOperatorCallExprClass: {
13873         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13874         for (const auto *Arg : OCE->arguments())
13875           CheckArrayAccess(Arg);
13876         return;
13877       }
13878       default:
13879         return;
13880     }
13881   }
13882 }
13883 
13884 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13885 
13886 namespace {
13887 
13888 struct RetainCycleOwner {
13889   VarDecl *Variable = nullptr;
13890   SourceRange Range;
13891   SourceLocation Loc;
13892   bool Indirect = false;
13893 
13894   RetainCycleOwner() = default;
13895 
13896   void setLocsFrom(Expr *e) {
13897     Loc = e->getExprLoc();
13898     Range = e->getSourceRange();
13899   }
13900 };
13901 
13902 } // namespace
13903 
13904 /// Consider whether capturing the given variable can possibly lead to
13905 /// a retain cycle.
13906 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13907   // In ARC, it's captured strongly iff the variable has __strong
13908   // lifetime.  In MRR, it's captured strongly if the variable is
13909   // __block and has an appropriate type.
13910   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13911     return false;
13912 
13913   owner.Variable = var;
13914   if (ref)
13915     owner.setLocsFrom(ref);
13916   return true;
13917 }
13918 
13919 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13920   while (true) {
13921     e = e->IgnoreParens();
13922     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13923       switch (cast->getCastKind()) {
13924       case CK_BitCast:
13925       case CK_LValueBitCast:
13926       case CK_LValueToRValue:
13927       case CK_ARCReclaimReturnedObject:
13928         e = cast->getSubExpr();
13929         continue;
13930 
13931       default:
13932         return false;
13933       }
13934     }
13935 
13936     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13937       ObjCIvarDecl *ivar = ref->getDecl();
13938       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13939         return false;
13940 
13941       // Try to find a retain cycle in the base.
13942       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13943         return false;
13944 
13945       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13946       owner.Indirect = true;
13947       return true;
13948     }
13949 
13950     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13951       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13952       if (!var) return false;
13953       return considerVariable(var, ref, owner);
13954     }
13955 
13956     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13957       if (member->isArrow()) return false;
13958 
13959       // Don't count this as an indirect ownership.
13960       e = member->getBase();
13961       continue;
13962     }
13963 
13964     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13965       // Only pay attention to pseudo-objects on property references.
13966       ObjCPropertyRefExpr *pre
13967         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13968                                               ->IgnoreParens());
13969       if (!pre) return false;
13970       if (pre->isImplicitProperty()) return false;
13971       ObjCPropertyDecl *property = pre->getExplicitProperty();
13972       if (!property->isRetaining() &&
13973           !(property->getPropertyIvarDecl() &&
13974             property->getPropertyIvarDecl()->getType()
13975               .getObjCLifetime() == Qualifiers::OCL_Strong))
13976           return false;
13977 
13978       owner.Indirect = true;
13979       if (pre->isSuperReceiver()) {
13980         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13981         if (!owner.Variable)
13982           return false;
13983         owner.Loc = pre->getLocation();
13984         owner.Range = pre->getSourceRange();
13985         return true;
13986       }
13987       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13988                               ->getSourceExpr());
13989       continue;
13990     }
13991 
13992     // Array ivars?
13993 
13994     return false;
13995   }
13996 }
13997 
13998 namespace {
13999 
14000   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14001     ASTContext &Context;
14002     VarDecl *Variable;
14003     Expr *Capturer = nullptr;
14004     bool VarWillBeReased = false;
14005 
14006     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14007         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14008           Context(Context), Variable(variable) {}
14009 
14010     void VisitDeclRefExpr(DeclRefExpr *ref) {
14011       if (ref->getDecl() == Variable && !Capturer)
14012         Capturer = ref;
14013     }
14014 
14015     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14016       if (Capturer) return;
14017       Visit(ref->getBase());
14018       if (Capturer && ref->isFreeIvar())
14019         Capturer = ref;
14020     }
14021 
14022     void VisitBlockExpr(BlockExpr *block) {
14023       // Look inside nested blocks
14024       if (block->getBlockDecl()->capturesVariable(Variable))
14025         Visit(block->getBlockDecl()->getBody());
14026     }
14027 
14028     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14029       if (Capturer) return;
14030       if (OVE->getSourceExpr())
14031         Visit(OVE->getSourceExpr());
14032     }
14033 
14034     void VisitBinaryOperator(BinaryOperator *BinOp) {
14035       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14036         return;
14037       Expr *LHS = BinOp->getLHS();
14038       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14039         if (DRE->getDecl() != Variable)
14040           return;
14041         if (Expr *RHS = BinOp->getRHS()) {
14042           RHS = RHS->IgnoreParenCasts();
14043           llvm::APSInt Value;
14044           VarWillBeReased =
14045             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
14046         }
14047       }
14048     }
14049   };
14050 
14051 } // namespace
14052 
14053 /// Check whether the given argument is a block which captures a
14054 /// variable.
14055 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14056   assert(owner.Variable && owner.Loc.isValid());
14057 
14058   e = e->IgnoreParenCasts();
14059 
14060   // Look through [^{...} copy] and Block_copy(^{...}).
14061   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14062     Selector Cmd = ME->getSelector();
14063     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14064       e = ME->getInstanceReceiver();
14065       if (!e)
14066         return nullptr;
14067       e = e->IgnoreParenCasts();
14068     }
14069   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14070     if (CE->getNumArgs() == 1) {
14071       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14072       if (Fn) {
14073         const IdentifierInfo *FnI = Fn->getIdentifier();
14074         if (FnI && FnI->isStr("_Block_copy")) {
14075           e = CE->getArg(0)->IgnoreParenCasts();
14076         }
14077       }
14078     }
14079   }
14080 
14081   BlockExpr *block = dyn_cast<BlockExpr>(e);
14082   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14083     return nullptr;
14084 
14085   FindCaptureVisitor visitor(S.Context, owner.Variable);
14086   visitor.Visit(block->getBlockDecl()->getBody());
14087   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14088 }
14089 
14090 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14091                                 RetainCycleOwner &owner) {
14092   assert(capturer);
14093   assert(owner.Variable && owner.Loc.isValid());
14094 
14095   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14096     << owner.Variable << capturer->getSourceRange();
14097   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14098     << owner.Indirect << owner.Range;
14099 }
14100 
14101 /// Check for a keyword selector that starts with the word 'add' or
14102 /// 'set'.
14103 static bool isSetterLikeSelector(Selector sel) {
14104   if (sel.isUnarySelector()) return false;
14105 
14106   StringRef str = sel.getNameForSlot(0);
14107   while (!str.empty() && str.front() == '_') str = str.substr(1);
14108   if (str.startswith("set"))
14109     str = str.substr(3);
14110   else if (str.startswith("add")) {
14111     // Specially allow 'addOperationWithBlock:'.
14112     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14113       return false;
14114     str = str.substr(3);
14115   }
14116   else
14117     return false;
14118 
14119   if (str.empty()) return true;
14120   return !isLowercase(str.front());
14121 }
14122 
14123 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14124                                                     ObjCMessageExpr *Message) {
14125   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14126                                                 Message->getReceiverInterface(),
14127                                                 NSAPI::ClassId_NSMutableArray);
14128   if (!IsMutableArray) {
14129     return None;
14130   }
14131 
14132   Selector Sel = Message->getSelector();
14133 
14134   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14135     S.NSAPIObj->getNSArrayMethodKind(Sel);
14136   if (!MKOpt) {
14137     return None;
14138   }
14139 
14140   NSAPI::NSArrayMethodKind MK = *MKOpt;
14141 
14142   switch (MK) {
14143     case NSAPI::NSMutableArr_addObject:
14144     case NSAPI::NSMutableArr_insertObjectAtIndex:
14145     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14146       return 0;
14147     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14148       return 1;
14149 
14150     default:
14151       return None;
14152   }
14153 
14154   return None;
14155 }
14156 
14157 static
14158 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14159                                                   ObjCMessageExpr *Message) {
14160   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14161                                             Message->getReceiverInterface(),
14162                                             NSAPI::ClassId_NSMutableDictionary);
14163   if (!IsMutableDictionary) {
14164     return None;
14165   }
14166 
14167   Selector Sel = Message->getSelector();
14168 
14169   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14170     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14171   if (!MKOpt) {
14172     return None;
14173   }
14174 
14175   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14176 
14177   switch (MK) {
14178     case NSAPI::NSMutableDict_setObjectForKey:
14179     case NSAPI::NSMutableDict_setValueForKey:
14180     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14181       return 0;
14182 
14183     default:
14184       return None;
14185   }
14186 
14187   return None;
14188 }
14189 
14190 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14191   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14192                                                 Message->getReceiverInterface(),
14193                                                 NSAPI::ClassId_NSMutableSet);
14194 
14195   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14196                                             Message->getReceiverInterface(),
14197                                             NSAPI::ClassId_NSMutableOrderedSet);
14198   if (!IsMutableSet && !IsMutableOrderedSet) {
14199     return None;
14200   }
14201 
14202   Selector Sel = Message->getSelector();
14203 
14204   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14205   if (!MKOpt) {
14206     return None;
14207   }
14208 
14209   NSAPI::NSSetMethodKind MK = *MKOpt;
14210 
14211   switch (MK) {
14212     case NSAPI::NSMutableSet_addObject:
14213     case NSAPI::NSOrderedSet_setObjectAtIndex:
14214     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14215     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14216       return 0;
14217     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14218       return 1;
14219   }
14220 
14221   return None;
14222 }
14223 
14224 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14225   if (!Message->isInstanceMessage()) {
14226     return;
14227   }
14228 
14229   Optional<int> ArgOpt;
14230 
14231   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14232       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14233       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14234     return;
14235   }
14236 
14237   int ArgIndex = *ArgOpt;
14238 
14239   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14240   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14241     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14242   }
14243 
14244   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14245     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14246       if (ArgRE->isObjCSelfExpr()) {
14247         Diag(Message->getSourceRange().getBegin(),
14248              diag::warn_objc_circular_container)
14249           << ArgRE->getDecl() << StringRef("'super'");
14250       }
14251     }
14252   } else {
14253     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14254 
14255     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14256       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14257     }
14258 
14259     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14260       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14261         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14262           ValueDecl *Decl = ReceiverRE->getDecl();
14263           Diag(Message->getSourceRange().getBegin(),
14264                diag::warn_objc_circular_container)
14265             << Decl << Decl;
14266           if (!ArgRE->isObjCSelfExpr()) {
14267             Diag(Decl->getLocation(),
14268                  diag::note_objc_circular_container_declared_here)
14269               << Decl;
14270           }
14271         }
14272       }
14273     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14274       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14275         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14276           ObjCIvarDecl *Decl = IvarRE->getDecl();
14277           Diag(Message->getSourceRange().getBegin(),
14278                diag::warn_objc_circular_container)
14279             << Decl << Decl;
14280           Diag(Decl->getLocation(),
14281                diag::note_objc_circular_container_declared_here)
14282             << Decl;
14283         }
14284       }
14285     }
14286   }
14287 }
14288 
14289 /// Check a message send to see if it's likely to cause a retain cycle.
14290 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14291   // Only check instance methods whose selector looks like a setter.
14292   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14293     return;
14294 
14295   // Try to find a variable that the receiver is strongly owned by.
14296   RetainCycleOwner owner;
14297   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14298     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14299       return;
14300   } else {
14301     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14302     owner.Variable = getCurMethodDecl()->getSelfDecl();
14303     owner.Loc = msg->getSuperLoc();
14304     owner.Range = msg->getSuperLoc();
14305   }
14306 
14307   // Check whether the receiver is captured by any of the arguments.
14308   const ObjCMethodDecl *MD = msg->getMethodDecl();
14309   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14310     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14311       // noescape blocks should not be retained by the method.
14312       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14313         continue;
14314       return diagnoseRetainCycle(*this, capturer, owner);
14315     }
14316   }
14317 }
14318 
14319 /// Check a property assign to see if it's likely to cause a retain cycle.
14320 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14321   RetainCycleOwner owner;
14322   if (!findRetainCycleOwner(*this, receiver, owner))
14323     return;
14324 
14325   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14326     diagnoseRetainCycle(*this, capturer, owner);
14327 }
14328 
14329 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14330   RetainCycleOwner Owner;
14331   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14332     return;
14333 
14334   // Because we don't have an expression for the variable, we have to set the
14335   // location explicitly here.
14336   Owner.Loc = Var->getLocation();
14337   Owner.Range = Var->getSourceRange();
14338 
14339   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14340     diagnoseRetainCycle(*this, Capturer, Owner);
14341 }
14342 
14343 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14344                                      Expr *RHS, bool isProperty) {
14345   // Check if RHS is an Objective-C object literal, which also can get
14346   // immediately zapped in a weak reference.  Note that we explicitly
14347   // allow ObjCStringLiterals, since those are designed to never really die.
14348   RHS = RHS->IgnoreParenImpCasts();
14349 
14350   // This enum needs to match with the 'select' in
14351   // warn_objc_arc_literal_assign (off-by-1).
14352   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14353   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14354     return false;
14355 
14356   S.Diag(Loc, diag::warn_arc_literal_assign)
14357     << (unsigned) Kind
14358     << (isProperty ? 0 : 1)
14359     << RHS->getSourceRange();
14360 
14361   return true;
14362 }
14363 
14364 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14365                                     Qualifiers::ObjCLifetime LT,
14366                                     Expr *RHS, bool isProperty) {
14367   // Strip off any implicit cast added to get to the one ARC-specific.
14368   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14369     if (cast->getCastKind() == CK_ARCConsumeObject) {
14370       S.Diag(Loc, diag::warn_arc_retained_assign)
14371         << (LT == Qualifiers::OCL_ExplicitNone)
14372         << (isProperty ? 0 : 1)
14373         << RHS->getSourceRange();
14374       return true;
14375     }
14376     RHS = cast->getSubExpr();
14377   }
14378 
14379   if (LT == Qualifiers::OCL_Weak &&
14380       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14381     return true;
14382 
14383   return false;
14384 }
14385 
14386 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14387                               QualType LHS, Expr *RHS) {
14388   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14389 
14390   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14391     return false;
14392 
14393   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14394     return true;
14395 
14396   return false;
14397 }
14398 
14399 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14400                               Expr *LHS, Expr *RHS) {
14401   QualType LHSType;
14402   // PropertyRef on LHS type need be directly obtained from
14403   // its declaration as it has a PseudoType.
14404   ObjCPropertyRefExpr *PRE
14405     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14406   if (PRE && !PRE->isImplicitProperty()) {
14407     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14408     if (PD)
14409       LHSType = PD->getType();
14410   }
14411 
14412   if (LHSType.isNull())
14413     LHSType = LHS->getType();
14414 
14415   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14416 
14417   if (LT == Qualifiers::OCL_Weak) {
14418     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14419       getCurFunction()->markSafeWeakUse(LHS);
14420   }
14421 
14422   if (checkUnsafeAssigns(Loc, LHSType, RHS))
14423     return;
14424 
14425   // FIXME. Check for other life times.
14426   if (LT != Qualifiers::OCL_None)
14427     return;
14428 
14429   if (PRE) {
14430     if (PRE->isImplicitProperty())
14431       return;
14432     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14433     if (!PD)
14434       return;
14435 
14436     unsigned Attributes = PD->getPropertyAttributes();
14437     if (Attributes & ObjCPropertyAttribute::kind_assign) {
14438       // when 'assign' attribute was not explicitly specified
14439       // by user, ignore it and rely on property type itself
14440       // for lifetime info.
14441       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14442       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14443           LHSType->isObjCRetainableType())
14444         return;
14445 
14446       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14447         if (cast->getCastKind() == CK_ARCConsumeObject) {
14448           Diag(Loc, diag::warn_arc_retained_property_assign)
14449           << RHS->getSourceRange();
14450           return;
14451         }
14452         RHS = cast->getSubExpr();
14453       }
14454     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
14455       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14456         return;
14457     }
14458   }
14459 }
14460 
14461 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14462 
14463 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14464                                         SourceLocation StmtLoc,
14465                                         const NullStmt *Body) {
14466   // Do not warn if the body is a macro that expands to nothing, e.g:
14467   //
14468   // #define CALL(x)
14469   // if (condition)
14470   //   CALL(0);
14471   if (Body->hasLeadingEmptyMacro())
14472     return false;
14473 
14474   // Get line numbers of statement and body.
14475   bool StmtLineInvalid;
14476   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14477                                                       &StmtLineInvalid);
14478   if (StmtLineInvalid)
14479     return false;
14480 
14481   bool BodyLineInvalid;
14482   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14483                                                       &BodyLineInvalid);
14484   if (BodyLineInvalid)
14485     return false;
14486 
14487   // Warn if null statement and body are on the same line.
14488   if (StmtLine != BodyLine)
14489     return false;
14490 
14491   return true;
14492 }
14493 
14494 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14495                                  const Stmt *Body,
14496                                  unsigned DiagID) {
14497   // Since this is a syntactic check, don't emit diagnostic for template
14498   // instantiations, this just adds noise.
14499   if (CurrentInstantiationScope)
14500     return;
14501 
14502   // The body should be a null statement.
14503   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14504   if (!NBody)
14505     return;
14506 
14507   // Do the usual checks.
14508   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14509     return;
14510 
14511   Diag(NBody->getSemiLoc(), DiagID);
14512   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14513 }
14514 
14515 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14516                                  const Stmt *PossibleBody) {
14517   assert(!CurrentInstantiationScope); // Ensured by caller
14518 
14519   SourceLocation StmtLoc;
14520   const Stmt *Body;
14521   unsigned DiagID;
14522   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14523     StmtLoc = FS->getRParenLoc();
14524     Body = FS->getBody();
14525     DiagID = diag::warn_empty_for_body;
14526   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14527     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14528     Body = WS->getBody();
14529     DiagID = diag::warn_empty_while_body;
14530   } else
14531     return; // Neither `for' nor `while'.
14532 
14533   // The body should be a null statement.
14534   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14535   if (!NBody)
14536     return;
14537 
14538   // Skip expensive checks if diagnostic is disabled.
14539   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14540     return;
14541 
14542   // Do the usual checks.
14543   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14544     return;
14545 
14546   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14547   // noise level low, emit diagnostics only if for/while is followed by a
14548   // CompoundStmt, e.g.:
14549   //    for (int i = 0; i < n; i++);
14550   //    {
14551   //      a(i);
14552   //    }
14553   // or if for/while is followed by a statement with more indentation
14554   // than for/while itself:
14555   //    for (int i = 0; i < n; i++);
14556   //      a(i);
14557   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14558   if (!ProbableTypo) {
14559     bool BodyColInvalid;
14560     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14561         PossibleBody->getBeginLoc(), &BodyColInvalid);
14562     if (BodyColInvalid)
14563       return;
14564 
14565     bool StmtColInvalid;
14566     unsigned StmtCol =
14567         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14568     if (StmtColInvalid)
14569       return;
14570 
14571     if (BodyCol > StmtCol)
14572       ProbableTypo = true;
14573   }
14574 
14575   if (ProbableTypo) {
14576     Diag(NBody->getSemiLoc(), DiagID);
14577     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14578   }
14579 }
14580 
14581 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14582 
14583 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14584 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14585                              SourceLocation OpLoc) {
14586   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14587     return;
14588 
14589   if (inTemplateInstantiation())
14590     return;
14591 
14592   // Strip parens and casts away.
14593   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14594   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14595 
14596   // Check for a call expression
14597   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14598   if (!CE || CE->getNumArgs() != 1)
14599     return;
14600 
14601   // Check for a call to std::move
14602   if (!CE->isCallToStdMove())
14603     return;
14604 
14605   // Get argument from std::move
14606   RHSExpr = CE->getArg(0);
14607 
14608   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14609   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14610 
14611   // Two DeclRefExpr's, check that the decls are the same.
14612   if (LHSDeclRef && RHSDeclRef) {
14613     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14614       return;
14615     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14616         RHSDeclRef->getDecl()->getCanonicalDecl())
14617       return;
14618 
14619     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14620                                         << LHSExpr->getSourceRange()
14621                                         << RHSExpr->getSourceRange();
14622     return;
14623   }
14624 
14625   // Member variables require a different approach to check for self moves.
14626   // MemberExpr's are the same if every nested MemberExpr refers to the same
14627   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14628   // the base Expr's are CXXThisExpr's.
14629   const Expr *LHSBase = LHSExpr;
14630   const Expr *RHSBase = RHSExpr;
14631   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14632   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14633   if (!LHSME || !RHSME)
14634     return;
14635 
14636   while (LHSME && RHSME) {
14637     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14638         RHSME->getMemberDecl()->getCanonicalDecl())
14639       return;
14640 
14641     LHSBase = LHSME->getBase();
14642     RHSBase = RHSME->getBase();
14643     LHSME = dyn_cast<MemberExpr>(LHSBase);
14644     RHSME = dyn_cast<MemberExpr>(RHSBase);
14645   }
14646 
14647   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14648   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14649   if (LHSDeclRef && RHSDeclRef) {
14650     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14651       return;
14652     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14653         RHSDeclRef->getDecl()->getCanonicalDecl())
14654       return;
14655 
14656     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14657                                         << LHSExpr->getSourceRange()
14658                                         << RHSExpr->getSourceRange();
14659     return;
14660   }
14661 
14662   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14663     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14664                                         << LHSExpr->getSourceRange()
14665                                         << RHSExpr->getSourceRange();
14666 }
14667 
14668 //===--- Layout compatibility ----------------------------------------------//
14669 
14670 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14671 
14672 /// Check if two enumeration types are layout-compatible.
14673 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14674   // C++11 [dcl.enum] p8:
14675   // Two enumeration types are layout-compatible if they have the same
14676   // underlying type.
14677   return ED1->isComplete() && ED2->isComplete() &&
14678          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14679 }
14680 
14681 /// Check if two fields are layout-compatible.
14682 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14683                                FieldDecl *Field2) {
14684   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14685     return false;
14686 
14687   if (Field1->isBitField() != Field2->isBitField())
14688     return false;
14689 
14690   if (Field1->isBitField()) {
14691     // Make sure that the bit-fields are the same length.
14692     unsigned Bits1 = Field1->getBitWidthValue(C);
14693     unsigned Bits2 = Field2->getBitWidthValue(C);
14694 
14695     if (Bits1 != Bits2)
14696       return false;
14697   }
14698 
14699   return true;
14700 }
14701 
14702 /// Check if two standard-layout structs are layout-compatible.
14703 /// (C++11 [class.mem] p17)
14704 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14705                                      RecordDecl *RD2) {
14706   // If both records are C++ classes, check that base classes match.
14707   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14708     // If one of records is a CXXRecordDecl we are in C++ mode,
14709     // thus the other one is a CXXRecordDecl, too.
14710     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14711     // Check number of base classes.
14712     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14713       return false;
14714 
14715     // Check the base classes.
14716     for (CXXRecordDecl::base_class_const_iterator
14717                Base1 = D1CXX->bases_begin(),
14718            BaseEnd1 = D1CXX->bases_end(),
14719               Base2 = D2CXX->bases_begin();
14720          Base1 != BaseEnd1;
14721          ++Base1, ++Base2) {
14722       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14723         return false;
14724     }
14725   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14726     // If only RD2 is a C++ class, it should have zero base classes.
14727     if (D2CXX->getNumBases() > 0)
14728       return false;
14729   }
14730 
14731   // Check the fields.
14732   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14733                              Field2End = RD2->field_end(),
14734                              Field1 = RD1->field_begin(),
14735                              Field1End = RD1->field_end();
14736   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14737     if (!isLayoutCompatible(C, *Field1, *Field2))
14738       return false;
14739   }
14740   if (Field1 != Field1End || Field2 != Field2End)
14741     return false;
14742 
14743   return true;
14744 }
14745 
14746 /// Check if two standard-layout unions are layout-compatible.
14747 /// (C++11 [class.mem] p18)
14748 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14749                                     RecordDecl *RD2) {
14750   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14751   for (auto *Field2 : RD2->fields())
14752     UnmatchedFields.insert(Field2);
14753 
14754   for (auto *Field1 : RD1->fields()) {
14755     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14756         I = UnmatchedFields.begin(),
14757         E = UnmatchedFields.end();
14758 
14759     for ( ; I != E; ++I) {
14760       if (isLayoutCompatible(C, Field1, *I)) {
14761         bool Result = UnmatchedFields.erase(*I);
14762         (void) Result;
14763         assert(Result);
14764         break;
14765       }
14766     }
14767     if (I == E)
14768       return false;
14769   }
14770 
14771   return UnmatchedFields.empty();
14772 }
14773 
14774 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14775                                RecordDecl *RD2) {
14776   if (RD1->isUnion() != RD2->isUnion())
14777     return false;
14778 
14779   if (RD1->isUnion())
14780     return isLayoutCompatibleUnion(C, RD1, RD2);
14781   else
14782     return isLayoutCompatibleStruct(C, RD1, RD2);
14783 }
14784 
14785 /// Check if two types are layout-compatible in C++11 sense.
14786 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14787   if (T1.isNull() || T2.isNull())
14788     return false;
14789 
14790   // C++11 [basic.types] p11:
14791   // If two types T1 and T2 are the same type, then T1 and T2 are
14792   // layout-compatible types.
14793   if (C.hasSameType(T1, T2))
14794     return true;
14795 
14796   T1 = T1.getCanonicalType().getUnqualifiedType();
14797   T2 = T2.getCanonicalType().getUnqualifiedType();
14798 
14799   const Type::TypeClass TC1 = T1->getTypeClass();
14800   const Type::TypeClass TC2 = T2->getTypeClass();
14801 
14802   if (TC1 != TC2)
14803     return false;
14804 
14805   if (TC1 == Type::Enum) {
14806     return isLayoutCompatible(C,
14807                               cast<EnumType>(T1)->getDecl(),
14808                               cast<EnumType>(T2)->getDecl());
14809   } else if (TC1 == Type::Record) {
14810     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14811       return false;
14812 
14813     return isLayoutCompatible(C,
14814                               cast<RecordType>(T1)->getDecl(),
14815                               cast<RecordType>(T2)->getDecl());
14816   }
14817 
14818   return false;
14819 }
14820 
14821 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14822 
14823 /// Given a type tag expression find the type tag itself.
14824 ///
14825 /// \param TypeExpr Type tag expression, as it appears in user's code.
14826 ///
14827 /// \param VD Declaration of an identifier that appears in a type tag.
14828 ///
14829 /// \param MagicValue Type tag magic value.
14830 ///
14831 /// \param isConstantEvaluated wether the evalaution should be performed in
14832 
14833 /// constant context.
14834 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14835                             const ValueDecl **VD, uint64_t *MagicValue,
14836                             bool isConstantEvaluated) {
14837   while(true) {
14838     if (!TypeExpr)
14839       return false;
14840 
14841     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14842 
14843     switch (TypeExpr->getStmtClass()) {
14844     case Stmt::UnaryOperatorClass: {
14845       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14846       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14847         TypeExpr = UO->getSubExpr();
14848         continue;
14849       }
14850       return false;
14851     }
14852 
14853     case Stmt::DeclRefExprClass: {
14854       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14855       *VD = DRE->getDecl();
14856       return true;
14857     }
14858 
14859     case Stmt::IntegerLiteralClass: {
14860       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14861       llvm::APInt MagicValueAPInt = IL->getValue();
14862       if (MagicValueAPInt.getActiveBits() <= 64) {
14863         *MagicValue = MagicValueAPInt.getZExtValue();
14864         return true;
14865       } else
14866         return false;
14867     }
14868 
14869     case Stmt::BinaryConditionalOperatorClass:
14870     case Stmt::ConditionalOperatorClass: {
14871       const AbstractConditionalOperator *ACO =
14872           cast<AbstractConditionalOperator>(TypeExpr);
14873       bool Result;
14874       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14875                                                      isConstantEvaluated)) {
14876         if (Result)
14877           TypeExpr = ACO->getTrueExpr();
14878         else
14879           TypeExpr = ACO->getFalseExpr();
14880         continue;
14881       }
14882       return false;
14883     }
14884 
14885     case Stmt::BinaryOperatorClass: {
14886       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14887       if (BO->getOpcode() == BO_Comma) {
14888         TypeExpr = BO->getRHS();
14889         continue;
14890       }
14891       return false;
14892     }
14893 
14894     default:
14895       return false;
14896     }
14897   }
14898 }
14899 
14900 /// Retrieve the C type corresponding to type tag TypeExpr.
14901 ///
14902 /// \param TypeExpr Expression that specifies a type tag.
14903 ///
14904 /// \param MagicValues Registered magic values.
14905 ///
14906 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14907 ///        kind.
14908 ///
14909 /// \param TypeInfo Information about the corresponding C type.
14910 ///
14911 /// \param isConstantEvaluated wether the evalaution should be performed in
14912 /// constant context.
14913 ///
14914 /// \returns true if the corresponding C type was found.
14915 static bool GetMatchingCType(
14916     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14917     const ASTContext &Ctx,
14918     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14919         *MagicValues,
14920     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14921     bool isConstantEvaluated) {
14922   FoundWrongKind = false;
14923 
14924   // Variable declaration that has type_tag_for_datatype attribute.
14925   const ValueDecl *VD = nullptr;
14926 
14927   uint64_t MagicValue;
14928 
14929   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14930     return false;
14931 
14932   if (VD) {
14933     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14934       if (I->getArgumentKind() != ArgumentKind) {
14935         FoundWrongKind = true;
14936         return false;
14937       }
14938       TypeInfo.Type = I->getMatchingCType();
14939       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14940       TypeInfo.MustBeNull = I->getMustBeNull();
14941       return true;
14942     }
14943     return false;
14944   }
14945 
14946   if (!MagicValues)
14947     return false;
14948 
14949   llvm::DenseMap<Sema::TypeTagMagicValue,
14950                  Sema::TypeTagData>::const_iterator I =
14951       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14952   if (I == MagicValues->end())
14953     return false;
14954 
14955   TypeInfo = I->second;
14956   return true;
14957 }
14958 
14959 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14960                                       uint64_t MagicValue, QualType Type,
14961                                       bool LayoutCompatible,
14962                                       bool MustBeNull) {
14963   if (!TypeTagForDatatypeMagicValues)
14964     TypeTagForDatatypeMagicValues.reset(
14965         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14966 
14967   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14968   (*TypeTagForDatatypeMagicValues)[Magic] =
14969       TypeTagData(Type, LayoutCompatible, MustBeNull);
14970 }
14971 
14972 static bool IsSameCharType(QualType T1, QualType T2) {
14973   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14974   if (!BT1)
14975     return false;
14976 
14977   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14978   if (!BT2)
14979     return false;
14980 
14981   BuiltinType::Kind T1Kind = BT1->getKind();
14982   BuiltinType::Kind T2Kind = BT2->getKind();
14983 
14984   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14985          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14986          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14987          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14988 }
14989 
14990 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14991                                     const ArrayRef<const Expr *> ExprArgs,
14992                                     SourceLocation CallSiteLoc) {
14993   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14994   bool IsPointerAttr = Attr->getIsPointer();
14995 
14996   // Retrieve the argument representing the 'type_tag'.
14997   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14998   if (TypeTagIdxAST >= ExprArgs.size()) {
14999     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15000         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15001     return;
15002   }
15003   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15004   bool FoundWrongKind;
15005   TypeTagData TypeInfo;
15006   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15007                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15008                         TypeInfo, isConstantEvaluated())) {
15009     if (FoundWrongKind)
15010       Diag(TypeTagExpr->getExprLoc(),
15011            diag::warn_type_tag_for_datatype_wrong_kind)
15012         << TypeTagExpr->getSourceRange();
15013     return;
15014   }
15015 
15016   // Retrieve the argument representing the 'arg_idx'.
15017   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15018   if (ArgumentIdxAST >= ExprArgs.size()) {
15019     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15020         << 1 << Attr->getArgumentIdx().getSourceIndex();
15021     return;
15022   }
15023   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15024   if (IsPointerAttr) {
15025     // Skip implicit cast of pointer to `void *' (as a function argument).
15026     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15027       if (ICE->getType()->isVoidPointerType() &&
15028           ICE->getCastKind() == CK_BitCast)
15029         ArgumentExpr = ICE->getSubExpr();
15030   }
15031   QualType ArgumentType = ArgumentExpr->getType();
15032 
15033   // Passing a `void*' pointer shouldn't trigger a warning.
15034   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15035     return;
15036 
15037   if (TypeInfo.MustBeNull) {
15038     // Type tag with matching void type requires a null pointer.
15039     if (!ArgumentExpr->isNullPointerConstant(Context,
15040                                              Expr::NPC_ValueDependentIsNotNull)) {
15041       Diag(ArgumentExpr->getExprLoc(),
15042            diag::warn_type_safety_null_pointer_required)
15043           << ArgumentKind->getName()
15044           << ArgumentExpr->getSourceRange()
15045           << TypeTagExpr->getSourceRange();
15046     }
15047     return;
15048   }
15049 
15050   QualType RequiredType = TypeInfo.Type;
15051   if (IsPointerAttr)
15052     RequiredType = Context.getPointerType(RequiredType);
15053 
15054   bool mismatch = false;
15055   if (!TypeInfo.LayoutCompatible) {
15056     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15057 
15058     // C++11 [basic.fundamental] p1:
15059     // Plain char, signed char, and unsigned char are three distinct types.
15060     //
15061     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15062     // char' depending on the current char signedness mode.
15063     if (mismatch)
15064       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15065                                            RequiredType->getPointeeType())) ||
15066           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15067         mismatch = false;
15068   } else
15069     if (IsPointerAttr)
15070       mismatch = !isLayoutCompatible(Context,
15071                                      ArgumentType->getPointeeType(),
15072                                      RequiredType->getPointeeType());
15073     else
15074       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15075 
15076   if (mismatch)
15077     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15078         << ArgumentType << ArgumentKind
15079         << TypeInfo.LayoutCompatible << RequiredType
15080         << ArgumentExpr->getSourceRange()
15081         << TypeTagExpr->getSourceRange();
15082 }
15083 
15084 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15085                                          CharUnits Alignment) {
15086   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15087 }
15088 
15089 void Sema::DiagnoseMisalignedMembers() {
15090   for (MisalignedMember &m : MisalignedMembers) {
15091     const NamedDecl *ND = m.RD;
15092     if (ND->getName().empty()) {
15093       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15094         ND = TD;
15095     }
15096     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15097         << m.MD << ND << m.E->getSourceRange();
15098   }
15099   MisalignedMembers.clear();
15100 }
15101 
15102 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15103   E = E->IgnoreParens();
15104   if (!T->isPointerType() && !T->isIntegerType())
15105     return;
15106   if (isa<UnaryOperator>(E) &&
15107       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15108     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15109     if (isa<MemberExpr>(Op)) {
15110       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15111       if (MA != MisalignedMembers.end() &&
15112           (T->isIntegerType() ||
15113            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15114                                    Context.getTypeAlignInChars(
15115                                        T->getPointeeType()) <= MA->Alignment))))
15116         MisalignedMembers.erase(MA);
15117     }
15118   }
15119 }
15120 
15121 void Sema::RefersToMemberWithReducedAlignment(
15122     Expr *E,
15123     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15124         Action) {
15125   const auto *ME = dyn_cast<MemberExpr>(E);
15126   if (!ME)
15127     return;
15128 
15129   // No need to check expressions with an __unaligned-qualified type.
15130   if (E->getType().getQualifiers().hasUnaligned())
15131     return;
15132 
15133   // For a chain of MemberExpr like "a.b.c.d" this list
15134   // will keep FieldDecl's like [d, c, b].
15135   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15136   const MemberExpr *TopME = nullptr;
15137   bool AnyIsPacked = false;
15138   do {
15139     QualType BaseType = ME->getBase()->getType();
15140     if (BaseType->isDependentType())
15141       return;
15142     if (ME->isArrow())
15143       BaseType = BaseType->getPointeeType();
15144     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15145     if (RD->isInvalidDecl())
15146       return;
15147 
15148     ValueDecl *MD = ME->getMemberDecl();
15149     auto *FD = dyn_cast<FieldDecl>(MD);
15150     // We do not care about non-data members.
15151     if (!FD || FD->isInvalidDecl())
15152       return;
15153 
15154     AnyIsPacked =
15155         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15156     ReverseMemberChain.push_back(FD);
15157 
15158     TopME = ME;
15159     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15160   } while (ME);
15161   assert(TopME && "We did not compute a topmost MemberExpr!");
15162 
15163   // Not the scope of this diagnostic.
15164   if (!AnyIsPacked)
15165     return;
15166 
15167   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15168   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15169   // TODO: The innermost base of the member expression may be too complicated.
15170   // For now, just disregard these cases. This is left for future
15171   // improvement.
15172   if (!DRE && !isa<CXXThisExpr>(TopBase))
15173       return;
15174 
15175   // Alignment expected by the whole expression.
15176   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15177 
15178   // No need to do anything else with this case.
15179   if (ExpectedAlignment.isOne())
15180     return;
15181 
15182   // Synthesize offset of the whole access.
15183   CharUnits Offset;
15184   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15185        I++) {
15186     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15187   }
15188 
15189   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15190   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15191       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15192 
15193   // The base expression of the innermost MemberExpr may give
15194   // stronger guarantees than the class containing the member.
15195   if (DRE && !TopME->isArrow()) {
15196     const ValueDecl *VD = DRE->getDecl();
15197     if (!VD->getType()->isReferenceType())
15198       CompleteObjectAlignment =
15199           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15200   }
15201 
15202   // Check if the synthesized offset fulfills the alignment.
15203   if (Offset % ExpectedAlignment != 0 ||
15204       // It may fulfill the offset it but the effective alignment may still be
15205       // lower than the expected expression alignment.
15206       CompleteObjectAlignment < ExpectedAlignment) {
15207     // If this happens, we want to determine a sensible culprit of this.
15208     // Intuitively, watching the chain of member expressions from right to
15209     // left, we start with the required alignment (as required by the field
15210     // type) but some packed attribute in that chain has reduced the alignment.
15211     // It may happen that another packed structure increases it again. But if
15212     // we are here such increase has not been enough. So pointing the first
15213     // FieldDecl that either is packed or else its RecordDecl is,
15214     // seems reasonable.
15215     FieldDecl *FD = nullptr;
15216     CharUnits Alignment;
15217     for (FieldDecl *FDI : ReverseMemberChain) {
15218       if (FDI->hasAttr<PackedAttr>() ||
15219           FDI->getParent()->hasAttr<PackedAttr>()) {
15220         FD = FDI;
15221         Alignment = std::min(
15222             Context.getTypeAlignInChars(FD->getType()),
15223             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15224         break;
15225       }
15226     }
15227     assert(FD && "We did not find a packed FieldDecl!");
15228     Action(E, FD->getParent(), FD, Alignment);
15229   }
15230 }
15231 
15232 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15233   using namespace std::placeholders;
15234 
15235   RefersToMemberWithReducedAlignment(
15236       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15237                      _2, _3, _4));
15238 }
15239 
15240 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15241                                             ExprResult CallResult) {
15242   if (checkArgCount(*this, TheCall, 1))
15243     return ExprError();
15244 
15245   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15246   if (MatrixArg.isInvalid())
15247     return MatrixArg;
15248   Expr *Matrix = MatrixArg.get();
15249 
15250   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15251   if (!MType) {
15252     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15253     return ExprError();
15254   }
15255 
15256   // Create returned matrix type by swapping rows and columns of the argument
15257   // matrix type.
15258   QualType ResultType = Context.getConstantMatrixType(
15259       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15260 
15261   // Change the return type to the type of the returned matrix.
15262   TheCall->setType(ResultType);
15263 
15264   // Update call argument to use the possibly converted matrix argument.
15265   TheCall->setArg(0, Matrix);
15266   return CallResult;
15267 }
15268 
15269 // Get and verify the matrix dimensions.
15270 static llvm::Optional<unsigned>
15271 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15272   llvm::APSInt Value(64);
15273   SourceLocation ErrorPos;
15274   if (!Expr->isIntegerConstantExpr(Value, S.Context, &ErrorPos)) {
15275     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15276         << Name;
15277     return {};
15278   }
15279   uint64_t Dim = Value.getZExtValue();
15280   if (!ConstantMatrixType::isDimensionValid(Dim)) {
15281     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15282         << Name << ConstantMatrixType::getMaxElementsPerDimension();
15283     return {};
15284   }
15285   return Dim;
15286 }
15287 
15288 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15289                                                   ExprResult CallResult) {
15290   if (!getLangOpts().MatrixTypes) {
15291     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15292     return ExprError();
15293   }
15294 
15295   if (checkArgCount(*this, TheCall, 4))
15296     return ExprError();
15297 
15298   Expr *PtrExpr = TheCall->getArg(0);
15299   Expr *RowsExpr = TheCall->getArg(1);
15300   Expr *ColumnsExpr = TheCall->getArg(2);
15301   Expr *StrideExpr = TheCall->getArg(3);
15302 
15303   bool ArgError = false;
15304 
15305   // Check pointer argument.
15306   {
15307     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15308     if (PtrConv.isInvalid())
15309       return PtrConv;
15310     PtrExpr = PtrConv.get();
15311     TheCall->setArg(0, PtrExpr);
15312     if (PtrExpr->isTypeDependent()) {
15313       TheCall->setType(Context.DependentTy);
15314       return TheCall;
15315     }
15316   }
15317 
15318   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15319   QualType ElementTy;
15320   if (!PtrTy) {
15321     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15322         << "first";
15323     ArgError = true;
15324   } else {
15325     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15326 
15327     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15328       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15329           << "first";
15330       ArgError = true;
15331     }
15332   }
15333 
15334   // Apply default Lvalue conversions and convert the expression to size_t.
15335   auto ApplyArgumentConversions = [this](Expr *E) {
15336     ExprResult Conv = DefaultLvalueConversion(E);
15337     if (Conv.isInvalid())
15338       return Conv;
15339 
15340     return tryConvertExprToType(Conv.get(), Context.getSizeType());
15341   };
15342 
15343   // Apply conversion to row and column expressions.
15344   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15345   if (!RowsConv.isInvalid()) {
15346     RowsExpr = RowsConv.get();
15347     TheCall->setArg(1, RowsExpr);
15348   } else
15349     RowsExpr = nullptr;
15350 
15351   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
15352   if (!ColumnsConv.isInvalid()) {
15353     ColumnsExpr = ColumnsConv.get();
15354     TheCall->setArg(2, ColumnsExpr);
15355   } else
15356     ColumnsExpr = nullptr;
15357 
15358   // If any any part of the result matrix type is still pending, just use
15359   // Context.DependentTy, until all parts are resolved.
15360   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
15361       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
15362     TheCall->setType(Context.DependentTy);
15363     return CallResult;
15364   }
15365 
15366   // Check row and column dimenions.
15367   llvm::Optional<unsigned> MaybeRows;
15368   if (RowsExpr)
15369     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
15370 
15371   llvm::Optional<unsigned> MaybeColumns;
15372   if (ColumnsExpr)
15373     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
15374 
15375   // Check stride argument.
15376   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
15377   if (StrideConv.isInvalid())
15378     return ExprError();
15379   StrideExpr = StrideConv.get();
15380   TheCall->setArg(3, StrideExpr);
15381 
15382   llvm::APSInt Value(64);
15383   if (MaybeRows && StrideExpr->isIntegerConstantExpr(Value, Context)) {
15384     uint64_t Stride = Value.getZExtValue();
15385     if (Stride < *MaybeRows) {
15386       Diag(StrideExpr->getBeginLoc(),
15387            diag::err_builtin_matrix_stride_too_small);
15388       ArgError = true;
15389     }
15390   }
15391 
15392   if (ArgError || !MaybeRows || !MaybeColumns)
15393     return ExprError();
15394 
15395   TheCall->setType(
15396       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
15397   return CallResult;
15398 }
15399 
15400 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
15401                                                    ExprResult CallResult) {
15402   if (checkArgCount(*this, TheCall, 3))
15403     return ExprError();
15404 
15405   Expr *MatrixExpr = TheCall->getArg(0);
15406   Expr *PtrExpr = TheCall->getArg(1);
15407   Expr *StrideExpr = TheCall->getArg(2);
15408 
15409   bool ArgError = false;
15410 
15411   {
15412     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
15413     if (MatrixConv.isInvalid())
15414       return MatrixConv;
15415     MatrixExpr = MatrixConv.get();
15416     TheCall->setArg(0, MatrixExpr);
15417   }
15418   if (MatrixExpr->isTypeDependent()) {
15419     TheCall->setType(Context.DependentTy);
15420     return TheCall;
15421   }
15422 
15423   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
15424   if (!MatrixTy) {
15425     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
15426     ArgError = true;
15427   }
15428 
15429   {
15430     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15431     if (PtrConv.isInvalid())
15432       return PtrConv;
15433     PtrExpr = PtrConv.get();
15434     TheCall->setArg(1, PtrExpr);
15435     if (PtrExpr->isTypeDependent()) {
15436       TheCall->setType(Context.DependentTy);
15437       return TheCall;
15438     }
15439   }
15440 
15441   // Check pointer argument.
15442   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15443   if (!PtrTy) {
15444     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15445         << "second";
15446     ArgError = true;
15447   } else {
15448     QualType ElementTy = PtrTy->getPointeeType();
15449     if (ElementTy.isConstQualified()) {
15450       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
15451       ArgError = true;
15452     }
15453     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
15454     if (MatrixTy &&
15455         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
15456       Diag(PtrExpr->getBeginLoc(),
15457            diag::err_builtin_matrix_pointer_arg_mismatch)
15458           << ElementTy << MatrixTy->getElementType();
15459       ArgError = true;
15460     }
15461   }
15462 
15463   // Apply default Lvalue conversions and convert the stride expression to
15464   // size_t.
15465   {
15466     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
15467     if (StrideConv.isInvalid())
15468       return StrideConv;
15469 
15470     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
15471     if (StrideConv.isInvalid())
15472       return StrideConv;
15473     StrideExpr = StrideConv.get();
15474     TheCall->setArg(2, StrideExpr);
15475   }
15476 
15477   // Check stride argument.
15478   llvm::APSInt Value(64);
15479   if (MatrixTy && StrideExpr->isIntegerConstantExpr(Value, Context)) {
15480     uint64_t Stride = Value.getZExtValue();
15481     if (Stride < MatrixTy->getNumRows()) {
15482       Diag(StrideExpr->getBeginLoc(),
15483            diag::err_builtin_matrix_stride_too_small);
15484       ArgError = true;
15485     }
15486   }
15487 
15488   if (ArgError)
15489     return ExprError();
15490 
15491   return CallResult;
15492 }
15493