1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSwitch.h"
79 #include "llvm/ADT/Triple.h"
80 #include "llvm/Support/AtomicOrdering.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ConvertUTF.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/Locale.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/SaveAndRestore.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include <algorithm>
91 #include <bitset>
92 #include <cassert>
93 #include <cstddef>
94 #include <cstdint>
95 #include <functional>
96 #include <limits>
97 #include <string>
98 #include <tuple>
99 #include <utility>
100 
101 using namespace clang;
102 using namespace sema;
103 
104 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
105                                                     unsigned ByteNo) const {
106   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
107                                Context.getTargetInfo());
108 }
109 
110 /// Checks that a call expression's argument count is the desired number.
111 /// This is useful when doing custom type-checking.  Returns true on error.
112 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
113   unsigned argCount = call->getNumArgs();
114   if (argCount == desiredArgCount) return false;
115 
116   if (argCount < desiredArgCount)
117     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
118            << 0 /*function call*/ << desiredArgCount << argCount
119            << call->getSourceRange();
120 
121   // Highlight all the excess arguments.
122   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
123                     call->getArg(argCount - 1)->getEndLoc());
124 
125   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
126     << 0 /*function call*/ << desiredArgCount << argCount
127     << call->getArg(1)->getSourceRange();
128 }
129 
130 /// Check that the first argument to __builtin_annotation is an integer
131 /// and the second argument is a non-wide string literal.
132 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
133   if (checkArgCount(S, TheCall, 2))
134     return true;
135 
136   // First argument should be an integer.
137   Expr *ValArg = TheCall->getArg(0);
138   QualType Ty = ValArg->getType();
139   if (!Ty->isIntegerType()) {
140     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
141         << ValArg->getSourceRange();
142     return true;
143   }
144 
145   // Second argument should be a constant string.
146   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
147   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
148   if (!Literal || !Literal->isAscii()) {
149     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
150         << StrArg->getSourceRange();
151     return true;
152   }
153 
154   TheCall->setType(Ty);
155   return false;
156 }
157 
158 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
159   // We need at least one argument.
160   if (TheCall->getNumArgs() < 1) {
161     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
162         << 0 << 1 << TheCall->getNumArgs()
163         << TheCall->getCallee()->getSourceRange();
164     return true;
165   }
166 
167   // All arguments should be wide string literals.
168   for (Expr *Arg : TheCall->arguments()) {
169     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
170     if (!Literal || !Literal->isWide()) {
171       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
172           << Arg->getSourceRange();
173       return true;
174     }
175   }
176 
177   return false;
178 }
179 
180 /// Check that the argument to __builtin_addressof is a glvalue, and set the
181 /// result type to the corresponding pointer type.
182 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
183   if (checkArgCount(S, TheCall, 1))
184     return true;
185 
186   ExprResult Arg(TheCall->getArg(0));
187   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
188   if (ResultType.isNull())
189     return true;
190 
191   TheCall->setArg(0, Arg.get());
192   TheCall->setType(ResultType);
193   return false;
194 }
195 
196 /// Check the number of arguments and set the result type to
197 /// the argument type.
198 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
199   if (checkArgCount(S, TheCall, 1))
200     return true;
201 
202   TheCall->setType(TheCall->getArg(0)->getType());
203   return false;
204 }
205 
206 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
207 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
208 /// type (but not a function pointer) and that the alignment is a power-of-two.
209 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
210   if (checkArgCount(S, TheCall, 2))
211     return true;
212 
213   clang::Expr *Source = TheCall->getArg(0);
214   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
215 
216   auto IsValidIntegerType = [](QualType Ty) {
217     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
218   };
219   QualType SrcTy = Source->getType();
220   // We should also be able to use it with arrays (but not functions!).
221   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
222     SrcTy = S.Context.getDecayedType(SrcTy);
223   }
224   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
225       SrcTy->isFunctionPointerType()) {
226     // FIXME: this is not quite the right error message since we don't allow
227     // floating point types, or member pointers.
228     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
229         << SrcTy;
230     return true;
231   }
232 
233   clang::Expr *AlignOp = TheCall->getArg(1);
234   if (!IsValidIntegerType(AlignOp->getType())) {
235     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
236         << AlignOp->getType();
237     return true;
238   }
239   Expr::EvalResult AlignResult;
240   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
241   // We can't check validity of alignment if it is value dependent.
242   if (!AlignOp->isValueDependent() &&
243       AlignOp->EvaluateAsInt(AlignResult, S.Context,
244                              Expr::SE_AllowSideEffects)) {
245     llvm::APSInt AlignValue = AlignResult.Val.getInt();
246     llvm::APSInt MaxValue(
247         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
248     if (AlignValue < 1) {
249       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
250       return true;
251     }
252     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
253       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
254           << MaxValue.toString(10);
255       return true;
256     }
257     if (!AlignValue.isPowerOf2()) {
258       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
259       return true;
260     }
261     if (AlignValue == 1) {
262       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
263           << IsBooleanAlignBuiltin;
264     }
265   }
266 
267   ExprResult SrcArg = S.PerformCopyInitialization(
268       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
269       SourceLocation(), Source);
270   if (SrcArg.isInvalid())
271     return true;
272   TheCall->setArg(0, SrcArg.get());
273   ExprResult AlignArg =
274       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
275                                       S.Context, AlignOp->getType(), false),
276                                   SourceLocation(), AlignOp);
277   if (AlignArg.isInvalid())
278     return true;
279   TheCall->setArg(1, AlignArg.get());
280   // For align_up/align_down, the return type is the same as the (potentially
281   // decayed) argument type including qualifiers. For is_aligned(), the result
282   // is always bool.
283   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
284   return false;
285 }
286 
287 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
288                                 unsigned BuiltinID) {
289   if (checkArgCount(S, TheCall, 3))
290     return true;
291 
292   // First two arguments should be integers.
293   for (unsigned I = 0; I < 2; ++I) {
294     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
295     if (Arg.isInvalid()) return true;
296     TheCall->setArg(I, Arg.get());
297 
298     QualType Ty = Arg.get()->getType();
299     if (!Ty->isIntegerType()) {
300       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
301           << Ty << Arg.get()->getSourceRange();
302       return true;
303     }
304   }
305 
306   // Third argument should be a pointer to a non-const integer.
307   // IRGen correctly handles volatile, restrict, and address spaces, and
308   // the other qualifiers aren't possible.
309   {
310     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
311     if (Arg.isInvalid()) return true;
312     TheCall->setArg(2, Arg.get());
313 
314     QualType Ty = Arg.get()->getType();
315     const auto *PtrTy = Ty->getAs<PointerType>();
316     if (!PtrTy ||
317         !PtrTy->getPointeeType()->isIntegerType() ||
318         PtrTy->getPointeeType().isConstQualified()) {
319       S.Diag(Arg.get()->getBeginLoc(),
320              diag::err_overflow_builtin_must_be_ptr_int)
321         << Ty << Arg.get()->getSourceRange();
322       return true;
323     }
324   }
325 
326   // Disallow signed ExtIntType args larger than 128 bits to mul function until
327   // we improve backend support.
328   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
329     for (unsigned I = 0; I < 3; ++I) {
330       const auto Arg = TheCall->getArg(I);
331       // Third argument will be a pointer.
332       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
333       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
334           S.getASTContext().getIntWidth(Ty) > 128)
335         return S.Diag(Arg->getBeginLoc(),
336                       diag::err_overflow_builtin_ext_int_max_size)
337                << 128;
338     }
339   }
340 
341   return false;
342 }
343 
344 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
345   if (checkArgCount(S, BuiltinCall, 2))
346     return true;
347 
348   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
349   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
350   Expr *Call = BuiltinCall->getArg(0);
351   Expr *Chain = BuiltinCall->getArg(1);
352 
353   if (Call->getStmtClass() != Stmt::CallExprClass) {
354     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
355         << Call->getSourceRange();
356     return true;
357   }
358 
359   auto CE = cast<CallExpr>(Call);
360   if (CE->getCallee()->getType()->isBlockPointerType()) {
361     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
362         << Call->getSourceRange();
363     return true;
364   }
365 
366   const Decl *TargetDecl = CE->getCalleeDecl();
367   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
368     if (FD->getBuiltinID()) {
369       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
370           << Call->getSourceRange();
371       return true;
372     }
373 
374   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
375     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
376         << Call->getSourceRange();
377     return true;
378   }
379 
380   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
381   if (ChainResult.isInvalid())
382     return true;
383   if (!ChainResult.get()->getType()->isPointerType()) {
384     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
385         << Chain->getSourceRange();
386     return true;
387   }
388 
389   QualType ReturnTy = CE->getCallReturnType(S.Context);
390   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
391   QualType BuiltinTy = S.Context.getFunctionType(
392       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
393   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
394 
395   Builtin =
396       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
397 
398   BuiltinCall->setType(CE->getType());
399   BuiltinCall->setValueKind(CE->getValueKind());
400   BuiltinCall->setObjectKind(CE->getObjectKind());
401   BuiltinCall->setCallee(Builtin);
402   BuiltinCall->setArg(1, ChainResult.get());
403 
404   return false;
405 }
406 
407 namespace {
408 
409 class EstimateSizeFormatHandler
410     : public analyze_format_string::FormatStringHandler {
411   size_t Size;
412 
413 public:
414   EstimateSizeFormatHandler(StringRef Format)
415       : Size(std::min(Format.find(0), Format.size()) +
416              1 /* null byte always written by sprintf */) {}
417 
418   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
419                              const char *, unsigned SpecifierLen) override {
420 
421     const size_t FieldWidth = computeFieldWidth(FS);
422     const size_t Precision = computePrecision(FS);
423 
424     // The actual format.
425     switch (FS.getConversionSpecifier().getKind()) {
426     // Just a char.
427     case analyze_format_string::ConversionSpecifier::cArg:
428     case analyze_format_string::ConversionSpecifier::CArg:
429       Size += std::max(FieldWidth, (size_t)1);
430       break;
431     // Just an integer.
432     case analyze_format_string::ConversionSpecifier::dArg:
433     case analyze_format_string::ConversionSpecifier::DArg:
434     case analyze_format_string::ConversionSpecifier::iArg:
435     case analyze_format_string::ConversionSpecifier::oArg:
436     case analyze_format_string::ConversionSpecifier::OArg:
437     case analyze_format_string::ConversionSpecifier::uArg:
438     case analyze_format_string::ConversionSpecifier::UArg:
439     case analyze_format_string::ConversionSpecifier::xArg:
440     case analyze_format_string::ConversionSpecifier::XArg:
441       Size += std::max(FieldWidth, Precision);
442       break;
443 
444     // %g style conversion switches between %f or %e style dynamically.
445     // %f always takes less space, so default to it.
446     case analyze_format_string::ConversionSpecifier::gArg:
447     case analyze_format_string::ConversionSpecifier::GArg:
448 
449     // Floating point number in the form '[+]ddd.ddd'.
450     case analyze_format_string::ConversionSpecifier::fArg:
451     case analyze_format_string::ConversionSpecifier::FArg:
452       Size += std::max(FieldWidth, 1 /* integer part */ +
453                                        (Precision ? 1 + Precision
454                                                   : 0) /* period + decimal */);
455       break;
456 
457     // Floating point number in the form '[-]d.ddde[+-]dd'.
458     case analyze_format_string::ConversionSpecifier::eArg:
459     case analyze_format_string::ConversionSpecifier::EArg:
460       Size +=
461           std::max(FieldWidth,
462                    1 /* integer part */ +
463                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
464                        1 /* e or E letter */ + 2 /* exponent */);
465       break;
466 
467     // Floating point number in the form '[-]0xh.hhhhp±dd'.
468     case analyze_format_string::ConversionSpecifier::aArg:
469     case analyze_format_string::ConversionSpecifier::AArg:
470       Size +=
471           std::max(FieldWidth,
472                    2 /* 0x */ + 1 /* integer part */ +
473                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
474                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
475       break;
476 
477     // Just a string.
478     case analyze_format_string::ConversionSpecifier::sArg:
479     case analyze_format_string::ConversionSpecifier::SArg:
480       Size += FieldWidth;
481       break;
482 
483     // Just a pointer in the form '0xddd'.
484     case analyze_format_string::ConversionSpecifier::pArg:
485       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
486       break;
487 
488     // A plain percent.
489     case analyze_format_string::ConversionSpecifier::PercentArg:
490       Size += 1;
491       break;
492 
493     default:
494       break;
495     }
496 
497     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
498 
499     if (FS.hasAlternativeForm()) {
500       switch (FS.getConversionSpecifier().getKind()) {
501       default:
502         break;
503       // Force a leading '0'.
504       case analyze_format_string::ConversionSpecifier::oArg:
505         Size += 1;
506         break;
507       // Force a leading '0x'.
508       case analyze_format_string::ConversionSpecifier::xArg:
509       case analyze_format_string::ConversionSpecifier::XArg:
510         Size += 2;
511         break;
512       // Force a period '.' before decimal, even if precision is 0.
513       case analyze_format_string::ConversionSpecifier::aArg:
514       case analyze_format_string::ConversionSpecifier::AArg:
515       case analyze_format_string::ConversionSpecifier::eArg:
516       case analyze_format_string::ConversionSpecifier::EArg:
517       case analyze_format_string::ConversionSpecifier::fArg:
518       case analyze_format_string::ConversionSpecifier::FArg:
519       case analyze_format_string::ConversionSpecifier::gArg:
520       case analyze_format_string::ConversionSpecifier::GArg:
521         Size += (Precision ? 0 : 1);
522         break;
523       }
524     }
525     assert(SpecifierLen <= Size && "no underflow");
526     Size -= SpecifierLen;
527     return true;
528   }
529 
530   size_t getSizeLowerBound() const { return Size; }
531 
532 private:
533   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
534     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
535     size_t FieldWidth = 0;
536     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
537       FieldWidth = FW.getConstantAmount();
538     return FieldWidth;
539   }
540 
541   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
542     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
543     size_t Precision = 0;
544 
545     // See man 3 printf for default precision value based on the specifier.
546     switch (FW.getHowSpecified()) {
547     case analyze_format_string::OptionalAmount::NotSpecified:
548       switch (FS.getConversionSpecifier().getKind()) {
549       default:
550         break;
551       case analyze_format_string::ConversionSpecifier::dArg: // %d
552       case analyze_format_string::ConversionSpecifier::DArg: // %D
553       case analyze_format_string::ConversionSpecifier::iArg: // %i
554         Precision = 1;
555         break;
556       case analyze_format_string::ConversionSpecifier::oArg: // %d
557       case analyze_format_string::ConversionSpecifier::OArg: // %D
558       case analyze_format_string::ConversionSpecifier::uArg: // %d
559       case analyze_format_string::ConversionSpecifier::UArg: // %D
560       case analyze_format_string::ConversionSpecifier::xArg: // %d
561       case analyze_format_string::ConversionSpecifier::XArg: // %D
562         Precision = 1;
563         break;
564       case analyze_format_string::ConversionSpecifier::fArg: // %f
565       case analyze_format_string::ConversionSpecifier::FArg: // %F
566       case analyze_format_string::ConversionSpecifier::eArg: // %e
567       case analyze_format_string::ConversionSpecifier::EArg: // %E
568       case analyze_format_string::ConversionSpecifier::gArg: // %g
569       case analyze_format_string::ConversionSpecifier::GArg: // %G
570         Precision = 6;
571         break;
572       case analyze_format_string::ConversionSpecifier::pArg: // %d
573         Precision = 1;
574         break;
575       }
576       break;
577     case analyze_format_string::OptionalAmount::Constant:
578       Precision = FW.getConstantAmount();
579       break;
580     default:
581       break;
582     }
583     return Precision;
584   }
585 };
586 
587 } // namespace
588 
589 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
590 /// __builtin_*_chk function, then use the object size argument specified in the
591 /// source. Otherwise, infer the object size using __builtin_object_size.
592 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
593                                                CallExpr *TheCall) {
594   // FIXME: There are some more useful checks we could be doing here:
595   //  - Evaluate strlen of strcpy arguments, use as object size.
596 
597   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
598       isConstantEvaluated())
599     return;
600 
601   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
602   if (!BuiltinID)
603     return;
604 
605   const TargetInfo &TI = getASTContext().getTargetInfo();
606   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
607 
608   unsigned DiagID = 0;
609   bool IsChkVariant = false;
610   Optional<llvm::APSInt> UsedSize;
611   unsigned SizeIndex, ObjectIndex;
612   switch (BuiltinID) {
613   default:
614     return;
615   case Builtin::BIsprintf:
616   case Builtin::BI__builtin___sprintf_chk: {
617     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
618     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
619 
620     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
621 
622       if (!Format->isAscii() && !Format->isUTF8())
623         return;
624 
625       StringRef FormatStrRef = Format->getString();
626       EstimateSizeFormatHandler H(FormatStrRef);
627       const char *FormatBytes = FormatStrRef.data();
628       const ConstantArrayType *T =
629           Context.getAsConstantArrayType(Format->getType());
630       assert(T && "String literal not of constant array type!");
631       size_t TypeSize = T->getSize().getZExtValue();
632 
633       // In case there's a null byte somewhere.
634       size_t StrLen =
635           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
636       if (!analyze_format_string::ParsePrintfString(
637               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
638               Context.getTargetInfo(), false)) {
639         DiagID = diag::warn_fortify_source_format_overflow;
640         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
641                        .extOrTrunc(SizeTypeWidth);
642         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
643           IsChkVariant = true;
644           ObjectIndex = 2;
645         } else {
646           IsChkVariant = false;
647           ObjectIndex = 0;
648         }
649         break;
650       }
651     }
652     return;
653   }
654   case Builtin::BI__builtin___memcpy_chk:
655   case Builtin::BI__builtin___memmove_chk:
656   case Builtin::BI__builtin___memset_chk:
657   case Builtin::BI__builtin___strlcat_chk:
658   case Builtin::BI__builtin___strlcpy_chk:
659   case Builtin::BI__builtin___strncat_chk:
660   case Builtin::BI__builtin___strncpy_chk:
661   case Builtin::BI__builtin___stpncpy_chk:
662   case Builtin::BI__builtin___memccpy_chk:
663   case Builtin::BI__builtin___mempcpy_chk: {
664     DiagID = diag::warn_builtin_chk_overflow;
665     IsChkVariant = true;
666     SizeIndex = TheCall->getNumArgs() - 2;
667     ObjectIndex = TheCall->getNumArgs() - 1;
668     break;
669   }
670 
671   case Builtin::BI__builtin___snprintf_chk:
672   case Builtin::BI__builtin___vsnprintf_chk: {
673     DiagID = diag::warn_builtin_chk_overflow;
674     IsChkVariant = true;
675     SizeIndex = 1;
676     ObjectIndex = 3;
677     break;
678   }
679 
680   case Builtin::BIstrncat:
681   case Builtin::BI__builtin_strncat:
682   case Builtin::BIstrncpy:
683   case Builtin::BI__builtin_strncpy:
684   case Builtin::BIstpncpy:
685   case Builtin::BI__builtin_stpncpy: {
686     // Whether these functions overflow depends on the runtime strlen of the
687     // string, not just the buffer size, so emitting the "always overflow"
688     // diagnostic isn't quite right. We should still diagnose passing a buffer
689     // size larger than the destination buffer though; this is a runtime abort
690     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
691     DiagID = diag::warn_fortify_source_size_mismatch;
692     SizeIndex = TheCall->getNumArgs() - 1;
693     ObjectIndex = 0;
694     break;
695   }
696 
697   case Builtin::BImemcpy:
698   case Builtin::BI__builtin_memcpy:
699   case Builtin::BImemmove:
700   case Builtin::BI__builtin_memmove:
701   case Builtin::BImemset:
702   case Builtin::BI__builtin_memset:
703   case Builtin::BImempcpy:
704   case Builtin::BI__builtin_mempcpy: {
705     DiagID = diag::warn_fortify_source_overflow;
706     SizeIndex = TheCall->getNumArgs() - 1;
707     ObjectIndex = 0;
708     break;
709   }
710   case Builtin::BIsnprintf:
711   case Builtin::BI__builtin_snprintf:
712   case Builtin::BIvsnprintf:
713   case Builtin::BI__builtin_vsnprintf: {
714     DiagID = diag::warn_fortify_source_size_mismatch;
715     SizeIndex = 1;
716     ObjectIndex = 0;
717     break;
718   }
719   }
720 
721   llvm::APSInt ObjectSize;
722   // For __builtin___*_chk, the object size is explicitly provided by the caller
723   // (usually using __builtin_object_size). Use that value to check this call.
724   if (IsChkVariant) {
725     Expr::EvalResult Result;
726     Expr *SizeArg = TheCall->getArg(ObjectIndex);
727     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
728       return;
729     ObjectSize = Result.Val.getInt();
730 
731   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
732   } else {
733     // If the parameter has a pass_object_size attribute, then we should use its
734     // (potentially) more strict checking mode. Otherwise, conservatively assume
735     // type 0.
736     int BOSType = 0;
737     if (const auto *POS =
738             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
739       BOSType = POS->getType();
740 
741     Expr *ObjArg = TheCall->getArg(ObjectIndex);
742     uint64_t Result;
743     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
744       return;
745     // Get the object size in the target's size_t width.
746     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
747   }
748 
749   // Evaluate the number of bytes of the object that this call will use.
750   if (!UsedSize) {
751     Expr::EvalResult Result;
752     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
753     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
754       return;
755     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
756   }
757 
758   if (UsedSize.getValue().ule(ObjectSize))
759     return;
760 
761   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
762   // Skim off the details of whichever builtin was called to produce a better
763   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
764   if (IsChkVariant) {
765     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
766     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
767   } else if (FunctionName.startswith("__builtin_")) {
768     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
769   }
770 
771   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
772                       PDiag(DiagID)
773                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
774                           << UsedSize.getValue().toString(/*Radix=*/10));
775 }
776 
777 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
778                                      Scope::ScopeFlags NeededScopeFlags,
779                                      unsigned DiagID) {
780   // Scopes aren't available during instantiation. Fortunately, builtin
781   // functions cannot be template args so they cannot be formed through template
782   // instantiation. Therefore checking once during the parse is sufficient.
783   if (SemaRef.inTemplateInstantiation())
784     return false;
785 
786   Scope *S = SemaRef.getCurScope();
787   while (S && !S->isSEHExceptScope())
788     S = S->getParent();
789   if (!S || !(S->getFlags() & NeededScopeFlags)) {
790     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
791     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
792         << DRE->getDecl()->getIdentifier();
793     return true;
794   }
795 
796   return false;
797 }
798 
799 static inline bool isBlockPointer(Expr *Arg) {
800   return Arg->getType()->isBlockPointerType();
801 }
802 
803 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
804 /// void*, which is a requirement of device side enqueue.
805 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
806   const BlockPointerType *BPT =
807       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
808   ArrayRef<QualType> Params =
809       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
810   unsigned ArgCounter = 0;
811   bool IllegalParams = false;
812   // Iterate through the block parameters until either one is found that is not
813   // a local void*, or the block is valid.
814   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
815        I != E; ++I, ++ArgCounter) {
816     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
817         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
818             LangAS::opencl_local) {
819       // Get the location of the error. If a block literal has been passed
820       // (BlockExpr) then we can point straight to the offending argument,
821       // else we just point to the variable reference.
822       SourceLocation ErrorLoc;
823       if (isa<BlockExpr>(BlockArg)) {
824         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
825         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
826       } else if (isa<DeclRefExpr>(BlockArg)) {
827         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
828       }
829       S.Diag(ErrorLoc,
830              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
831       IllegalParams = true;
832     }
833   }
834 
835   return IllegalParams;
836 }
837 
838 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
839   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
840     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
841         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
842     return true;
843   }
844   return false;
845 }
846 
847 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
848   if (checkArgCount(S, TheCall, 2))
849     return true;
850 
851   if (checkOpenCLSubgroupExt(S, TheCall))
852     return true;
853 
854   // First argument is an ndrange_t type.
855   Expr *NDRangeArg = TheCall->getArg(0);
856   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
857     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
858         << TheCall->getDirectCallee() << "'ndrange_t'";
859     return true;
860   }
861 
862   Expr *BlockArg = TheCall->getArg(1);
863   if (!isBlockPointer(BlockArg)) {
864     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
865         << TheCall->getDirectCallee() << "block";
866     return true;
867   }
868   return checkOpenCLBlockArgs(S, BlockArg);
869 }
870 
871 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
872 /// get_kernel_work_group_size
873 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
874 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
875   if (checkArgCount(S, TheCall, 1))
876     return true;
877 
878   Expr *BlockArg = TheCall->getArg(0);
879   if (!isBlockPointer(BlockArg)) {
880     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
881         << TheCall->getDirectCallee() << "block";
882     return true;
883   }
884   return checkOpenCLBlockArgs(S, BlockArg);
885 }
886 
887 /// Diagnose integer type and any valid implicit conversion to it.
888 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
889                                       const QualType &IntType);
890 
891 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
892                                             unsigned Start, unsigned End) {
893   bool IllegalParams = false;
894   for (unsigned I = Start; I <= End; ++I)
895     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
896                                               S.Context.getSizeType());
897   return IllegalParams;
898 }
899 
900 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
901 /// 'local void*' parameter of passed block.
902 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
903                                            Expr *BlockArg,
904                                            unsigned NumNonVarArgs) {
905   const BlockPointerType *BPT =
906       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
907   unsigned NumBlockParams =
908       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
909   unsigned TotalNumArgs = TheCall->getNumArgs();
910 
911   // For each argument passed to the block, a corresponding uint needs to
912   // be passed to describe the size of the local memory.
913   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
914     S.Diag(TheCall->getBeginLoc(),
915            diag::err_opencl_enqueue_kernel_local_size_args);
916     return true;
917   }
918 
919   // Check that the sizes of the local memory are specified by integers.
920   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
921                                          TotalNumArgs - 1);
922 }
923 
924 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
925 /// overload formats specified in Table 6.13.17.1.
926 /// int enqueue_kernel(queue_t queue,
927 ///                    kernel_enqueue_flags_t flags,
928 ///                    const ndrange_t ndrange,
929 ///                    void (^block)(void))
930 /// int enqueue_kernel(queue_t queue,
931 ///                    kernel_enqueue_flags_t flags,
932 ///                    const ndrange_t ndrange,
933 ///                    uint num_events_in_wait_list,
934 ///                    clk_event_t *event_wait_list,
935 ///                    clk_event_t *event_ret,
936 ///                    void (^block)(void))
937 /// int enqueue_kernel(queue_t queue,
938 ///                    kernel_enqueue_flags_t flags,
939 ///                    const ndrange_t ndrange,
940 ///                    void (^block)(local void*, ...),
941 ///                    uint size0, ...)
942 /// int enqueue_kernel(queue_t queue,
943 ///                    kernel_enqueue_flags_t flags,
944 ///                    const ndrange_t ndrange,
945 ///                    uint num_events_in_wait_list,
946 ///                    clk_event_t *event_wait_list,
947 ///                    clk_event_t *event_ret,
948 ///                    void (^block)(local void*, ...),
949 ///                    uint size0, ...)
950 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
951   unsigned NumArgs = TheCall->getNumArgs();
952 
953   if (NumArgs < 4) {
954     S.Diag(TheCall->getBeginLoc(),
955            diag::err_typecheck_call_too_few_args_at_least)
956         << 0 << 4 << NumArgs;
957     return true;
958   }
959 
960   Expr *Arg0 = TheCall->getArg(0);
961   Expr *Arg1 = TheCall->getArg(1);
962   Expr *Arg2 = TheCall->getArg(2);
963   Expr *Arg3 = TheCall->getArg(3);
964 
965   // First argument always needs to be a queue_t type.
966   if (!Arg0->getType()->isQueueT()) {
967     S.Diag(TheCall->getArg(0)->getBeginLoc(),
968            diag::err_opencl_builtin_expected_type)
969         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
970     return true;
971   }
972 
973   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
974   if (!Arg1->getType()->isIntegerType()) {
975     S.Diag(TheCall->getArg(1)->getBeginLoc(),
976            diag::err_opencl_builtin_expected_type)
977         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
978     return true;
979   }
980 
981   // Third argument is always an ndrange_t type.
982   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
983     S.Diag(TheCall->getArg(2)->getBeginLoc(),
984            diag::err_opencl_builtin_expected_type)
985         << TheCall->getDirectCallee() << "'ndrange_t'";
986     return true;
987   }
988 
989   // With four arguments, there is only one form that the function could be
990   // called in: no events and no variable arguments.
991   if (NumArgs == 4) {
992     // check that the last argument is the right block type.
993     if (!isBlockPointer(Arg3)) {
994       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
995           << TheCall->getDirectCallee() << "block";
996       return true;
997     }
998     // we have a block type, check the prototype
999     const BlockPointerType *BPT =
1000         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1001     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1002       S.Diag(Arg3->getBeginLoc(),
1003              diag::err_opencl_enqueue_kernel_blocks_no_args);
1004       return true;
1005     }
1006     return false;
1007   }
1008   // we can have block + varargs.
1009   if (isBlockPointer(Arg3))
1010     return (checkOpenCLBlockArgs(S, Arg3) ||
1011             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1012   // last two cases with either exactly 7 args or 7 args and varargs.
1013   if (NumArgs >= 7) {
1014     // check common block argument.
1015     Expr *Arg6 = TheCall->getArg(6);
1016     if (!isBlockPointer(Arg6)) {
1017       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1018           << TheCall->getDirectCallee() << "block";
1019       return true;
1020     }
1021     if (checkOpenCLBlockArgs(S, Arg6))
1022       return true;
1023 
1024     // Forth argument has to be any integer type.
1025     if (!Arg3->getType()->isIntegerType()) {
1026       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1027              diag::err_opencl_builtin_expected_type)
1028           << TheCall->getDirectCallee() << "integer";
1029       return true;
1030     }
1031     // check remaining common arguments.
1032     Expr *Arg4 = TheCall->getArg(4);
1033     Expr *Arg5 = TheCall->getArg(5);
1034 
1035     // Fifth argument is always passed as a pointer to clk_event_t.
1036     if (!Arg4->isNullPointerConstant(S.Context,
1037                                      Expr::NPC_ValueDependentIsNotNull) &&
1038         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1039       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1040              diag::err_opencl_builtin_expected_type)
1041           << TheCall->getDirectCallee()
1042           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1043       return true;
1044     }
1045 
1046     // Sixth argument is always passed as a pointer to clk_event_t.
1047     if (!Arg5->isNullPointerConstant(S.Context,
1048                                      Expr::NPC_ValueDependentIsNotNull) &&
1049         !(Arg5->getType()->isPointerType() &&
1050           Arg5->getType()->getPointeeType()->isClkEventT())) {
1051       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1052              diag::err_opencl_builtin_expected_type)
1053           << TheCall->getDirectCallee()
1054           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1055       return true;
1056     }
1057 
1058     if (NumArgs == 7)
1059       return false;
1060 
1061     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1062   }
1063 
1064   // None of the specific case has been detected, give generic error
1065   S.Diag(TheCall->getBeginLoc(),
1066          diag::err_opencl_enqueue_kernel_incorrect_args);
1067   return true;
1068 }
1069 
1070 /// Returns OpenCL access qual.
1071 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1072     return D->getAttr<OpenCLAccessAttr>();
1073 }
1074 
1075 /// Returns true if pipe element type is different from the pointer.
1076 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1077   const Expr *Arg0 = Call->getArg(0);
1078   // First argument type should always be pipe.
1079   if (!Arg0->getType()->isPipeType()) {
1080     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1081         << Call->getDirectCallee() << Arg0->getSourceRange();
1082     return true;
1083   }
1084   OpenCLAccessAttr *AccessQual =
1085       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1086   // Validates the access qualifier is compatible with the call.
1087   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1088   // read_only and write_only, and assumed to be read_only if no qualifier is
1089   // specified.
1090   switch (Call->getDirectCallee()->getBuiltinID()) {
1091   case Builtin::BIread_pipe:
1092   case Builtin::BIreserve_read_pipe:
1093   case Builtin::BIcommit_read_pipe:
1094   case Builtin::BIwork_group_reserve_read_pipe:
1095   case Builtin::BIsub_group_reserve_read_pipe:
1096   case Builtin::BIwork_group_commit_read_pipe:
1097   case Builtin::BIsub_group_commit_read_pipe:
1098     if (!(!AccessQual || AccessQual->isReadOnly())) {
1099       S.Diag(Arg0->getBeginLoc(),
1100              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1101           << "read_only" << Arg0->getSourceRange();
1102       return true;
1103     }
1104     break;
1105   case Builtin::BIwrite_pipe:
1106   case Builtin::BIreserve_write_pipe:
1107   case Builtin::BIcommit_write_pipe:
1108   case Builtin::BIwork_group_reserve_write_pipe:
1109   case Builtin::BIsub_group_reserve_write_pipe:
1110   case Builtin::BIwork_group_commit_write_pipe:
1111   case Builtin::BIsub_group_commit_write_pipe:
1112     if (!(AccessQual && AccessQual->isWriteOnly())) {
1113       S.Diag(Arg0->getBeginLoc(),
1114              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1115           << "write_only" << Arg0->getSourceRange();
1116       return true;
1117     }
1118     break;
1119   default:
1120     break;
1121   }
1122   return false;
1123 }
1124 
1125 /// Returns true if pipe element type is different from the pointer.
1126 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1127   const Expr *Arg0 = Call->getArg(0);
1128   const Expr *ArgIdx = Call->getArg(Idx);
1129   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1130   const QualType EltTy = PipeTy->getElementType();
1131   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1132   // The Idx argument should be a pointer and the type of the pointer and
1133   // the type of pipe element should also be the same.
1134   if (!ArgTy ||
1135       !S.Context.hasSameType(
1136           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1137     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1138         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1139         << ArgIdx->getType() << ArgIdx->getSourceRange();
1140     return true;
1141   }
1142   return false;
1143 }
1144 
1145 // Performs semantic analysis for the read/write_pipe call.
1146 // \param S Reference to the semantic analyzer.
1147 // \param Call A pointer to the builtin call.
1148 // \return True if a semantic error has been found, false otherwise.
1149 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1150   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1151   // functions have two forms.
1152   switch (Call->getNumArgs()) {
1153   case 2:
1154     if (checkOpenCLPipeArg(S, Call))
1155       return true;
1156     // The call with 2 arguments should be
1157     // read/write_pipe(pipe T, T*).
1158     // Check packet type T.
1159     if (checkOpenCLPipePacketType(S, Call, 1))
1160       return true;
1161     break;
1162 
1163   case 4: {
1164     if (checkOpenCLPipeArg(S, Call))
1165       return true;
1166     // The call with 4 arguments should be
1167     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1168     // Check reserve_id_t.
1169     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1170       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1171           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1172           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1173       return true;
1174     }
1175 
1176     // Check the index.
1177     const Expr *Arg2 = Call->getArg(2);
1178     if (!Arg2->getType()->isIntegerType() &&
1179         !Arg2->getType()->isUnsignedIntegerType()) {
1180       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1181           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1182           << Arg2->getType() << Arg2->getSourceRange();
1183       return true;
1184     }
1185 
1186     // Check packet type T.
1187     if (checkOpenCLPipePacketType(S, Call, 3))
1188       return true;
1189   } break;
1190   default:
1191     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1192         << Call->getDirectCallee() << Call->getSourceRange();
1193     return true;
1194   }
1195 
1196   return false;
1197 }
1198 
1199 // Performs a semantic analysis on the {work_group_/sub_group_
1200 //        /_}reserve_{read/write}_pipe
1201 // \param S Reference to the semantic analyzer.
1202 // \param Call The call to the builtin function to be analyzed.
1203 // \return True if a semantic error was found, false otherwise.
1204 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1205   if (checkArgCount(S, Call, 2))
1206     return true;
1207 
1208   if (checkOpenCLPipeArg(S, Call))
1209     return true;
1210 
1211   // Check the reserve size.
1212   if (!Call->getArg(1)->getType()->isIntegerType() &&
1213       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1214     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1215         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1216         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1217     return true;
1218   }
1219 
1220   // Since return type of reserve_read/write_pipe built-in function is
1221   // reserve_id_t, which is not defined in the builtin def file , we used int
1222   // as return type and need to override the return type of these functions.
1223   Call->setType(S.Context.OCLReserveIDTy);
1224 
1225   return false;
1226 }
1227 
1228 // Performs a semantic analysis on {work_group_/sub_group_
1229 //        /_}commit_{read/write}_pipe
1230 // \param S Reference to the semantic analyzer.
1231 // \param Call The call to the builtin function to be analyzed.
1232 // \return True if a semantic error was found, false otherwise.
1233 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1234   if (checkArgCount(S, Call, 2))
1235     return true;
1236 
1237   if (checkOpenCLPipeArg(S, Call))
1238     return true;
1239 
1240   // Check reserve_id_t.
1241   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1242     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1243         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1244         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1245     return true;
1246   }
1247 
1248   return false;
1249 }
1250 
1251 // Performs a semantic analysis on the call to built-in Pipe
1252 //        Query Functions.
1253 // \param S Reference to the semantic analyzer.
1254 // \param Call The call to the builtin function to be analyzed.
1255 // \return True if a semantic error was found, false otherwise.
1256 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1257   if (checkArgCount(S, Call, 1))
1258     return true;
1259 
1260   if (!Call->getArg(0)->getType()->isPipeType()) {
1261     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1262         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1263     return true;
1264   }
1265 
1266   return false;
1267 }
1268 
1269 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1270 // Performs semantic analysis for the to_global/local/private call.
1271 // \param S Reference to the semantic analyzer.
1272 // \param BuiltinID ID of the builtin function.
1273 // \param Call A pointer to the builtin call.
1274 // \return True if a semantic error has been found, false otherwise.
1275 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1276                                     CallExpr *Call) {
1277   if (Call->getNumArgs() != 1) {
1278     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
1279         << Call->getDirectCallee() << Call->getSourceRange();
1280     return true;
1281   }
1282 
1283   auto RT = Call->getArg(0)->getType();
1284   if (!RT->isPointerType() || RT->getPointeeType()
1285       .getAddressSpace() == LangAS::opencl_constant) {
1286     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1287         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1288     return true;
1289   }
1290 
1291   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1292     S.Diag(Call->getArg(0)->getBeginLoc(),
1293            diag::warn_opencl_generic_address_space_arg)
1294         << Call->getDirectCallee()->getNameInfo().getAsString()
1295         << Call->getArg(0)->getSourceRange();
1296   }
1297 
1298   RT = RT->getPointeeType();
1299   auto Qual = RT.getQualifiers();
1300   switch (BuiltinID) {
1301   case Builtin::BIto_global:
1302     Qual.setAddressSpace(LangAS::opencl_global);
1303     break;
1304   case Builtin::BIto_local:
1305     Qual.setAddressSpace(LangAS::opencl_local);
1306     break;
1307   case Builtin::BIto_private:
1308     Qual.setAddressSpace(LangAS::opencl_private);
1309     break;
1310   default:
1311     llvm_unreachable("Invalid builtin function");
1312   }
1313   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1314       RT.getUnqualifiedType(), Qual)));
1315 
1316   return false;
1317 }
1318 
1319 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1320   if (checkArgCount(S, TheCall, 1))
1321     return ExprError();
1322 
1323   // Compute __builtin_launder's parameter type from the argument.
1324   // The parameter type is:
1325   //  * The type of the argument if it's not an array or function type,
1326   //  Otherwise,
1327   //  * The decayed argument type.
1328   QualType ParamTy = [&]() {
1329     QualType ArgTy = TheCall->getArg(0)->getType();
1330     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1331       return S.Context.getPointerType(Ty->getElementType());
1332     if (ArgTy->isFunctionType()) {
1333       return S.Context.getPointerType(ArgTy);
1334     }
1335     return ArgTy;
1336   }();
1337 
1338   TheCall->setType(ParamTy);
1339 
1340   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1341     if (!ParamTy->isPointerType())
1342       return 0;
1343     if (ParamTy->isFunctionPointerType())
1344       return 1;
1345     if (ParamTy->isVoidPointerType())
1346       return 2;
1347     return llvm::Optional<unsigned>{};
1348   }();
1349   if (DiagSelect.hasValue()) {
1350     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1351         << DiagSelect.getValue() << TheCall->getSourceRange();
1352     return ExprError();
1353   }
1354 
1355   // We either have an incomplete class type, or we have a class template
1356   // whose instantiation has not been forced. Example:
1357   //
1358   //   template <class T> struct Foo { T value; };
1359   //   Foo<int> *p = nullptr;
1360   //   auto *d = __builtin_launder(p);
1361   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1362                             diag::err_incomplete_type))
1363     return ExprError();
1364 
1365   assert(ParamTy->getPointeeType()->isObjectType() &&
1366          "Unhandled non-object pointer case");
1367 
1368   InitializedEntity Entity =
1369       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1370   ExprResult Arg =
1371       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1372   if (Arg.isInvalid())
1373     return ExprError();
1374   TheCall->setArg(0, Arg.get());
1375 
1376   return TheCall;
1377 }
1378 
1379 // Emit an error and return true if the current architecture is not in the list
1380 // of supported architectures.
1381 static bool
1382 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1383                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1384   llvm::Triple::ArchType CurArch =
1385       S.getASTContext().getTargetInfo().getTriple().getArch();
1386   if (llvm::is_contained(SupportedArchs, CurArch))
1387     return false;
1388   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1389       << TheCall->getSourceRange();
1390   return true;
1391 }
1392 
1393 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1394                                  SourceLocation CallSiteLoc);
1395 
1396 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1397                                       CallExpr *TheCall) {
1398   switch (TI.getTriple().getArch()) {
1399   default:
1400     // Some builtins don't require additional checking, so just consider these
1401     // acceptable.
1402     return false;
1403   case llvm::Triple::arm:
1404   case llvm::Triple::armeb:
1405   case llvm::Triple::thumb:
1406   case llvm::Triple::thumbeb:
1407     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1408   case llvm::Triple::aarch64:
1409   case llvm::Triple::aarch64_32:
1410   case llvm::Triple::aarch64_be:
1411     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1412   case llvm::Triple::bpfeb:
1413   case llvm::Triple::bpfel:
1414     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1415   case llvm::Triple::hexagon:
1416     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1417   case llvm::Triple::mips:
1418   case llvm::Triple::mipsel:
1419   case llvm::Triple::mips64:
1420   case llvm::Triple::mips64el:
1421     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1422   case llvm::Triple::systemz:
1423     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1424   case llvm::Triple::x86:
1425   case llvm::Triple::x86_64:
1426     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1427   case llvm::Triple::ppc:
1428   case llvm::Triple::ppc64:
1429   case llvm::Triple::ppc64le:
1430     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1431   case llvm::Triple::amdgcn:
1432     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1433   }
1434 }
1435 
1436 ExprResult
1437 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1438                                CallExpr *TheCall) {
1439   ExprResult TheCallResult(TheCall);
1440 
1441   // Find out if any arguments are required to be integer constant expressions.
1442   unsigned ICEArguments = 0;
1443   ASTContext::GetBuiltinTypeError Error;
1444   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1445   if (Error != ASTContext::GE_None)
1446     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1447 
1448   // If any arguments are required to be ICE's, check and diagnose.
1449   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1450     // Skip arguments not required to be ICE's.
1451     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1452 
1453     llvm::APSInt Result;
1454     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1455       return true;
1456     ICEArguments &= ~(1 << ArgNo);
1457   }
1458 
1459   switch (BuiltinID) {
1460   case Builtin::BI__builtin___CFStringMakeConstantString:
1461     assert(TheCall->getNumArgs() == 1 &&
1462            "Wrong # arguments to builtin CFStringMakeConstantString");
1463     if (CheckObjCString(TheCall->getArg(0)))
1464       return ExprError();
1465     break;
1466   case Builtin::BI__builtin_ms_va_start:
1467   case Builtin::BI__builtin_stdarg_start:
1468   case Builtin::BI__builtin_va_start:
1469     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1470       return ExprError();
1471     break;
1472   case Builtin::BI__va_start: {
1473     switch (Context.getTargetInfo().getTriple().getArch()) {
1474     case llvm::Triple::aarch64:
1475     case llvm::Triple::arm:
1476     case llvm::Triple::thumb:
1477       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1478         return ExprError();
1479       break;
1480     default:
1481       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1482         return ExprError();
1483       break;
1484     }
1485     break;
1486   }
1487 
1488   // The acquire, release, and no fence variants are ARM and AArch64 only.
1489   case Builtin::BI_interlockedbittestandset_acq:
1490   case Builtin::BI_interlockedbittestandset_rel:
1491   case Builtin::BI_interlockedbittestandset_nf:
1492   case Builtin::BI_interlockedbittestandreset_acq:
1493   case Builtin::BI_interlockedbittestandreset_rel:
1494   case Builtin::BI_interlockedbittestandreset_nf:
1495     if (CheckBuiltinTargetSupport(
1496             *this, BuiltinID, TheCall,
1497             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1498       return ExprError();
1499     break;
1500 
1501   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1502   case Builtin::BI_bittest64:
1503   case Builtin::BI_bittestandcomplement64:
1504   case Builtin::BI_bittestandreset64:
1505   case Builtin::BI_bittestandset64:
1506   case Builtin::BI_interlockedbittestandreset64:
1507   case Builtin::BI_interlockedbittestandset64:
1508     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1509                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1510                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1511       return ExprError();
1512     break;
1513 
1514   case Builtin::BI__builtin_isgreater:
1515   case Builtin::BI__builtin_isgreaterequal:
1516   case Builtin::BI__builtin_isless:
1517   case Builtin::BI__builtin_islessequal:
1518   case Builtin::BI__builtin_islessgreater:
1519   case Builtin::BI__builtin_isunordered:
1520     if (SemaBuiltinUnorderedCompare(TheCall))
1521       return ExprError();
1522     break;
1523   case Builtin::BI__builtin_fpclassify:
1524     if (SemaBuiltinFPClassification(TheCall, 6))
1525       return ExprError();
1526     break;
1527   case Builtin::BI__builtin_isfinite:
1528   case Builtin::BI__builtin_isinf:
1529   case Builtin::BI__builtin_isinf_sign:
1530   case Builtin::BI__builtin_isnan:
1531   case Builtin::BI__builtin_isnormal:
1532   case Builtin::BI__builtin_signbit:
1533   case Builtin::BI__builtin_signbitf:
1534   case Builtin::BI__builtin_signbitl:
1535     if (SemaBuiltinFPClassification(TheCall, 1))
1536       return ExprError();
1537     break;
1538   case Builtin::BI__builtin_shufflevector:
1539     return SemaBuiltinShuffleVector(TheCall);
1540     // TheCall will be freed by the smart pointer here, but that's fine, since
1541     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1542   case Builtin::BI__builtin_prefetch:
1543     if (SemaBuiltinPrefetch(TheCall))
1544       return ExprError();
1545     break;
1546   case Builtin::BI__builtin_alloca_with_align:
1547     if (SemaBuiltinAllocaWithAlign(TheCall))
1548       return ExprError();
1549     LLVM_FALLTHROUGH;
1550   case Builtin::BI__builtin_alloca:
1551     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1552         << TheCall->getDirectCallee();
1553     break;
1554   case Builtin::BI__assume:
1555   case Builtin::BI__builtin_assume:
1556     if (SemaBuiltinAssume(TheCall))
1557       return ExprError();
1558     break;
1559   case Builtin::BI__builtin_assume_aligned:
1560     if (SemaBuiltinAssumeAligned(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI__builtin_dynamic_object_size:
1564   case Builtin::BI__builtin_object_size:
1565     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1566       return ExprError();
1567     break;
1568   case Builtin::BI__builtin_longjmp:
1569     if (SemaBuiltinLongjmp(TheCall))
1570       return ExprError();
1571     break;
1572   case Builtin::BI__builtin_setjmp:
1573     if (SemaBuiltinSetjmp(TheCall))
1574       return ExprError();
1575     break;
1576   case Builtin::BI_setjmp:
1577   case Builtin::BI_setjmpex:
1578     if (checkArgCount(*this, TheCall, 1))
1579       return true;
1580     break;
1581   case Builtin::BI__builtin_classify_type:
1582     if (checkArgCount(*this, TheCall, 1)) return true;
1583     TheCall->setType(Context.IntTy);
1584     break;
1585   case Builtin::BI__builtin_constant_p: {
1586     if (checkArgCount(*this, TheCall, 1)) return true;
1587     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1588     if (Arg.isInvalid()) return true;
1589     TheCall->setArg(0, Arg.get());
1590     TheCall->setType(Context.IntTy);
1591     break;
1592   }
1593   case Builtin::BI__builtin_launder:
1594     return SemaBuiltinLaunder(*this, TheCall);
1595   case Builtin::BI__sync_fetch_and_add:
1596   case Builtin::BI__sync_fetch_and_add_1:
1597   case Builtin::BI__sync_fetch_and_add_2:
1598   case Builtin::BI__sync_fetch_and_add_4:
1599   case Builtin::BI__sync_fetch_and_add_8:
1600   case Builtin::BI__sync_fetch_and_add_16:
1601   case Builtin::BI__sync_fetch_and_sub:
1602   case Builtin::BI__sync_fetch_and_sub_1:
1603   case Builtin::BI__sync_fetch_and_sub_2:
1604   case Builtin::BI__sync_fetch_and_sub_4:
1605   case Builtin::BI__sync_fetch_and_sub_8:
1606   case Builtin::BI__sync_fetch_and_sub_16:
1607   case Builtin::BI__sync_fetch_and_or:
1608   case Builtin::BI__sync_fetch_and_or_1:
1609   case Builtin::BI__sync_fetch_and_or_2:
1610   case Builtin::BI__sync_fetch_and_or_4:
1611   case Builtin::BI__sync_fetch_and_or_8:
1612   case Builtin::BI__sync_fetch_and_or_16:
1613   case Builtin::BI__sync_fetch_and_and:
1614   case Builtin::BI__sync_fetch_and_and_1:
1615   case Builtin::BI__sync_fetch_and_and_2:
1616   case Builtin::BI__sync_fetch_and_and_4:
1617   case Builtin::BI__sync_fetch_and_and_8:
1618   case Builtin::BI__sync_fetch_and_and_16:
1619   case Builtin::BI__sync_fetch_and_xor:
1620   case Builtin::BI__sync_fetch_and_xor_1:
1621   case Builtin::BI__sync_fetch_and_xor_2:
1622   case Builtin::BI__sync_fetch_and_xor_4:
1623   case Builtin::BI__sync_fetch_and_xor_8:
1624   case Builtin::BI__sync_fetch_and_xor_16:
1625   case Builtin::BI__sync_fetch_and_nand:
1626   case Builtin::BI__sync_fetch_and_nand_1:
1627   case Builtin::BI__sync_fetch_and_nand_2:
1628   case Builtin::BI__sync_fetch_and_nand_4:
1629   case Builtin::BI__sync_fetch_and_nand_8:
1630   case Builtin::BI__sync_fetch_and_nand_16:
1631   case Builtin::BI__sync_add_and_fetch:
1632   case Builtin::BI__sync_add_and_fetch_1:
1633   case Builtin::BI__sync_add_and_fetch_2:
1634   case Builtin::BI__sync_add_and_fetch_4:
1635   case Builtin::BI__sync_add_and_fetch_8:
1636   case Builtin::BI__sync_add_and_fetch_16:
1637   case Builtin::BI__sync_sub_and_fetch:
1638   case Builtin::BI__sync_sub_and_fetch_1:
1639   case Builtin::BI__sync_sub_and_fetch_2:
1640   case Builtin::BI__sync_sub_and_fetch_4:
1641   case Builtin::BI__sync_sub_and_fetch_8:
1642   case Builtin::BI__sync_sub_and_fetch_16:
1643   case Builtin::BI__sync_and_and_fetch:
1644   case Builtin::BI__sync_and_and_fetch_1:
1645   case Builtin::BI__sync_and_and_fetch_2:
1646   case Builtin::BI__sync_and_and_fetch_4:
1647   case Builtin::BI__sync_and_and_fetch_8:
1648   case Builtin::BI__sync_and_and_fetch_16:
1649   case Builtin::BI__sync_or_and_fetch:
1650   case Builtin::BI__sync_or_and_fetch_1:
1651   case Builtin::BI__sync_or_and_fetch_2:
1652   case Builtin::BI__sync_or_and_fetch_4:
1653   case Builtin::BI__sync_or_and_fetch_8:
1654   case Builtin::BI__sync_or_and_fetch_16:
1655   case Builtin::BI__sync_xor_and_fetch:
1656   case Builtin::BI__sync_xor_and_fetch_1:
1657   case Builtin::BI__sync_xor_and_fetch_2:
1658   case Builtin::BI__sync_xor_and_fetch_4:
1659   case Builtin::BI__sync_xor_and_fetch_8:
1660   case Builtin::BI__sync_xor_and_fetch_16:
1661   case Builtin::BI__sync_nand_and_fetch:
1662   case Builtin::BI__sync_nand_and_fetch_1:
1663   case Builtin::BI__sync_nand_and_fetch_2:
1664   case Builtin::BI__sync_nand_and_fetch_4:
1665   case Builtin::BI__sync_nand_and_fetch_8:
1666   case Builtin::BI__sync_nand_and_fetch_16:
1667   case Builtin::BI__sync_val_compare_and_swap:
1668   case Builtin::BI__sync_val_compare_and_swap_1:
1669   case Builtin::BI__sync_val_compare_and_swap_2:
1670   case Builtin::BI__sync_val_compare_and_swap_4:
1671   case Builtin::BI__sync_val_compare_and_swap_8:
1672   case Builtin::BI__sync_val_compare_and_swap_16:
1673   case Builtin::BI__sync_bool_compare_and_swap:
1674   case Builtin::BI__sync_bool_compare_and_swap_1:
1675   case Builtin::BI__sync_bool_compare_and_swap_2:
1676   case Builtin::BI__sync_bool_compare_and_swap_4:
1677   case Builtin::BI__sync_bool_compare_and_swap_8:
1678   case Builtin::BI__sync_bool_compare_and_swap_16:
1679   case Builtin::BI__sync_lock_test_and_set:
1680   case Builtin::BI__sync_lock_test_and_set_1:
1681   case Builtin::BI__sync_lock_test_and_set_2:
1682   case Builtin::BI__sync_lock_test_and_set_4:
1683   case Builtin::BI__sync_lock_test_and_set_8:
1684   case Builtin::BI__sync_lock_test_and_set_16:
1685   case Builtin::BI__sync_lock_release:
1686   case Builtin::BI__sync_lock_release_1:
1687   case Builtin::BI__sync_lock_release_2:
1688   case Builtin::BI__sync_lock_release_4:
1689   case Builtin::BI__sync_lock_release_8:
1690   case Builtin::BI__sync_lock_release_16:
1691   case Builtin::BI__sync_swap:
1692   case Builtin::BI__sync_swap_1:
1693   case Builtin::BI__sync_swap_2:
1694   case Builtin::BI__sync_swap_4:
1695   case Builtin::BI__sync_swap_8:
1696   case Builtin::BI__sync_swap_16:
1697     return SemaBuiltinAtomicOverloaded(TheCallResult);
1698   case Builtin::BI__sync_synchronize:
1699     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1700         << TheCall->getCallee()->getSourceRange();
1701     break;
1702   case Builtin::BI__builtin_nontemporal_load:
1703   case Builtin::BI__builtin_nontemporal_store:
1704     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1705   case Builtin::BI__builtin_memcpy_inline: {
1706     clang::Expr *SizeOp = TheCall->getArg(2);
1707     // We warn about copying to or from `nullptr` pointers when `size` is
1708     // greater than 0. When `size` is value dependent we cannot evaluate its
1709     // value so we bail out.
1710     if (SizeOp->isValueDependent())
1711       break;
1712     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1713       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1714       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1715     }
1716     break;
1717   }
1718 #define BUILTIN(ID, TYPE, ATTRS)
1719 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1720   case Builtin::BI##ID: \
1721     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1722 #include "clang/Basic/Builtins.def"
1723   case Builtin::BI__annotation:
1724     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1725       return ExprError();
1726     break;
1727   case Builtin::BI__builtin_annotation:
1728     if (SemaBuiltinAnnotation(*this, TheCall))
1729       return ExprError();
1730     break;
1731   case Builtin::BI__builtin_addressof:
1732     if (SemaBuiltinAddressof(*this, TheCall))
1733       return ExprError();
1734     break;
1735   case Builtin::BI__builtin_is_aligned:
1736   case Builtin::BI__builtin_align_up:
1737   case Builtin::BI__builtin_align_down:
1738     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1739       return ExprError();
1740     break;
1741   case Builtin::BI__builtin_add_overflow:
1742   case Builtin::BI__builtin_sub_overflow:
1743   case Builtin::BI__builtin_mul_overflow:
1744     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_operator_new:
1748   case Builtin::BI__builtin_operator_delete: {
1749     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1750     ExprResult Res =
1751         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1752     if (Res.isInvalid())
1753       CorrectDelayedTyposInExpr(TheCallResult.get());
1754     return Res;
1755   }
1756   case Builtin::BI__builtin_dump_struct: {
1757     // We first want to ensure we are called with 2 arguments
1758     if (checkArgCount(*this, TheCall, 2))
1759       return ExprError();
1760     // Ensure that the first argument is of type 'struct XX *'
1761     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1762     const QualType PtrArgType = PtrArg->getType();
1763     if (!PtrArgType->isPointerType() ||
1764         !PtrArgType->getPointeeType()->isRecordType()) {
1765       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1766           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1767           << "structure pointer";
1768       return ExprError();
1769     }
1770 
1771     // Ensure that the second argument is of type 'FunctionType'
1772     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1773     const QualType FnPtrArgType = FnPtrArg->getType();
1774     if (!FnPtrArgType->isPointerType()) {
1775       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1776           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1777           << FnPtrArgType << "'int (*)(const char *, ...)'";
1778       return ExprError();
1779     }
1780 
1781     const auto *FuncType =
1782         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1783 
1784     if (!FuncType) {
1785       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1786           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1787           << FnPtrArgType << "'int (*)(const char *, ...)'";
1788       return ExprError();
1789     }
1790 
1791     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1792       if (!FT->getNumParams()) {
1793         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1794             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1795             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1796         return ExprError();
1797       }
1798       QualType PT = FT->getParamType(0);
1799       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1800           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1801           !PT->getPointeeType().isConstQualified()) {
1802         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1803             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1804             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1805         return ExprError();
1806       }
1807     }
1808 
1809     TheCall->setType(Context.IntTy);
1810     break;
1811   }
1812   case Builtin::BI__builtin_expect_with_probability: {
1813     // We first want to ensure we are called with 3 arguments
1814     if (checkArgCount(*this, TheCall, 3))
1815       return ExprError();
1816     // then check probability is constant float in range [0.0, 1.0]
1817     const Expr *ProbArg = TheCall->getArg(2);
1818     SmallVector<PartialDiagnosticAt, 8> Notes;
1819     Expr::EvalResult Eval;
1820     Eval.Diag = &Notes;
1821     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
1822                                           Context)) ||
1823         !Eval.Val.isFloat()) {
1824       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1825           << ProbArg->getSourceRange();
1826       for (const PartialDiagnosticAt &PDiag : Notes)
1827         Diag(PDiag.first, PDiag.second);
1828       return ExprError();
1829     }
1830     llvm::APFloat Probability = Eval.Val.getFloat();
1831     bool LoseInfo = false;
1832     Probability.convert(llvm::APFloat::IEEEdouble(),
1833                         llvm::RoundingMode::Dynamic, &LoseInfo);
1834     if (!(Probability >= llvm::APFloat(0.0) &&
1835           Probability <= llvm::APFloat(1.0))) {
1836       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1837           << ProbArg->getSourceRange();
1838       return ExprError();
1839     }
1840     break;
1841   }
1842   case Builtin::BI__builtin_preserve_access_index:
1843     if (SemaBuiltinPreserveAI(*this, TheCall))
1844       return ExprError();
1845     break;
1846   case Builtin::BI__builtin_call_with_static_chain:
1847     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1848       return ExprError();
1849     break;
1850   case Builtin::BI__exception_code:
1851   case Builtin::BI_exception_code:
1852     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1853                                  diag::err_seh___except_block))
1854       return ExprError();
1855     break;
1856   case Builtin::BI__exception_info:
1857   case Builtin::BI_exception_info:
1858     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1859                                  diag::err_seh___except_filter))
1860       return ExprError();
1861     break;
1862   case Builtin::BI__GetExceptionInfo:
1863     if (checkArgCount(*this, TheCall, 1))
1864       return ExprError();
1865 
1866     if (CheckCXXThrowOperand(
1867             TheCall->getBeginLoc(),
1868             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1869             TheCall))
1870       return ExprError();
1871 
1872     TheCall->setType(Context.VoidPtrTy);
1873     break;
1874   // OpenCL v2.0, s6.13.16 - Pipe functions
1875   case Builtin::BIread_pipe:
1876   case Builtin::BIwrite_pipe:
1877     // Since those two functions are declared with var args, we need a semantic
1878     // check for the argument.
1879     if (SemaBuiltinRWPipe(*this, TheCall))
1880       return ExprError();
1881     break;
1882   case Builtin::BIreserve_read_pipe:
1883   case Builtin::BIreserve_write_pipe:
1884   case Builtin::BIwork_group_reserve_read_pipe:
1885   case Builtin::BIwork_group_reserve_write_pipe:
1886     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1887       return ExprError();
1888     break;
1889   case Builtin::BIsub_group_reserve_read_pipe:
1890   case Builtin::BIsub_group_reserve_write_pipe:
1891     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1892         SemaBuiltinReserveRWPipe(*this, TheCall))
1893       return ExprError();
1894     break;
1895   case Builtin::BIcommit_read_pipe:
1896   case Builtin::BIcommit_write_pipe:
1897   case Builtin::BIwork_group_commit_read_pipe:
1898   case Builtin::BIwork_group_commit_write_pipe:
1899     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1900       return ExprError();
1901     break;
1902   case Builtin::BIsub_group_commit_read_pipe:
1903   case Builtin::BIsub_group_commit_write_pipe:
1904     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1905         SemaBuiltinCommitRWPipe(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIget_pipe_num_packets:
1909   case Builtin::BIget_pipe_max_packets:
1910     if (SemaBuiltinPipePackets(*this, TheCall))
1911       return ExprError();
1912     break;
1913   case Builtin::BIto_global:
1914   case Builtin::BIto_local:
1915   case Builtin::BIto_private:
1916     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1917       return ExprError();
1918     break;
1919   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1920   case Builtin::BIenqueue_kernel:
1921     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1922       return ExprError();
1923     break;
1924   case Builtin::BIget_kernel_work_group_size:
1925   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1926     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1930   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1931     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1932       return ExprError();
1933     break;
1934   case Builtin::BI__builtin_os_log_format:
1935     Cleanup.setExprNeedsCleanups(true);
1936     LLVM_FALLTHROUGH;
1937   case Builtin::BI__builtin_os_log_format_buffer_size:
1938     if (SemaBuiltinOSLogFormat(TheCall))
1939       return ExprError();
1940     break;
1941   case Builtin::BI__builtin_frame_address:
1942   case Builtin::BI__builtin_return_address: {
1943     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1944       return ExprError();
1945 
1946     // -Wframe-address warning if non-zero passed to builtin
1947     // return/frame address.
1948     Expr::EvalResult Result;
1949     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1950         Result.Val.getInt() != 0)
1951       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1952           << ((BuiltinID == Builtin::BI__builtin_return_address)
1953                   ? "__builtin_return_address"
1954                   : "__builtin_frame_address")
1955           << TheCall->getSourceRange();
1956     break;
1957   }
1958 
1959   case Builtin::BI__builtin_matrix_transpose:
1960     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1961 
1962   case Builtin::BI__builtin_matrix_column_major_load:
1963     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1964 
1965   case Builtin::BI__builtin_matrix_column_major_store:
1966     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1967   }
1968 
1969   // Since the target specific builtins for each arch overlap, only check those
1970   // of the arch we are compiling for.
1971   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1972     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1973       assert(Context.getAuxTargetInfo() &&
1974              "Aux Target Builtin, but not an aux target?");
1975 
1976       if (CheckTSBuiltinFunctionCall(
1977               *Context.getAuxTargetInfo(),
1978               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1979         return ExprError();
1980     } else {
1981       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1982                                      TheCall))
1983         return ExprError();
1984     }
1985   }
1986 
1987   return TheCallResult;
1988 }
1989 
1990 // Get the valid immediate range for the specified NEON type code.
1991 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1992   NeonTypeFlags Type(t);
1993   int IsQuad = ForceQuad ? true : Type.isQuad();
1994   switch (Type.getEltType()) {
1995   case NeonTypeFlags::Int8:
1996   case NeonTypeFlags::Poly8:
1997     return shift ? 7 : (8 << IsQuad) - 1;
1998   case NeonTypeFlags::Int16:
1999   case NeonTypeFlags::Poly16:
2000     return shift ? 15 : (4 << IsQuad) - 1;
2001   case NeonTypeFlags::Int32:
2002     return shift ? 31 : (2 << IsQuad) - 1;
2003   case NeonTypeFlags::Int64:
2004   case NeonTypeFlags::Poly64:
2005     return shift ? 63 : (1 << IsQuad) - 1;
2006   case NeonTypeFlags::Poly128:
2007     return shift ? 127 : (1 << IsQuad) - 1;
2008   case NeonTypeFlags::Float16:
2009     assert(!shift && "cannot shift float types!");
2010     return (4 << IsQuad) - 1;
2011   case NeonTypeFlags::Float32:
2012     assert(!shift && "cannot shift float types!");
2013     return (2 << IsQuad) - 1;
2014   case NeonTypeFlags::Float64:
2015     assert(!shift && "cannot shift float types!");
2016     return (1 << IsQuad) - 1;
2017   case NeonTypeFlags::BFloat16:
2018     assert(!shift && "cannot shift float types!");
2019     return (4 << IsQuad) - 1;
2020   }
2021   llvm_unreachable("Invalid NeonTypeFlag!");
2022 }
2023 
2024 /// getNeonEltType - Return the QualType corresponding to the elements of
2025 /// the vector type specified by the NeonTypeFlags.  This is used to check
2026 /// the pointer arguments for Neon load/store intrinsics.
2027 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2028                                bool IsPolyUnsigned, bool IsInt64Long) {
2029   switch (Flags.getEltType()) {
2030   case NeonTypeFlags::Int8:
2031     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2032   case NeonTypeFlags::Int16:
2033     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2034   case NeonTypeFlags::Int32:
2035     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2036   case NeonTypeFlags::Int64:
2037     if (IsInt64Long)
2038       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2039     else
2040       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2041                                 : Context.LongLongTy;
2042   case NeonTypeFlags::Poly8:
2043     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2044   case NeonTypeFlags::Poly16:
2045     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2046   case NeonTypeFlags::Poly64:
2047     if (IsInt64Long)
2048       return Context.UnsignedLongTy;
2049     else
2050       return Context.UnsignedLongLongTy;
2051   case NeonTypeFlags::Poly128:
2052     break;
2053   case NeonTypeFlags::Float16:
2054     return Context.HalfTy;
2055   case NeonTypeFlags::Float32:
2056     return Context.FloatTy;
2057   case NeonTypeFlags::Float64:
2058     return Context.DoubleTy;
2059   case NeonTypeFlags::BFloat16:
2060     return Context.BFloat16Ty;
2061   }
2062   llvm_unreachable("Invalid NeonTypeFlag!");
2063 }
2064 
2065 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2066   // Range check SVE intrinsics that take immediate values.
2067   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2068 
2069   switch (BuiltinID) {
2070   default:
2071     return false;
2072 #define GET_SVE_IMMEDIATE_CHECK
2073 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2074 #undef GET_SVE_IMMEDIATE_CHECK
2075   }
2076 
2077   // Perform all the immediate checks for this builtin call.
2078   bool HasError = false;
2079   for (auto &I : ImmChecks) {
2080     int ArgNum, CheckTy, ElementSizeInBits;
2081     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2082 
2083     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2084 
2085     // Function that checks whether the operand (ArgNum) is an immediate
2086     // that is one of the predefined values.
2087     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2088                                    int ErrDiag) -> bool {
2089       // We can't check the value of a dependent argument.
2090       Expr *Arg = TheCall->getArg(ArgNum);
2091       if (Arg->isTypeDependent() || Arg->isValueDependent())
2092         return false;
2093 
2094       // Check constant-ness first.
2095       llvm::APSInt Imm;
2096       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2097         return true;
2098 
2099       if (!CheckImm(Imm.getSExtValue()))
2100         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2101       return false;
2102     };
2103 
2104     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2105     case SVETypeFlags::ImmCheck0_31:
2106       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2107         HasError = true;
2108       break;
2109     case SVETypeFlags::ImmCheck0_13:
2110       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2111         HasError = true;
2112       break;
2113     case SVETypeFlags::ImmCheck1_16:
2114       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2115         HasError = true;
2116       break;
2117     case SVETypeFlags::ImmCheck0_7:
2118       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2119         HasError = true;
2120       break;
2121     case SVETypeFlags::ImmCheckExtract:
2122       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2123                                       (2048 / ElementSizeInBits) - 1))
2124         HasError = true;
2125       break;
2126     case SVETypeFlags::ImmCheckShiftRight:
2127       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2128         HasError = true;
2129       break;
2130     case SVETypeFlags::ImmCheckShiftRightNarrow:
2131       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2132                                       ElementSizeInBits / 2))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheckShiftLeft:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2137                                       ElementSizeInBits - 1))
2138         HasError = true;
2139       break;
2140     case SVETypeFlags::ImmCheckLaneIndex:
2141       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2142                                       (128 / (1 * ElementSizeInBits)) - 1))
2143         HasError = true;
2144       break;
2145     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2146       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2147                                       (128 / (2 * ElementSizeInBits)) - 1))
2148         HasError = true;
2149       break;
2150     case SVETypeFlags::ImmCheckLaneIndexDot:
2151       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2152                                       (128 / (4 * ElementSizeInBits)) - 1))
2153         HasError = true;
2154       break;
2155     case SVETypeFlags::ImmCheckComplexRot90_270:
2156       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2157                               diag::err_rotation_argument_to_cadd))
2158         HasError = true;
2159       break;
2160     case SVETypeFlags::ImmCheckComplexRotAll90:
2161       if (CheckImmediateInSet(
2162               [](int64_t V) {
2163                 return V == 0 || V == 90 || V == 180 || V == 270;
2164               },
2165               diag::err_rotation_argument_to_cmla))
2166         HasError = true;
2167       break;
2168     case SVETypeFlags::ImmCheck0_1:
2169       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2170         HasError = true;
2171       break;
2172     case SVETypeFlags::ImmCheck0_2:
2173       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2174         HasError = true;
2175       break;
2176     case SVETypeFlags::ImmCheck0_3:
2177       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2178         HasError = true;
2179       break;
2180     }
2181   }
2182 
2183   return HasError;
2184 }
2185 
2186 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2187                                         unsigned BuiltinID, CallExpr *TheCall) {
2188   llvm::APSInt Result;
2189   uint64_t mask = 0;
2190   unsigned TV = 0;
2191   int PtrArgNum = -1;
2192   bool HasConstPtr = false;
2193   switch (BuiltinID) {
2194 #define GET_NEON_OVERLOAD_CHECK
2195 #include "clang/Basic/arm_neon.inc"
2196 #include "clang/Basic/arm_fp16.inc"
2197 #undef GET_NEON_OVERLOAD_CHECK
2198   }
2199 
2200   // For NEON intrinsics which are overloaded on vector element type, validate
2201   // the immediate which specifies which variant to emit.
2202   unsigned ImmArg = TheCall->getNumArgs()-1;
2203   if (mask) {
2204     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2205       return true;
2206 
2207     TV = Result.getLimitedValue(64);
2208     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2209       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2210              << TheCall->getArg(ImmArg)->getSourceRange();
2211   }
2212 
2213   if (PtrArgNum >= 0) {
2214     // Check that pointer arguments have the specified type.
2215     Expr *Arg = TheCall->getArg(PtrArgNum);
2216     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2217       Arg = ICE->getSubExpr();
2218     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2219     QualType RHSTy = RHS.get()->getType();
2220 
2221     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2222     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2223                           Arch == llvm::Triple::aarch64_32 ||
2224                           Arch == llvm::Triple::aarch64_be;
2225     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2226     QualType EltTy =
2227         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2228     if (HasConstPtr)
2229       EltTy = EltTy.withConst();
2230     QualType LHSTy = Context.getPointerType(EltTy);
2231     AssignConvertType ConvTy;
2232     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2233     if (RHS.isInvalid())
2234       return true;
2235     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2236                                  RHS.get(), AA_Assigning))
2237       return true;
2238   }
2239 
2240   // For NEON intrinsics which take an immediate value as part of the
2241   // instruction, range check them here.
2242   unsigned i = 0, l = 0, u = 0;
2243   switch (BuiltinID) {
2244   default:
2245     return false;
2246   #define GET_NEON_IMMEDIATE_CHECK
2247   #include "clang/Basic/arm_neon.inc"
2248   #include "clang/Basic/arm_fp16.inc"
2249   #undef GET_NEON_IMMEDIATE_CHECK
2250   }
2251 
2252   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2253 }
2254 
2255 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2256   switch (BuiltinID) {
2257   default:
2258     return false;
2259   #include "clang/Basic/arm_mve_builtin_sema.inc"
2260   }
2261 }
2262 
2263 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2264                                        CallExpr *TheCall) {
2265   bool Err = false;
2266   switch (BuiltinID) {
2267   default:
2268     return false;
2269 #include "clang/Basic/arm_cde_builtin_sema.inc"
2270   }
2271 
2272   if (Err)
2273     return true;
2274 
2275   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2276 }
2277 
2278 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2279                                         const Expr *CoprocArg, bool WantCDE) {
2280   if (isConstantEvaluated())
2281     return false;
2282 
2283   // We can't check the value of a dependent argument.
2284   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2285     return false;
2286 
2287   llvm::APSInt CoprocNoAP;
2288   bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context);
2289   (void)IsICE;
2290   assert(IsICE && "Coprocossor immediate is not a constant expression");
2291   int64_t CoprocNo = CoprocNoAP.getExtValue();
2292   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2293 
2294   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2295   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2296 
2297   if (IsCDECoproc != WantCDE)
2298     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2299            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2300 
2301   return false;
2302 }
2303 
2304 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2305                                         unsigned MaxWidth) {
2306   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2307           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2308           BuiltinID == ARM::BI__builtin_arm_strex ||
2309           BuiltinID == ARM::BI__builtin_arm_stlex ||
2310           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2311           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2312           BuiltinID == AArch64::BI__builtin_arm_strex ||
2313           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2314          "unexpected ARM builtin");
2315   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2316                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2317                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2318                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2319 
2320   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2321 
2322   // Ensure that we have the proper number of arguments.
2323   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2324     return true;
2325 
2326   // Inspect the pointer argument of the atomic builtin.  This should always be
2327   // a pointer type, whose element is an integral scalar or pointer type.
2328   // Because it is a pointer type, we don't have to worry about any implicit
2329   // casts here.
2330   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2331   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2332   if (PointerArgRes.isInvalid())
2333     return true;
2334   PointerArg = PointerArgRes.get();
2335 
2336   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2337   if (!pointerType) {
2338     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2339         << PointerArg->getType() << PointerArg->getSourceRange();
2340     return true;
2341   }
2342 
2343   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2344   // task is to insert the appropriate casts into the AST. First work out just
2345   // what the appropriate type is.
2346   QualType ValType = pointerType->getPointeeType();
2347   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2348   if (IsLdrex)
2349     AddrType.addConst();
2350 
2351   // Issue a warning if the cast is dodgy.
2352   CastKind CastNeeded = CK_NoOp;
2353   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2354     CastNeeded = CK_BitCast;
2355     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2356         << PointerArg->getType() << Context.getPointerType(AddrType)
2357         << AA_Passing << PointerArg->getSourceRange();
2358   }
2359 
2360   // Finally, do the cast and replace the argument with the corrected version.
2361   AddrType = Context.getPointerType(AddrType);
2362   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2363   if (PointerArgRes.isInvalid())
2364     return true;
2365   PointerArg = PointerArgRes.get();
2366 
2367   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2368 
2369   // In general, we allow ints, floats and pointers to be loaded and stored.
2370   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2371       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2372     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2373         << PointerArg->getType() << PointerArg->getSourceRange();
2374     return true;
2375   }
2376 
2377   // But ARM doesn't have instructions to deal with 128-bit versions.
2378   if (Context.getTypeSize(ValType) > MaxWidth) {
2379     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2380     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2381         << PointerArg->getType() << PointerArg->getSourceRange();
2382     return true;
2383   }
2384 
2385   switch (ValType.getObjCLifetime()) {
2386   case Qualifiers::OCL_None:
2387   case Qualifiers::OCL_ExplicitNone:
2388     // okay
2389     break;
2390 
2391   case Qualifiers::OCL_Weak:
2392   case Qualifiers::OCL_Strong:
2393   case Qualifiers::OCL_Autoreleasing:
2394     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2395         << ValType << PointerArg->getSourceRange();
2396     return true;
2397   }
2398 
2399   if (IsLdrex) {
2400     TheCall->setType(ValType);
2401     return false;
2402   }
2403 
2404   // Initialize the argument to be stored.
2405   ExprResult ValArg = TheCall->getArg(0);
2406   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2407       Context, ValType, /*consume*/ false);
2408   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2409   if (ValArg.isInvalid())
2410     return true;
2411   TheCall->setArg(0, ValArg.get());
2412 
2413   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2414   // but the custom checker bypasses all default analysis.
2415   TheCall->setType(Context.IntTy);
2416   return false;
2417 }
2418 
2419 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2420                                        CallExpr *TheCall) {
2421   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2422       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2423       BuiltinID == ARM::BI__builtin_arm_strex ||
2424       BuiltinID == ARM::BI__builtin_arm_stlex) {
2425     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2426   }
2427 
2428   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2429     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2430       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2431   }
2432 
2433   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2434       BuiltinID == ARM::BI__builtin_arm_wsr64)
2435     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2436 
2437   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2438       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2439       BuiltinID == ARM::BI__builtin_arm_wsr ||
2440       BuiltinID == ARM::BI__builtin_arm_wsrp)
2441     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2442 
2443   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2444     return true;
2445   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2446     return true;
2447   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2448     return true;
2449 
2450   // For intrinsics which take an immediate value as part of the instruction,
2451   // range check them here.
2452   // FIXME: VFP Intrinsics should error if VFP not present.
2453   switch (BuiltinID) {
2454   default: return false;
2455   case ARM::BI__builtin_arm_ssat:
2456     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2457   case ARM::BI__builtin_arm_usat:
2458     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2459   case ARM::BI__builtin_arm_ssat16:
2460     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2461   case ARM::BI__builtin_arm_usat16:
2462     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2463   case ARM::BI__builtin_arm_vcvtr_f:
2464   case ARM::BI__builtin_arm_vcvtr_d:
2465     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2466   case ARM::BI__builtin_arm_dmb:
2467   case ARM::BI__builtin_arm_dsb:
2468   case ARM::BI__builtin_arm_isb:
2469   case ARM::BI__builtin_arm_dbg:
2470     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2471   case ARM::BI__builtin_arm_cdp:
2472   case ARM::BI__builtin_arm_cdp2:
2473   case ARM::BI__builtin_arm_mcr:
2474   case ARM::BI__builtin_arm_mcr2:
2475   case ARM::BI__builtin_arm_mrc:
2476   case ARM::BI__builtin_arm_mrc2:
2477   case ARM::BI__builtin_arm_mcrr:
2478   case ARM::BI__builtin_arm_mcrr2:
2479   case ARM::BI__builtin_arm_mrrc:
2480   case ARM::BI__builtin_arm_mrrc2:
2481   case ARM::BI__builtin_arm_ldc:
2482   case ARM::BI__builtin_arm_ldcl:
2483   case ARM::BI__builtin_arm_ldc2:
2484   case ARM::BI__builtin_arm_ldc2l:
2485   case ARM::BI__builtin_arm_stc:
2486   case ARM::BI__builtin_arm_stcl:
2487   case ARM::BI__builtin_arm_stc2:
2488   case ARM::BI__builtin_arm_stc2l:
2489     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2490            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2491                                         /*WantCDE*/ false);
2492   }
2493 }
2494 
2495 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2496                                            unsigned BuiltinID,
2497                                            CallExpr *TheCall) {
2498   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2499       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2500       BuiltinID == AArch64::BI__builtin_arm_strex ||
2501       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2502     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2503   }
2504 
2505   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2506     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2507       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2508       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2509       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2510   }
2511 
2512   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2513       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2514     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2515 
2516   // Memory Tagging Extensions (MTE) Intrinsics
2517   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2518       BuiltinID == AArch64::BI__builtin_arm_addg ||
2519       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2520       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2521       BuiltinID == AArch64::BI__builtin_arm_stg ||
2522       BuiltinID == AArch64::BI__builtin_arm_subp) {
2523     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2524   }
2525 
2526   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2527       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2528       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2529       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2530     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2531 
2532   // Only check the valid encoding range. Any constant in this range would be
2533   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2534   // an exception for incorrect registers. This matches MSVC behavior.
2535   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2536       BuiltinID == AArch64::BI_WriteStatusReg)
2537     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2538 
2539   if (BuiltinID == AArch64::BI__getReg)
2540     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2541 
2542   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2543     return true;
2544 
2545   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2546     return true;
2547 
2548   // For intrinsics which take an immediate value as part of the instruction,
2549   // range check them here.
2550   unsigned i = 0, l = 0, u = 0;
2551   switch (BuiltinID) {
2552   default: return false;
2553   case AArch64::BI__builtin_arm_dmb:
2554   case AArch64::BI__builtin_arm_dsb:
2555   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2556   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2557   }
2558 
2559   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2560 }
2561 
2562 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2563                                        CallExpr *TheCall) {
2564   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2565           BuiltinID == BPF::BI__builtin_btf_type_id) &&
2566          "unexpected ARM builtin");
2567 
2568   if (checkArgCount(*this, TheCall, 2))
2569     return true;
2570 
2571   Expr *Arg;
2572   if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2573     // The second argument needs to be a constant int
2574     llvm::APSInt Value;
2575     Arg = TheCall->getArg(1);
2576     if (!Arg->isIntegerConstantExpr(Value, Context)) {
2577       Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const)
2578           << 2 << Arg->getSourceRange();
2579       return true;
2580     }
2581 
2582     TheCall->setType(Context.UnsignedIntTy);
2583     return false;
2584   }
2585 
2586   // The first argument needs to be a record field access.
2587   // If it is an array element access, we delay decision
2588   // to BPF backend to check whether the access is a
2589   // field access or not.
2590   Arg = TheCall->getArg(0);
2591   if (Arg->getType()->getAsPlaceholderType() ||
2592       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2593        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2594        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2595     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2596         << 1 << Arg->getSourceRange();
2597     return true;
2598   }
2599 
2600   // The second argument needs to be a constant int
2601   Arg = TheCall->getArg(1);
2602   llvm::APSInt Value;
2603   if (!Arg->isIntegerConstantExpr(Value, Context)) {
2604     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2605         << 2 << Arg->getSourceRange();
2606     return true;
2607   }
2608 
2609   TheCall->setType(Context.UnsignedIntTy);
2610   return false;
2611 }
2612 
2613 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2614   struct ArgInfo {
2615     uint8_t OpNum;
2616     bool IsSigned;
2617     uint8_t BitWidth;
2618     uint8_t Align;
2619   };
2620   struct BuiltinInfo {
2621     unsigned BuiltinID;
2622     ArgInfo Infos[2];
2623   };
2624 
2625   static BuiltinInfo Infos[] = {
2626     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2627     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2628     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2629     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2630     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2631     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2632     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2633     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2634     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2635     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2636     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2637 
2638     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2639     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2640     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2641     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2642     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2643     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2644     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2645     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2646     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2647     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2648     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2649 
2650     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2651     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2652     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2653     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2654     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2655     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2656     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2657     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2658     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2659     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2660     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2661     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2662     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2663     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2664     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2665     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2666     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2667     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2668     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2669     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2670     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2671     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2672     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2673     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2674     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2675     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2676     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2677     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2678     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2679     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2680     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2681     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2682     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2683     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2684     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2685     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2686     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2687     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2688     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2690     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2691     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2692     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2693     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2695     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2696     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2697     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2698     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2699     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2700     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2701     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2702                                                       {{ 1, false, 6,  0 }} },
2703     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2706     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2709     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2710                                                       {{ 1, false, 5,  0 }} },
2711     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2712     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2713     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2714     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2715     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2716     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2717                                                        { 2, false, 5,  0 }} },
2718     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2719                                                        { 2, false, 6,  0 }} },
2720     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2721                                                        { 3, false, 5,  0 }} },
2722     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2723                                                        { 3, false, 6,  0 }} },
2724     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2725     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2726     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2727     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2728     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2729     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2730     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2731     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2732     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2733     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2734     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2735     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2736     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2737     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2738     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2739     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2740                                                       {{ 2, false, 4,  0 },
2741                                                        { 3, false, 5,  0 }} },
2742     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2743                                                       {{ 2, false, 4,  0 },
2744                                                        { 3, false, 5,  0 }} },
2745     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2746                                                       {{ 2, false, 4,  0 },
2747                                                        { 3, false, 5,  0 }} },
2748     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2749                                                       {{ 2, false, 4,  0 },
2750                                                        { 3, false, 5,  0 }} },
2751     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2752     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2753     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2754     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2755     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2756     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2757     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2759     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2760     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2761     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2762                                                        { 2, false, 5,  0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2764                                                        { 2, false, 6,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2774                                                       {{ 1, false, 4,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2777                                                       {{ 1, false, 4,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2798                                                       {{ 3, false, 1,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2803                                                       {{ 3, false, 1,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2808                                                       {{ 3, false, 1,  0 }} },
2809   };
2810 
2811   // Use a dynamically initialized static to sort the table exactly once on
2812   // first run.
2813   static const bool SortOnce =
2814       (llvm::sort(Infos,
2815                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2816                    return LHS.BuiltinID < RHS.BuiltinID;
2817                  }),
2818        true);
2819   (void)SortOnce;
2820 
2821   const BuiltinInfo *F = llvm::partition_point(
2822       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2823   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2824     return false;
2825 
2826   bool Error = false;
2827 
2828   for (const ArgInfo &A : F->Infos) {
2829     // Ignore empty ArgInfo elements.
2830     if (A.BitWidth == 0)
2831       continue;
2832 
2833     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2834     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2835     if (!A.Align) {
2836       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2837     } else {
2838       unsigned M = 1 << A.Align;
2839       Min *= M;
2840       Max *= M;
2841       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2842                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2843     }
2844   }
2845   return Error;
2846 }
2847 
2848 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2849                                            CallExpr *TheCall) {
2850   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2851 }
2852 
2853 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2854                                         unsigned BuiltinID, CallExpr *TheCall) {
2855   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2856          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2857 }
2858 
2859 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2860                                CallExpr *TheCall) {
2861 
2862   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2863       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2864     if (!TI.hasFeature("dsp"))
2865       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2866   }
2867 
2868   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2869       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2870     if (!TI.hasFeature("dspr2"))
2871       return Diag(TheCall->getBeginLoc(),
2872                   diag::err_mips_builtin_requires_dspr2);
2873   }
2874 
2875   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2876       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2877     if (!TI.hasFeature("msa"))
2878       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2879   }
2880 
2881   return false;
2882 }
2883 
2884 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2885 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2886 // ordering for DSP is unspecified. MSA is ordered by the data format used
2887 // by the underlying instruction i.e., df/m, df/n and then by size.
2888 //
2889 // FIXME: The size tests here should instead be tablegen'd along with the
2890 //        definitions from include/clang/Basic/BuiltinsMips.def.
2891 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2892 //        be too.
2893 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2894   unsigned i = 0, l = 0, u = 0, m = 0;
2895   switch (BuiltinID) {
2896   default: return false;
2897   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2898   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2899   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2900   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2901   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2902   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2903   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2904   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2905   // df/m field.
2906   // These intrinsics take an unsigned 3 bit immediate.
2907   case Mips::BI__builtin_msa_bclri_b:
2908   case Mips::BI__builtin_msa_bnegi_b:
2909   case Mips::BI__builtin_msa_bseti_b:
2910   case Mips::BI__builtin_msa_sat_s_b:
2911   case Mips::BI__builtin_msa_sat_u_b:
2912   case Mips::BI__builtin_msa_slli_b:
2913   case Mips::BI__builtin_msa_srai_b:
2914   case Mips::BI__builtin_msa_srari_b:
2915   case Mips::BI__builtin_msa_srli_b:
2916   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2917   case Mips::BI__builtin_msa_binsli_b:
2918   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2919   // These intrinsics take an unsigned 4 bit immediate.
2920   case Mips::BI__builtin_msa_bclri_h:
2921   case Mips::BI__builtin_msa_bnegi_h:
2922   case Mips::BI__builtin_msa_bseti_h:
2923   case Mips::BI__builtin_msa_sat_s_h:
2924   case Mips::BI__builtin_msa_sat_u_h:
2925   case Mips::BI__builtin_msa_slli_h:
2926   case Mips::BI__builtin_msa_srai_h:
2927   case Mips::BI__builtin_msa_srari_h:
2928   case Mips::BI__builtin_msa_srli_h:
2929   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2930   case Mips::BI__builtin_msa_binsli_h:
2931   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2932   // These intrinsics take an unsigned 5 bit immediate.
2933   // The first block of intrinsics actually have an unsigned 5 bit field,
2934   // not a df/n field.
2935   case Mips::BI__builtin_msa_cfcmsa:
2936   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2937   case Mips::BI__builtin_msa_clei_u_b:
2938   case Mips::BI__builtin_msa_clei_u_h:
2939   case Mips::BI__builtin_msa_clei_u_w:
2940   case Mips::BI__builtin_msa_clei_u_d:
2941   case Mips::BI__builtin_msa_clti_u_b:
2942   case Mips::BI__builtin_msa_clti_u_h:
2943   case Mips::BI__builtin_msa_clti_u_w:
2944   case Mips::BI__builtin_msa_clti_u_d:
2945   case Mips::BI__builtin_msa_maxi_u_b:
2946   case Mips::BI__builtin_msa_maxi_u_h:
2947   case Mips::BI__builtin_msa_maxi_u_w:
2948   case Mips::BI__builtin_msa_maxi_u_d:
2949   case Mips::BI__builtin_msa_mini_u_b:
2950   case Mips::BI__builtin_msa_mini_u_h:
2951   case Mips::BI__builtin_msa_mini_u_w:
2952   case Mips::BI__builtin_msa_mini_u_d:
2953   case Mips::BI__builtin_msa_addvi_b:
2954   case Mips::BI__builtin_msa_addvi_h:
2955   case Mips::BI__builtin_msa_addvi_w:
2956   case Mips::BI__builtin_msa_addvi_d:
2957   case Mips::BI__builtin_msa_bclri_w:
2958   case Mips::BI__builtin_msa_bnegi_w:
2959   case Mips::BI__builtin_msa_bseti_w:
2960   case Mips::BI__builtin_msa_sat_s_w:
2961   case Mips::BI__builtin_msa_sat_u_w:
2962   case Mips::BI__builtin_msa_slli_w:
2963   case Mips::BI__builtin_msa_srai_w:
2964   case Mips::BI__builtin_msa_srari_w:
2965   case Mips::BI__builtin_msa_srli_w:
2966   case Mips::BI__builtin_msa_srlri_w:
2967   case Mips::BI__builtin_msa_subvi_b:
2968   case Mips::BI__builtin_msa_subvi_h:
2969   case Mips::BI__builtin_msa_subvi_w:
2970   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2971   case Mips::BI__builtin_msa_binsli_w:
2972   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2973   // These intrinsics take an unsigned 6 bit immediate.
2974   case Mips::BI__builtin_msa_bclri_d:
2975   case Mips::BI__builtin_msa_bnegi_d:
2976   case Mips::BI__builtin_msa_bseti_d:
2977   case Mips::BI__builtin_msa_sat_s_d:
2978   case Mips::BI__builtin_msa_sat_u_d:
2979   case Mips::BI__builtin_msa_slli_d:
2980   case Mips::BI__builtin_msa_srai_d:
2981   case Mips::BI__builtin_msa_srari_d:
2982   case Mips::BI__builtin_msa_srli_d:
2983   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2984   case Mips::BI__builtin_msa_binsli_d:
2985   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2986   // These intrinsics take a signed 5 bit immediate.
2987   case Mips::BI__builtin_msa_ceqi_b:
2988   case Mips::BI__builtin_msa_ceqi_h:
2989   case Mips::BI__builtin_msa_ceqi_w:
2990   case Mips::BI__builtin_msa_ceqi_d:
2991   case Mips::BI__builtin_msa_clti_s_b:
2992   case Mips::BI__builtin_msa_clti_s_h:
2993   case Mips::BI__builtin_msa_clti_s_w:
2994   case Mips::BI__builtin_msa_clti_s_d:
2995   case Mips::BI__builtin_msa_clei_s_b:
2996   case Mips::BI__builtin_msa_clei_s_h:
2997   case Mips::BI__builtin_msa_clei_s_w:
2998   case Mips::BI__builtin_msa_clei_s_d:
2999   case Mips::BI__builtin_msa_maxi_s_b:
3000   case Mips::BI__builtin_msa_maxi_s_h:
3001   case Mips::BI__builtin_msa_maxi_s_w:
3002   case Mips::BI__builtin_msa_maxi_s_d:
3003   case Mips::BI__builtin_msa_mini_s_b:
3004   case Mips::BI__builtin_msa_mini_s_h:
3005   case Mips::BI__builtin_msa_mini_s_w:
3006   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3007   // These intrinsics take an unsigned 8 bit immediate.
3008   case Mips::BI__builtin_msa_andi_b:
3009   case Mips::BI__builtin_msa_nori_b:
3010   case Mips::BI__builtin_msa_ori_b:
3011   case Mips::BI__builtin_msa_shf_b:
3012   case Mips::BI__builtin_msa_shf_h:
3013   case Mips::BI__builtin_msa_shf_w:
3014   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3015   case Mips::BI__builtin_msa_bseli_b:
3016   case Mips::BI__builtin_msa_bmnzi_b:
3017   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3018   // df/n format
3019   // These intrinsics take an unsigned 4 bit immediate.
3020   case Mips::BI__builtin_msa_copy_s_b:
3021   case Mips::BI__builtin_msa_copy_u_b:
3022   case Mips::BI__builtin_msa_insve_b:
3023   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3024   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3025   // These intrinsics take an unsigned 3 bit immediate.
3026   case Mips::BI__builtin_msa_copy_s_h:
3027   case Mips::BI__builtin_msa_copy_u_h:
3028   case Mips::BI__builtin_msa_insve_h:
3029   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3030   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3031   // These intrinsics take an unsigned 2 bit immediate.
3032   case Mips::BI__builtin_msa_copy_s_w:
3033   case Mips::BI__builtin_msa_copy_u_w:
3034   case Mips::BI__builtin_msa_insve_w:
3035   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3036   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3037   // These intrinsics take an unsigned 1 bit immediate.
3038   case Mips::BI__builtin_msa_copy_s_d:
3039   case Mips::BI__builtin_msa_copy_u_d:
3040   case Mips::BI__builtin_msa_insve_d:
3041   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3042   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3043   // Memory offsets and immediate loads.
3044   // These intrinsics take a signed 10 bit immediate.
3045   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3046   case Mips::BI__builtin_msa_ldi_h:
3047   case Mips::BI__builtin_msa_ldi_w:
3048   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3049   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3050   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3051   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3052   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3053   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3054   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3055   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3056   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3057   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3058   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3059   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3060   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3061   }
3062 
3063   if (!m)
3064     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3065 
3066   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3067          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3068 }
3069 
3070 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3071                                        CallExpr *TheCall) {
3072   unsigned i = 0, l = 0, u = 0;
3073   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3074                       BuiltinID == PPC::BI__builtin_divdeu ||
3075                       BuiltinID == PPC::BI__builtin_bpermd;
3076   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3077   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3078                        BuiltinID == PPC::BI__builtin_divweu ||
3079                        BuiltinID == PPC::BI__builtin_divde ||
3080                        BuiltinID == PPC::BI__builtin_divdeu;
3081 
3082   if (Is64BitBltin && !IsTarget64Bit)
3083     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3084            << TheCall->getSourceRange();
3085 
3086   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3087       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3088     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3089            << TheCall->getSourceRange();
3090 
3091   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3092     if (!TI.hasFeature("vsx"))
3093       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3094              << TheCall->getSourceRange();
3095     return false;
3096   };
3097 
3098   switch (BuiltinID) {
3099   default: return false;
3100   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3101   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3102     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3103            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3104   case PPC::BI__builtin_altivec_dss:
3105     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3106   case PPC::BI__builtin_tbegin:
3107   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3108   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3109   case PPC::BI__builtin_tabortwc:
3110   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3111   case PPC::BI__builtin_tabortwci:
3112   case PPC::BI__builtin_tabortdci:
3113     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3114            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3115   case PPC::BI__builtin_altivec_dst:
3116   case PPC::BI__builtin_altivec_dstt:
3117   case PPC::BI__builtin_altivec_dstst:
3118   case PPC::BI__builtin_altivec_dststt:
3119     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3120   case PPC::BI__builtin_vsx_xxpermdi:
3121   case PPC::BI__builtin_vsx_xxsldwi:
3122     return SemaBuiltinVSX(TheCall);
3123   case PPC::BI__builtin_unpack_vector_int128:
3124     return SemaVSXCheck(TheCall) ||
3125            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3126   case PPC::BI__builtin_pack_vector_int128:
3127     return SemaVSXCheck(TheCall);
3128   case PPC::BI__builtin_altivec_vgnb:
3129      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3130   case PPC::BI__builtin_vsx_xxeval:
3131      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3132   case PPC::BI__builtin_altivec_vsldbi:
3133      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3134   case PPC::BI__builtin_altivec_vsrdbi:
3135      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3136   case PPC::BI__builtin_vsx_xxpermx:
3137      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3138   }
3139   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3140 }
3141 
3142 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3143                                           CallExpr *TheCall) {
3144   // position of memory order and scope arguments in the builtin
3145   unsigned OrderIndex, ScopeIndex;
3146   switch (BuiltinID) {
3147   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3148   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3149   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3150   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3151     OrderIndex = 2;
3152     ScopeIndex = 3;
3153     break;
3154   case AMDGPU::BI__builtin_amdgcn_fence:
3155     OrderIndex = 0;
3156     ScopeIndex = 1;
3157     break;
3158   default:
3159     return false;
3160   }
3161 
3162   ExprResult Arg = TheCall->getArg(OrderIndex);
3163   auto ArgExpr = Arg.get();
3164   Expr::EvalResult ArgResult;
3165 
3166   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3167     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3168            << ArgExpr->getType();
3169   int ord = ArgResult.Val.getInt().getZExtValue();
3170 
3171   // Check valididty of memory ordering as per C11 / C++11's memody model.
3172   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3173   case llvm::AtomicOrderingCABI::acquire:
3174   case llvm::AtomicOrderingCABI::release:
3175   case llvm::AtomicOrderingCABI::acq_rel:
3176   case llvm::AtomicOrderingCABI::seq_cst:
3177     break;
3178   default: {
3179     return Diag(ArgExpr->getBeginLoc(),
3180                 diag::warn_atomic_op_has_invalid_memory_order)
3181            << ArgExpr->getSourceRange();
3182   }
3183   }
3184 
3185   Arg = TheCall->getArg(ScopeIndex);
3186   ArgExpr = Arg.get();
3187   Expr::EvalResult ArgResult1;
3188   // Check that sync scope is a constant literal
3189   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen,
3190                                        Context))
3191     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3192            << ArgExpr->getType();
3193 
3194   return false;
3195 }
3196 
3197 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3198                                            CallExpr *TheCall) {
3199   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3200     Expr *Arg = TheCall->getArg(0);
3201     llvm::APSInt AbortCode(32);
3202     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3203         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3204       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3205              << Arg->getSourceRange();
3206   }
3207 
3208   // For intrinsics which take an immediate value as part of the instruction,
3209   // range check them here.
3210   unsigned i = 0, l = 0, u = 0;
3211   switch (BuiltinID) {
3212   default: return false;
3213   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3214   case SystemZ::BI__builtin_s390_verimb:
3215   case SystemZ::BI__builtin_s390_verimh:
3216   case SystemZ::BI__builtin_s390_verimf:
3217   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3218   case SystemZ::BI__builtin_s390_vfaeb:
3219   case SystemZ::BI__builtin_s390_vfaeh:
3220   case SystemZ::BI__builtin_s390_vfaef:
3221   case SystemZ::BI__builtin_s390_vfaebs:
3222   case SystemZ::BI__builtin_s390_vfaehs:
3223   case SystemZ::BI__builtin_s390_vfaefs:
3224   case SystemZ::BI__builtin_s390_vfaezb:
3225   case SystemZ::BI__builtin_s390_vfaezh:
3226   case SystemZ::BI__builtin_s390_vfaezf:
3227   case SystemZ::BI__builtin_s390_vfaezbs:
3228   case SystemZ::BI__builtin_s390_vfaezhs:
3229   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3230   case SystemZ::BI__builtin_s390_vfisb:
3231   case SystemZ::BI__builtin_s390_vfidb:
3232     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3233            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3234   case SystemZ::BI__builtin_s390_vftcisb:
3235   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3236   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3237   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3238   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3239   case SystemZ::BI__builtin_s390_vstrcb:
3240   case SystemZ::BI__builtin_s390_vstrch:
3241   case SystemZ::BI__builtin_s390_vstrcf:
3242   case SystemZ::BI__builtin_s390_vstrczb:
3243   case SystemZ::BI__builtin_s390_vstrczh:
3244   case SystemZ::BI__builtin_s390_vstrczf:
3245   case SystemZ::BI__builtin_s390_vstrcbs:
3246   case SystemZ::BI__builtin_s390_vstrchs:
3247   case SystemZ::BI__builtin_s390_vstrcfs:
3248   case SystemZ::BI__builtin_s390_vstrczbs:
3249   case SystemZ::BI__builtin_s390_vstrczhs:
3250   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3251   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3252   case SystemZ::BI__builtin_s390_vfminsb:
3253   case SystemZ::BI__builtin_s390_vfmaxsb:
3254   case SystemZ::BI__builtin_s390_vfmindb:
3255   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3256   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3257   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3258   }
3259   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3260 }
3261 
3262 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3263 /// This checks that the target supports __builtin_cpu_supports and
3264 /// that the string argument is constant and valid.
3265 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3266                                    CallExpr *TheCall) {
3267   Expr *Arg = TheCall->getArg(0);
3268 
3269   // Check if the argument is a string literal.
3270   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3271     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3272            << Arg->getSourceRange();
3273 
3274   // Check the contents of the string.
3275   StringRef Feature =
3276       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3277   if (!TI.validateCpuSupports(Feature))
3278     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3279            << Arg->getSourceRange();
3280   return false;
3281 }
3282 
3283 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3284 /// This checks that the target supports __builtin_cpu_is and
3285 /// that the string argument is constant and valid.
3286 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3287   Expr *Arg = TheCall->getArg(0);
3288 
3289   // Check if the argument is a string literal.
3290   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3291     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3292            << Arg->getSourceRange();
3293 
3294   // Check the contents of the string.
3295   StringRef Feature =
3296       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3297   if (!TI.validateCpuIs(Feature))
3298     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3299            << Arg->getSourceRange();
3300   return false;
3301 }
3302 
3303 // Check if the rounding mode is legal.
3304 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3305   // Indicates if this instruction has rounding control or just SAE.
3306   bool HasRC = false;
3307 
3308   unsigned ArgNum = 0;
3309   switch (BuiltinID) {
3310   default:
3311     return false;
3312   case X86::BI__builtin_ia32_vcvttsd2si32:
3313   case X86::BI__builtin_ia32_vcvttsd2si64:
3314   case X86::BI__builtin_ia32_vcvttsd2usi32:
3315   case X86::BI__builtin_ia32_vcvttsd2usi64:
3316   case X86::BI__builtin_ia32_vcvttss2si32:
3317   case X86::BI__builtin_ia32_vcvttss2si64:
3318   case X86::BI__builtin_ia32_vcvttss2usi32:
3319   case X86::BI__builtin_ia32_vcvttss2usi64:
3320     ArgNum = 1;
3321     break;
3322   case X86::BI__builtin_ia32_maxpd512:
3323   case X86::BI__builtin_ia32_maxps512:
3324   case X86::BI__builtin_ia32_minpd512:
3325   case X86::BI__builtin_ia32_minps512:
3326     ArgNum = 2;
3327     break;
3328   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3329   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3330   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3331   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3332   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3333   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3334   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3335   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3336   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3337   case X86::BI__builtin_ia32_exp2pd_mask:
3338   case X86::BI__builtin_ia32_exp2ps_mask:
3339   case X86::BI__builtin_ia32_getexppd512_mask:
3340   case X86::BI__builtin_ia32_getexpps512_mask:
3341   case X86::BI__builtin_ia32_rcp28pd_mask:
3342   case X86::BI__builtin_ia32_rcp28ps_mask:
3343   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3344   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3345   case X86::BI__builtin_ia32_vcomisd:
3346   case X86::BI__builtin_ia32_vcomiss:
3347   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3348     ArgNum = 3;
3349     break;
3350   case X86::BI__builtin_ia32_cmppd512_mask:
3351   case X86::BI__builtin_ia32_cmpps512_mask:
3352   case X86::BI__builtin_ia32_cmpsd_mask:
3353   case X86::BI__builtin_ia32_cmpss_mask:
3354   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3355   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3356   case X86::BI__builtin_ia32_getexpss128_round_mask:
3357   case X86::BI__builtin_ia32_getmantpd512_mask:
3358   case X86::BI__builtin_ia32_getmantps512_mask:
3359   case X86::BI__builtin_ia32_maxsd_round_mask:
3360   case X86::BI__builtin_ia32_maxss_round_mask:
3361   case X86::BI__builtin_ia32_minsd_round_mask:
3362   case X86::BI__builtin_ia32_minss_round_mask:
3363   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3364   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3365   case X86::BI__builtin_ia32_reducepd512_mask:
3366   case X86::BI__builtin_ia32_reduceps512_mask:
3367   case X86::BI__builtin_ia32_rndscalepd_mask:
3368   case X86::BI__builtin_ia32_rndscaleps_mask:
3369   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3370   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3371     ArgNum = 4;
3372     break;
3373   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3374   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3375   case X86::BI__builtin_ia32_fixupimmps512_mask:
3376   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3377   case X86::BI__builtin_ia32_fixupimmsd_mask:
3378   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3379   case X86::BI__builtin_ia32_fixupimmss_mask:
3380   case X86::BI__builtin_ia32_fixupimmss_maskz:
3381   case X86::BI__builtin_ia32_getmantsd_round_mask:
3382   case X86::BI__builtin_ia32_getmantss_round_mask:
3383   case X86::BI__builtin_ia32_rangepd512_mask:
3384   case X86::BI__builtin_ia32_rangeps512_mask:
3385   case X86::BI__builtin_ia32_rangesd128_round_mask:
3386   case X86::BI__builtin_ia32_rangess128_round_mask:
3387   case X86::BI__builtin_ia32_reducesd_mask:
3388   case X86::BI__builtin_ia32_reducess_mask:
3389   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3390   case X86::BI__builtin_ia32_rndscaless_round_mask:
3391     ArgNum = 5;
3392     break;
3393   case X86::BI__builtin_ia32_vcvtsd2si64:
3394   case X86::BI__builtin_ia32_vcvtsd2si32:
3395   case X86::BI__builtin_ia32_vcvtsd2usi32:
3396   case X86::BI__builtin_ia32_vcvtsd2usi64:
3397   case X86::BI__builtin_ia32_vcvtss2si32:
3398   case X86::BI__builtin_ia32_vcvtss2si64:
3399   case X86::BI__builtin_ia32_vcvtss2usi32:
3400   case X86::BI__builtin_ia32_vcvtss2usi64:
3401   case X86::BI__builtin_ia32_sqrtpd512:
3402   case X86::BI__builtin_ia32_sqrtps512:
3403     ArgNum = 1;
3404     HasRC = true;
3405     break;
3406   case X86::BI__builtin_ia32_addpd512:
3407   case X86::BI__builtin_ia32_addps512:
3408   case X86::BI__builtin_ia32_divpd512:
3409   case X86::BI__builtin_ia32_divps512:
3410   case X86::BI__builtin_ia32_mulpd512:
3411   case X86::BI__builtin_ia32_mulps512:
3412   case X86::BI__builtin_ia32_subpd512:
3413   case X86::BI__builtin_ia32_subps512:
3414   case X86::BI__builtin_ia32_cvtsi2sd64:
3415   case X86::BI__builtin_ia32_cvtsi2ss32:
3416   case X86::BI__builtin_ia32_cvtsi2ss64:
3417   case X86::BI__builtin_ia32_cvtusi2sd64:
3418   case X86::BI__builtin_ia32_cvtusi2ss32:
3419   case X86::BI__builtin_ia32_cvtusi2ss64:
3420     ArgNum = 2;
3421     HasRC = true;
3422     break;
3423   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3424   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3425   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3426   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3427   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3428   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3429   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3430   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3431   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3432   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3433   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3434   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3435   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3436   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3437   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3438     ArgNum = 3;
3439     HasRC = true;
3440     break;
3441   case X86::BI__builtin_ia32_addss_round_mask:
3442   case X86::BI__builtin_ia32_addsd_round_mask:
3443   case X86::BI__builtin_ia32_divss_round_mask:
3444   case X86::BI__builtin_ia32_divsd_round_mask:
3445   case X86::BI__builtin_ia32_mulss_round_mask:
3446   case X86::BI__builtin_ia32_mulsd_round_mask:
3447   case X86::BI__builtin_ia32_subss_round_mask:
3448   case X86::BI__builtin_ia32_subsd_round_mask:
3449   case X86::BI__builtin_ia32_scalefpd512_mask:
3450   case X86::BI__builtin_ia32_scalefps512_mask:
3451   case X86::BI__builtin_ia32_scalefsd_round_mask:
3452   case X86::BI__builtin_ia32_scalefss_round_mask:
3453   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3454   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3455   case X86::BI__builtin_ia32_sqrtss_round_mask:
3456   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3457   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3458   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3459   case X86::BI__builtin_ia32_vfmaddss3_mask:
3460   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3461   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3462   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3463   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3464   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3465   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3466   case X86::BI__builtin_ia32_vfmaddps512_mask:
3467   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3468   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3469   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3470   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3471   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3472   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3473   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3474   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3475   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3476   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3477   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3478     ArgNum = 4;
3479     HasRC = true;
3480     break;
3481   }
3482 
3483   llvm::APSInt Result;
3484 
3485   // We can't check the value of a dependent argument.
3486   Expr *Arg = TheCall->getArg(ArgNum);
3487   if (Arg->isTypeDependent() || Arg->isValueDependent())
3488     return false;
3489 
3490   // Check constant-ness first.
3491   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3492     return true;
3493 
3494   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3495   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3496   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3497   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3498   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3499       Result == 8/*ROUND_NO_EXC*/ ||
3500       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3501       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3502     return false;
3503 
3504   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3505          << Arg->getSourceRange();
3506 }
3507 
3508 // Check if the gather/scatter scale is legal.
3509 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3510                                              CallExpr *TheCall) {
3511   unsigned ArgNum = 0;
3512   switch (BuiltinID) {
3513   default:
3514     return false;
3515   case X86::BI__builtin_ia32_gatherpfdpd:
3516   case X86::BI__builtin_ia32_gatherpfdps:
3517   case X86::BI__builtin_ia32_gatherpfqpd:
3518   case X86::BI__builtin_ia32_gatherpfqps:
3519   case X86::BI__builtin_ia32_scatterpfdpd:
3520   case X86::BI__builtin_ia32_scatterpfdps:
3521   case X86::BI__builtin_ia32_scatterpfqpd:
3522   case X86::BI__builtin_ia32_scatterpfqps:
3523     ArgNum = 3;
3524     break;
3525   case X86::BI__builtin_ia32_gatherd_pd:
3526   case X86::BI__builtin_ia32_gatherd_pd256:
3527   case X86::BI__builtin_ia32_gatherq_pd:
3528   case X86::BI__builtin_ia32_gatherq_pd256:
3529   case X86::BI__builtin_ia32_gatherd_ps:
3530   case X86::BI__builtin_ia32_gatherd_ps256:
3531   case X86::BI__builtin_ia32_gatherq_ps:
3532   case X86::BI__builtin_ia32_gatherq_ps256:
3533   case X86::BI__builtin_ia32_gatherd_q:
3534   case X86::BI__builtin_ia32_gatherd_q256:
3535   case X86::BI__builtin_ia32_gatherq_q:
3536   case X86::BI__builtin_ia32_gatherq_q256:
3537   case X86::BI__builtin_ia32_gatherd_d:
3538   case X86::BI__builtin_ia32_gatherd_d256:
3539   case X86::BI__builtin_ia32_gatherq_d:
3540   case X86::BI__builtin_ia32_gatherq_d256:
3541   case X86::BI__builtin_ia32_gather3div2df:
3542   case X86::BI__builtin_ia32_gather3div2di:
3543   case X86::BI__builtin_ia32_gather3div4df:
3544   case X86::BI__builtin_ia32_gather3div4di:
3545   case X86::BI__builtin_ia32_gather3div4sf:
3546   case X86::BI__builtin_ia32_gather3div4si:
3547   case X86::BI__builtin_ia32_gather3div8sf:
3548   case X86::BI__builtin_ia32_gather3div8si:
3549   case X86::BI__builtin_ia32_gather3siv2df:
3550   case X86::BI__builtin_ia32_gather3siv2di:
3551   case X86::BI__builtin_ia32_gather3siv4df:
3552   case X86::BI__builtin_ia32_gather3siv4di:
3553   case X86::BI__builtin_ia32_gather3siv4sf:
3554   case X86::BI__builtin_ia32_gather3siv4si:
3555   case X86::BI__builtin_ia32_gather3siv8sf:
3556   case X86::BI__builtin_ia32_gather3siv8si:
3557   case X86::BI__builtin_ia32_gathersiv8df:
3558   case X86::BI__builtin_ia32_gathersiv16sf:
3559   case X86::BI__builtin_ia32_gatherdiv8df:
3560   case X86::BI__builtin_ia32_gatherdiv16sf:
3561   case X86::BI__builtin_ia32_gathersiv8di:
3562   case X86::BI__builtin_ia32_gathersiv16si:
3563   case X86::BI__builtin_ia32_gatherdiv8di:
3564   case X86::BI__builtin_ia32_gatherdiv16si:
3565   case X86::BI__builtin_ia32_scatterdiv2df:
3566   case X86::BI__builtin_ia32_scatterdiv2di:
3567   case X86::BI__builtin_ia32_scatterdiv4df:
3568   case X86::BI__builtin_ia32_scatterdiv4di:
3569   case X86::BI__builtin_ia32_scatterdiv4sf:
3570   case X86::BI__builtin_ia32_scatterdiv4si:
3571   case X86::BI__builtin_ia32_scatterdiv8sf:
3572   case X86::BI__builtin_ia32_scatterdiv8si:
3573   case X86::BI__builtin_ia32_scattersiv2df:
3574   case X86::BI__builtin_ia32_scattersiv2di:
3575   case X86::BI__builtin_ia32_scattersiv4df:
3576   case X86::BI__builtin_ia32_scattersiv4di:
3577   case X86::BI__builtin_ia32_scattersiv4sf:
3578   case X86::BI__builtin_ia32_scattersiv4si:
3579   case X86::BI__builtin_ia32_scattersiv8sf:
3580   case X86::BI__builtin_ia32_scattersiv8si:
3581   case X86::BI__builtin_ia32_scattersiv8df:
3582   case X86::BI__builtin_ia32_scattersiv16sf:
3583   case X86::BI__builtin_ia32_scatterdiv8df:
3584   case X86::BI__builtin_ia32_scatterdiv16sf:
3585   case X86::BI__builtin_ia32_scattersiv8di:
3586   case X86::BI__builtin_ia32_scattersiv16si:
3587   case X86::BI__builtin_ia32_scatterdiv8di:
3588   case X86::BI__builtin_ia32_scatterdiv16si:
3589     ArgNum = 4;
3590     break;
3591   }
3592 
3593   llvm::APSInt Result;
3594 
3595   // We can't check the value of a dependent argument.
3596   Expr *Arg = TheCall->getArg(ArgNum);
3597   if (Arg->isTypeDependent() || Arg->isValueDependent())
3598     return false;
3599 
3600   // Check constant-ness first.
3601   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3602     return true;
3603 
3604   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3605     return false;
3606 
3607   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3608          << Arg->getSourceRange();
3609 }
3610 
3611 enum { TileRegLow = 0, TileRegHigh = 7 };
3612 
3613 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3614                                     ArrayRef<int> ArgNums) {
3615   for (int ArgNum : ArgNums) {
3616     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3617       return true;
3618   }
3619   return false;
3620 }
3621 
3622 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum) {
3623   return SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh);
3624 }
3625 
3626 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3627                                         ArrayRef<int> ArgNums) {
3628   // Because the max number of tile register is TileRegHigh + 1, so here we use
3629   // each bit to represent the usage of them in bitset.
3630   std::bitset<TileRegHigh + 1> ArgValues;
3631   for (int ArgNum : ArgNums) {
3632     llvm::APSInt Arg;
3633     SemaBuiltinConstantArg(TheCall, ArgNum, Arg);
3634     int ArgExtValue = Arg.getExtValue();
3635     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3636            "Incorrect tile register num.");
3637     if (ArgValues.test(ArgExtValue))
3638       return Diag(TheCall->getBeginLoc(),
3639                   diag::err_x86_builtin_tile_arg_duplicate)
3640              << TheCall->getArg(ArgNum)->getSourceRange();
3641     ArgValues.set(ArgExtValue);
3642   }
3643   return false;
3644 }
3645 
3646 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3647                                                 ArrayRef<int> ArgNums) {
3648   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3649          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3650 }
3651 
3652 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3653   switch (BuiltinID) {
3654   default:
3655     return false;
3656   case X86::BI__builtin_ia32_tileloadd64:
3657   case X86::BI__builtin_ia32_tileloaddt164:
3658   case X86::BI__builtin_ia32_tilestored64:
3659   case X86::BI__builtin_ia32_tilezero:
3660     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3661   case X86::BI__builtin_ia32_tdpbssd:
3662   case X86::BI__builtin_ia32_tdpbsud:
3663   case X86::BI__builtin_ia32_tdpbusd:
3664   case X86::BI__builtin_ia32_tdpbuud:
3665   case X86::BI__builtin_ia32_tdpbf16ps:
3666     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3667   }
3668 }
3669 static bool isX86_32Builtin(unsigned BuiltinID) {
3670   // These builtins only work on x86-32 targets.
3671   switch (BuiltinID) {
3672   case X86::BI__builtin_ia32_readeflags_u32:
3673   case X86::BI__builtin_ia32_writeeflags_u32:
3674     return true;
3675   }
3676 
3677   return false;
3678 }
3679 
3680 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3681                                        CallExpr *TheCall) {
3682   if (BuiltinID == X86::BI__builtin_cpu_supports)
3683     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3684 
3685   if (BuiltinID == X86::BI__builtin_cpu_is)
3686     return SemaBuiltinCpuIs(*this, TI, TheCall);
3687 
3688   // Check for 32-bit only builtins on a 64-bit target.
3689   const llvm::Triple &TT = TI.getTriple();
3690   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3691     return Diag(TheCall->getCallee()->getBeginLoc(),
3692                 diag::err_32_bit_builtin_64_bit_tgt);
3693 
3694   // If the intrinsic has rounding or SAE make sure its valid.
3695   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3696     return true;
3697 
3698   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3699   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3700     return true;
3701 
3702   // If the intrinsic has a tile arguments, make sure they are valid.
3703   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3704     return true;
3705 
3706   // For intrinsics which take an immediate value as part of the instruction,
3707   // range check them here.
3708   int i = 0, l = 0, u = 0;
3709   switch (BuiltinID) {
3710   default:
3711     return false;
3712   case X86::BI__builtin_ia32_vec_ext_v2si:
3713   case X86::BI__builtin_ia32_vec_ext_v2di:
3714   case X86::BI__builtin_ia32_vextractf128_pd256:
3715   case X86::BI__builtin_ia32_vextractf128_ps256:
3716   case X86::BI__builtin_ia32_vextractf128_si256:
3717   case X86::BI__builtin_ia32_extract128i256:
3718   case X86::BI__builtin_ia32_extractf64x4_mask:
3719   case X86::BI__builtin_ia32_extracti64x4_mask:
3720   case X86::BI__builtin_ia32_extractf32x8_mask:
3721   case X86::BI__builtin_ia32_extracti32x8_mask:
3722   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3723   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3724   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3725   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3726     i = 1; l = 0; u = 1;
3727     break;
3728   case X86::BI__builtin_ia32_vec_set_v2di:
3729   case X86::BI__builtin_ia32_vinsertf128_pd256:
3730   case X86::BI__builtin_ia32_vinsertf128_ps256:
3731   case X86::BI__builtin_ia32_vinsertf128_si256:
3732   case X86::BI__builtin_ia32_insert128i256:
3733   case X86::BI__builtin_ia32_insertf32x8:
3734   case X86::BI__builtin_ia32_inserti32x8:
3735   case X86::BI__builtin_ia32_insertf64x4:
3736   case X86::BI__builtin_ia32_inserti64x4:
3737   case X86::BI__builtin_ia32_insertf64x2_256:
3738   case X86::BI__builtin_ia32_inserti64x2_256:
3739   case X86::BI__builtin_ia32_insertf32x4_256:
3740   case X86::BI__builtin_ia32_inserti32x4_256:
3741     i = 2; l = 0; u = 1;
3742     break;
3743   case X86::BI__builtin_ia32_vpermilpd:
3744   case X86::BI__builtin_ia32_vec_ext_v4hi:
3745   case X86::BI__builtin_ia32_vec_ext_v4si:
3746   case X86::BI__builtin_ia32_vec_ext_v4sf:
3747   case X86::BI__builtin_ia32_vec_ext_v4di:
3748   case X86::BI__builtin_ia32_extractf32x4_mask:
3749   case X86::BI__builtin_ia32_extracti32x4_mask:
3750   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3751   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3752     i = 1; l = 0; u = 3;
3753     break;
3754   case X86::BI_mm_prefetch:
3755   case X86::BI__builtin_ia32_vec_ext_v8hi:
3756   case X86::BI__builtin_ia32_vec_ext_v8si:
3757     i = 1; l = 0; u = 7;
3758     break;
3759   case X86::BI__builtin_ia32_sha1rnds4:
3760   case X86::BI__builtin_ia32_blendpd:
3761   case X86::BI__builtin_ia32_shufpd:
3762   case X86::BI__builtin_ia32_vec_set_v4hi:
3763   case X86::BI__builtin_ia32_vec_set_v4si:
3764   case X86::BI__builtin_ia32_vec_set_v4di:
3765   case X86::BI__builtin_ia32_shuf_f32x4_256:
3766   case X86::BI__builtin_ia32_shuf_f64x2_256:
3767   case X86::BI__builtin_ia32_shuf_i32x4_256:
3768   case X86::BI__builtin_ia32_shuf_i64x2_256:
3769   case X86::BI__builtin_ia32_insertf64x2_512:
3770   case X86::BI__builtin_ia32_inserti64x2_512:
3771   case X86::BI__builtin_ia32_insertf32x4:
3772   case X86::BI__builtin_ia32_inserti32x4:
3773     i = 2; l = 0; u = 3;
3774     break;
3775   case X86::BI__builtin_ia32_vpermil2pd:
3776   case X86::BI__builtin_ia32_vpermil2pd256:
3777   case X86::BI__builtin_ia32_vpermil2ps:
3778   case X86::BI__builtin_ia32_vpermil2ps256:
3779     i = 3; l = 0; u = 3;
3780     break;
3781   case X86::BI__builtin_ia32_cmpb128_mask:
3782   case X86::BI__builtin_ia32_cmpw128_mask:
3783   case X86::BI__builtin_ia32_cmpd128_mask:
3784   case X86::BI__builtin_ia32_cmpq128_mask:
3785   case X86::BI__builtin_ia32_cmpb256_mask:
3786   case X86::BI__builtin_ia32_cmpw256_mask:
3787   case X86::BI__builtin_ia32_cmpd256_mask:
3788   case X86::BI__builtin_ia32_cmpq256_mask:
3789   case X86::BI__builtin_ia32_cmpb512_mask:
3790   case X86::BI__builtin_ia32_cmpw512_mask:
3791   case X86::BI__builtin_ia32_cmpd512_mask:
3792   case X86::BI__builtin_ia32_cmpq512_mask:
3793   case X86::BI__builtin_ia32_ucmpb128_mask:
3794   case X86::BI__builtin_ia32_ucmpw128_mask:
3795   case X86::BI__builtin_ia32_ucmpd128_mask:
3796   case X86::BI__builtin_ia32_ucmpq128_mask:
3797   case X86::BI__builtin_ia32_ucmpb256_mask:
3798   case X86::BI__builtin_ia32_ucmpw256_mask:
3799   case X86::BI__builtin_ia32_ucmpd256_mask:
3800   case X86::BI__builtin_ia32_ucmpq256_mask:
3801   case X86::BI__builtin_ia32_ucmpb512_mask:
3802   case X86::BI__builtin_ia32_ucmpw512_mask:
3803   case X86::BI__builtin_ia32_ucmpd512_mask:
3804   case X86::BI__builtin_ia32_ucmpq512_mask:
3805   case X86::BI__builtin_ia32_vpcomub:
3806   case X86::BI__builtin_ia32_vpcomuw:
3807   case X86::BI__builtin_ia32_vpcomud:
3808   case X86::BI__builtin_ia32_vpcomuq:
3809   case X86::BI__builtin_ia32_vpcomb:
3810   case X86::BI__builtin_ia32_vpcomw:
3811   case X86::BI__builtin_ia32_vpcomd:
3812   case X86::BI__builtin_ia32_vpcomq:
3813   case X86::BI__builtin_ia32_vec_set_v8hi:
3814   case X86::BI__builtin_ia32_vec_set_v8si:
3815     i = 2; l = 0; u = 7;
3816     break;
3817   case X86::BI__builtin_ia32_vpermilpd256:
3818   case X86::BI__builtin_ia32_roundps:
3819   case X86::BI__builtin_ia32_roundpd:
3820   case X86::BI__builtin_ia32_roundps256:
3821   case X86::BI__builtin_ia32_roundpd256:
3822   case X86::BI__builtin_ia32_getmantpd128_mask:
3823   case X86::BI__builtin_ia32_getmantpd256_mask:
3824   case X86::BI__builtin_ia32_getmantps128_mask:
3825   case X86::BI__builtin_ia32_getmantps256_mask:
3826   case X86::BI__builtin_ia32_getmantpd512_mask:
3827   case X86::BI__builtin_ia32_getmantps512_mask:
3828   case X86::BI__builtin_ia32_vec_ext_v16qi:
3829   case X86::BI__builtin_ia32_vec_ext_v16hi:
3830     i = 1; l = 0; u = 15;
3831     break;
3832   case X86::BI__builtin_ia32_pblendd128:
3833   case X86::BI__builtin_ia32_blendps:
3834   case X86::BI__builtin_ia32_blendpd256:
3835   case X86::BI__builtin_ia32_shufpd256:
3836   case X86::BI__builtin_ia32_roundss:
3837   case X86::BI__builtin_ia32_roundsd:
3838   case X86::BI__builtin_ia32_rangepd128_mask:
3839   case X86::BI__builtin_ia32_rangepd256_mask:
3840   case X86::BI__builtin_ia32_rangepd512_mask:
3841   case X86::BI__builtin_ia32_rangeps128_mask:
3842   case X86::BI__builtin_ia32_rangeps256_mask:
3843   case X86::BI__builtin_ia32_rangeps512_mask:
3844   case X86::BI__builtin_ia32_getmantsd_round_mask:
3845   case X86::BI__builtin_ia32_getmantss_round_mask:
3846   case X86::BI__builtin_ia32_vec_set_v16qi:
3847   case X86::BI__builtin_ia32_vec_set_v16hi:
3848     i = 2; l = 0; u = 15;
3849     break;
3850   case X86::BI__builtin_ia32_vec_ext_v32qi:
3851     i = 1; l = 0; u = 31;
3852     break;
3853   case X86::BI__builtin_ia32_cmpps:
3854   case X86::BI__builtin_ia32_cmpss:
3855   case X86::BI__builtin_ia32_cmppd:
3856   case X86::BI__builtin_ia32_cmpsd:
3857   case X86::BI__builtin_ia32_cmpps256:
3858   case X86::BI__builtin_ia32_cmppd256:
3859   case X86::BI__builtin_ia32_cmpps128_mask:
3860   case X86::BI__builtin_ia32_cmppd128_mask:
3861   case X86::BI__builtin_ia32_cmpps256_mask:
3862   case X86::BI__builtin_ia32_cmppd256_mask:
3863   case X86::BI__builtin_ia32_cmpps512_mask:
3864   case X86::BI__builtin_ia32_cmppd512_mask:
3865   case X86::BI__builtin_ia32_cmpsd_mask:
3866   case X86::BI__builtin_ia32_cmpss_mask:
3867   case X86::BI__builtin_ia32_vec_set_v32qi:
3868     i = 2; l = 0; u = 31;
3869     break;
3870   case X86::BI__builtin_ia32_permdf256:
3871   case X86::BI__builtin_ia32_permdi256:
3872   case X86::BI__builtin_ia32_permdf512:
3873   case X86::BI__builtin_ia32_permdi512:
3874   case X86::BI__builtin_ia32_vpermilps:
3875   case X86::BI__builtin_ia32_vpermilps256:
3876   case X86::BI__builtin_ia32_vpermilpd512:
3877   case X86::BI__builtin_ia32_vpermilps512:
3878   case X86::BI__builtin_ia32_pshufd:
3879   case X86::BI__builtin_ia32_pshufd256:
3880   case X86::BI__builtin_ia32_pshufd512:
3881   case X86::BI__builtin_ia32_pshufhw:
3882   case X86::BI__builtin_ia32_pshufhw256:
3883   case X86::BI__builtin_ia32_pshufhw512:
3884   case X86::BI__builtin_ia32_pshuflw:
3885   case X86::BI__builtin_ia32_pshuflw256:
3886   case X86::BI__builtin_ia32_pshuflw512:
3887   case X86::BI__builtin_ia32_vcvtps2ph:
3888   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3889   case X86::BI__builtin_ia32_vcvtps2ph256:
3890   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3891   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3892   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3893   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3894   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3895   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3896   case X86::BI__builtin_ia32_rndscaleps_mask:
3897   case X86::BI__builtin_ia32_rndscalepd_mask:
3898   case X86::BI__builtin_ia32_reducepd128_mask:
3899   case X86::BI__builtin_ia32_reducepd256_mask:
3900   case X86::BI__builtin_ia32_reducepd512_mask:
3901   case X86::BI__builtin_ia32_reduceps128_mask:
3902   case X86::BI__builtin_ia32_reduceps256_mask:
3903   case X86::BI__builtin_ia32_reduceps512_mask:
3904   case X86::BI__builtin_ia32_prold512:
3905   case X86::BI__builtin_ia32_prolq512:
3906   case X86::BI__builtin_ia32_prold128:
3907   case X86::BI__builtin_ia32_prold256:
3908   case X86::BI__builtin_ia32_prolq128:
3909   case X86::BI__builtin_ia32_prolq256:
3910   case X86::BI__builtin_ia32_prord512:
3911   case X86::BI__builtin_ia32_prorq512:
3912   case X86::BI__builtin_ia32_prord128:
3913   case X86::BI__builtin_ia32_prord256:
3914   case X86::BI__builtin_ia32_prorq128:
3915   case X86::BI__builtin_ia32_prorq256:
3916   case X86::BI__builtin_ia32_fpclasspd128_mask:
3917   case X86::BI__builtin_ia32_fpclasspd256_mask:
3918   case X86::BI__builtin_ia32_fpclassps128_mask:
3919   case X86::BI__builtin_ia32_fpclassps256_mask:
3920   case X86::BI__builtin_ia32_fpclassps512_mask:
3921   case X86::BI__builtin_ia32_fpclasspd512_mask:
3922   case X86::BI__builtin_ia32_fpclasssd_mask:
3923   case X86::BI__builtin_ia32_fpclassss_mask:
3924   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3925   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3926   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3927   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3928   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3929   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3930   case X86::BI__builtin_ia32_kshiftliqi:
3931   case X86::BI__builtin_ia32_kshiftlihi:
3932   case X86::BI__builtin_ia32_kshiftlisi:
3933   case X86::BI__builtin_ia32_kshiftlidi:
3934   case X86::BI__builtin_ia32_kshiftriqi:
3935   case X86::BI__builtin_ia32_kshiftrihi:
3936   case X86::BI__builtin_ia32_kshiftrisi:
3937   case X86::BI__builtin_ia32_kshiftridi:
3938     i = 1; l = 0; u = 255;
3939     break;
3940   case X86::BI__builtin_ia32_vperm2f128_pd256:
3941   case X86::BI__builtin_ia32_vperm2f128_ps256:
3942   case X86::BI__builtin_ia32_vperm2f128_si256:
3943   case X86::BI__builtin_ia32_permti256:
3944   case X86::BI__builtin_ia32_pblendw128:
3945   case X86::BI__builtin_ia32_pblendw256:
3946   case X86::BI__builtin_ia32_blendps256:
3947   case X86::BI__builtin_ia32_pblendd256:
3948   case X86::BI__builtin_ia32_palignr128:
3949   case X86::BI__builtin_ia32_palignr256:
3950   case X86::BI__builtin_ia32_palignr512:
3951   case X86::BI__builtin_ia32_alignq512:
3952   case X86::BI__builtin_ia32_alignd512:
3953   case X86::BI__builtin_ia32_alignd128:
3954   case X86::BI__builtin_ia32_alignd256:
3955   case X86::BI__builtin_ia32_alignq128:
3956   case X86::BI__builtin_ia32_alignq256:
3957   case X86::BI__builtin_ia32_vcomisd:
3958   case X86::BI__builtin_ia32_vcomiss:
3959   case X86::BI__builtin_ia32_shuf_f32x4:
3960   case X86::BI__builtin_ia32_shuf_f64x2:
3961   case X86::BI__builtin_ia32_shuf_i32x4:
3962   case X86::BI__builtin_ia32_shuf_i64x2:
3963   case X86::BI__builtin_ia32_shufpd512:
3964   case X86::BI__builtin_ia32_shufps:
3965   case X86::BI__builtin_ia32_shufps256:
3966   case X86::BI__builtin_ia32_shufps512:
3967   case X86::BI__builtin_ia32_dbpsadbw128:
3968   case X86::BI__builtin_ia32_dbpsadbw256:
3969   case X86::BI__builtin_ia32_dbpsadbw512:
3970   case X86::BI__builtin_ia32_vpshldd128:
3971   case X86::BI__builtin_ia32_vpshldd256:
3972   case X86::BI__builtin_ia32_vpshldd512:
3973   case X86::BI__builtin_ia32_vpshldq128:
3974   case X86::BI__builtin_ia32_vpshldq256:
3975   case X86::BI__builtin_ia32_vpshldq512:
3976   case X86::BI__builtin_ia32_vpshldw128:
3977   case X86::BI__builtin_ia32_vpshldw256:
3978   case X86::BI__builtin_ia32_vpshldw512:
3979   case X86::BI__builtin_ia32_vpshrdd128:
3980   case X86::BI__builtin_ia32_vpshrdd256:
3981   case X86::BI__builtin_ia32_vpshrdd512:
3982   case X86::BI__builtin_ia32_vpshrdq128:
3983   case X86::BI__builtin_ia32_vpshrdq256:
3984   case X86::BI__builtin_ia32_vpshrdq512:
3985   case X86::BI__builtin_ia32_vpshrdw128:
3986   case X86::BI__builtin_ia32_vpshrdw256:
3987   case X86::BI__builtin_ia32_vpshrdw512:
3988     i = 2; l = 0; u = 255;
3989     break;
3990   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3991   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3992   case X86::BI__builtin_ia32_fixupimmps512_mask:
3993   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3994   case X86::BI__builtin_ia32_fixupimmsd_mask:
3995   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3996   case X86::BI__builtin_ia32_fixupimmss_mask:
3997   case X86::BI__builtin_ia32_fixupimmss_maskz:
3998   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3999   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4000   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4001   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4002   case X86::BI__builtin_ia32_fixupimmps128_mask:
4003   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4004   case X86::BI__builtin_ia32_fixupimmps256_mask:
4005   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4006   case X86::BI__builtin_ia32_pternlogd512_mask:
4007   case X86::BI__builtin_ia32_pternlogd512_maskz:
4008   case X86::BI__builtin_ia32_pternlogq512_mask:
4009   case X86::BI__builtin_ia32_pternlogq512_maskz:
4010   case X86::BI__builtin_ia32_pternlogd128_mask:
4011   case X86::BI__builtin_ia32_pternlogd128_maskz:
4012   case X86::BI__builtin_ia32_pternlogd256_mask:
4013   case X86::BI__builtin_ia32_pternlogd256_maskz:
4014   case X86::BI__builtin_ia32_pternlogq128_mask:
4015   case X86::BI__builtin_ia32_pternlogq128_maskz:
4016   case X86::BI__builtin_ia32_pternlogq256_mask:
4017   case X86::BI__builtin_ia32_pternlogq256_maskz:
4018     i = 3; l = 0; u = 255;
4019     break;
4020   case X86::BI__builtin_ia32_gatherpfdpd:
4021   case X86::BI__builtin_ia32_gatherpfdps:
4022   case X86::BI__builtin_ia32_gatherpfqpd:
4023   case X86::BI__builtin_ia32_gatherpfqps:
4024   case X86::BI__builtin_ia32_scatterpfdpd:
4025   case X86::BI__builtin_ia32_scatterpfdps:
4026   case X86::BI__builtin_ia32_scatterpfqpd:
4027   case X86::BI__builtin_ia32_scatterpfqps:
4028     i = 4; l = 2; u = 3;
4029     break;
4030   case X86::BI__builtin_ia32_reducesd_mask:
4031   case X86::BI__builtin_ia32_reducess_mask:
4032   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4033   case X86::BI__builtin_ia32_rndscaless_round_mask:
4034     i = 4; l = 0; u = 255;
4035     break;
4036   }
4037 
4038   // Note that we don't force a hard error on the range check here, allowing
4039   // template-generated or macro-generated dead code to potentially have out-of-
4040   // range values. These need to code generate, but don't need to necessarily
4041   // make any sense. We use a warning that defaults to an error.
4042   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4043 }
4044 
4045 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4046 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4047 /// Returns true when the format fits the function and the FormatStringInfo has
4048 /// been populated.
4049 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4050                                FormatStringInfo *FSI) {
4051   FSI->HasVAListArg = Format->getFirstArg() == 0;
4052   FSI->FormatIdx = Format->getFormatIdx() - 1;
4053   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4054 
4055   // The way the format attribute works in GCC, the implicit this argument
4056   // of member functions is counted. However, it doesn't appear in our own
4057   // lists, so decrement format_idx in that case.
4058   if (IsCXXMember) {
4059     if(FSI->FormatIdx == 0)
4060       return false;
4061     --FSI->FormatIdx;
4062     if (FSI->FirstDataArg != 0)
4063       --FSI->FirstDataArg;
4064   }
4065   return true;
4066 }
4067 
4068 /// Checks if a the given expression evaluates to null.
4069 ///
4070 /// Returns true if the value evaluates to null.
4071 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4072   // If the expression has non-null type, it doesn't evaluate to null.
4073   if (auto nullability
4074         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4075     if (*nullability == NullabilityKind::NonNull)
4076       return false;
4077   }
4078 
4079   // As a special case, transparent unions initialized with zero are
4080   // considered null for the purposes of the nonnull attribute.
4081   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4082     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4083       if (const CompoundLiteralExpr *CLE =
4084           dyn_cast<CompoundLiteralExpr>(Expr))
4085         if (const InitListExpr *ILE =
4086             dyn_cast<InitListExpr>(CLE->getInitializer()))
4087           Expr = ILE->getInit(0);
4088   }
4089 
4090   bool Result;
4091   return (!Expr->isValueDependent() &&
4092           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4093           !Result);
4094 }
4095 
4096 static void CheckNonNullArgument(Sema &S,
4097                                  const Expr *ArgExpr,
4098                                  SourceLocation CallSiteLoc) {
4099   if (CheckNonNullExpr(S, ArgExpr))
4100     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4101                           S.PDiag(diag::warn_null_arg)
4102                               << ArgExpr->getSourceRange());
4103 }
4104 
4105 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4106   FormatStringInfo FSI;
4107   if ((GetFormatStringType(Format) == FST_NSString) &&
4108       getFormatStringInfo(Format, false, &FSI)) {
4109     Idx = FSI.FormatIdx;
4110     return true;
4111   }
4112   return false;
4113 }
4114 
4115 /// Diagnose use of %s directive in an NSString which is being passed
4116 /// as formatting string to formatting method.
4117 static void
4118 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4119                                         const NamedDecl *FDecl,
4120                                         Expr **Args,
4121                                         unsigned NumArgs) {
4122   unsigned Idx = 0;
4123   bool Format = false;
4124   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4125   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4126     Idx = 2;
4127     Format = true;
4128   }
4129   else
4130     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4131       if (S.GetFormatNSStringIdx(I, Idx)) {
4132         Format = true;
4133         break;
4134       }
4135     }
4136   if (!Format || NumArgs <= Idx)
4137     return;
4138   const Expr *FormatExpr = Args[Idx];
4139   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4140     FormatExpr = CSCE->getSubExpr();
4141   const StringLiteral *FormatString;
4142   if (const ObjCStringLiteral *OSL =
4143       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4144     FormatString = OSL->getString();
4145   else
4146     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4147   if (!FormatString)
4148     return;
4149   if (S.FormatStringHasSArg(FormatString)) {
4150     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4151       << "%s" << 1 << 1;
4152     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4153       << FDecl->getDeclName();
4154   }
4155 }
4156 
4157 /// Determine whether the given type has a non-null nullability annotation.
4158 static bool isNonNullType(ASTContext &ctx, QualType type) {
4159   if (auto nullability = type->getNullability(ctx))
4160     return *nullability == NullabilityKind::NonNull;
4161 
4162   return false;
4163 }
4164 
4165 static void CheckNonNullArguments(Sema &S,
4166                                   const NamedDecl *FDecl,
4167                                   const FunctionProtoType *Proto,
4168                                   ArrayRef<const Expr *> Args,
4169                                   SourceLocation CallSiteLoc) {
4170   assert((FDecl || Proto) && "Need a function declaration or prototype");
4171 
4172   // Already checked by by constant evaluator.
4173   if (S.isConstantEvaluated())
4174     return;
4175   // Check the attributes attached to the method/function itself.
4176   llvm::SmallBitVector NonNullArgs;
4177   if (FDecl) {
4178     // Handle the nonnull attribute on the function/method declaration itself.
4179     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4180       if (!NonNull->args_size()) {
4181         // Easy case: all pointer arguments are nonnull.
4182         for (const auto *Arg : Args)
4183           if (S.isValidPointerAttrType(Arg->getType()))
4184             CheckNonNullArgument(S, Arg, CallSiteLoc);
4185         return;
4186       }
4187 
4188       for (const ParamIdx &Idx : NonNull->args()) {
4189         unsigned IdxAST = Idx.getASTIndex();
4190         if (IdxAST >= Args.size())
4191           continue;
4192         if (NonNullArgs.empty())
4193           NonNullArgs.resize(Args.size());
4194         NonNullArgs.set(IdxAST);
4195       }
4196     }
4197   }
4198 
4199   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4200     // Handle the nonnull attribute on the parameters of the
4201     // function/method.
4202     ArrayRef<ParmVarDecl*> parms;
4203     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4204       parms = FD->parameters();
4205     else
4206       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4207 
4208     unsigned ParamIndex = 0;
4209     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4210          I != E; ++I, ++ParamIndex) {
4211       const ParmVarDecl *PVD = *I;
4212       if (PVD->hasAttr<NonNullAttr>() ||
4213           isNonNullType(S.Context, PVD->getType())) {
4214         if (NonNullArgs.empty())
4215           NonNullArgs.resize(Args.size());
4216 
4217         NonNullArgs.set(ParamIndex);
4218       }
4219     }
4220   } else {
4221     // If we have a non-function, non-method declaration but no
4222     // function prototype, try to dig out the function prototype.
4223     if (!Proto) {
4224       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4225         QualType type = VD->getType().getNonReferenceType();
4226         if (auto pointerType = type->getAs<PointerType>())
4227           type = pointerType->getPointeeType();
4228         else if (auto blockType = type->getAs<BlockPointerType>())
4229           type = blockType->getPointeeType();
4230         // FIXME: data member pointers?
4231 
4232         // Dig out the function prototype, if there is one.
4233         Proto = type->getAs<FunctionProtoType>();
4234       }
4235     }
4236 
4237     // Fill in non-null argument information from the nullability
4238     // information on the parameter types (if we have them).
4239     if (Proto) {
4240       unsigned Index = 0;
4241       for (auto paramType : Proto->getParamTypes()) {
4242         if (isNonNullType(S.Context, paramType)) {
4243           if (NonNullArgs.empty())
4244             NonNullArgs.resize(Args.size());
4245 
4246           NonNullArgs.set(Index);
4247         }
4248 
4249         ++Index;
4250       }
4251     }
4252   }
4253 
4254   // Check for non-null arguments.
4255   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4256        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4257     if (NonNullArgs[ArgIndex])
4258       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4259   }
4260 }
4261 
4262 /// Handles the checks for format strings, non-POD arguments to vararg
4263 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4264 /// attributes.
4265 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4266                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4267                      bool IsMemberFunction, SourceLocation Loc,
4268                      SourceRange Range, VariadicCallType CallType) {
4269   // FIXME: We should check as much as we can in the template definition.
4270   if (CurContext->isDependentContext())
4271     return;
4272 
4273   // Printf and scanf checking.
4274   llvm::SmallBitVector CheckedVarArgs;
4275   if (FDecl) {
4276     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4277       // Only create vector if there are format attributes.
4278       CheckedVarArgs.resize(Args.size());
4279 
4280       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4281                            CheckedVarArgs);
4282     }
4283   }
4284 
4285   // Refuse POD arguments that weren't caught by the format string
4286   // checks above.
4287   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4288   if (CallType != VariadicDoesNotApply &&
4289       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4290     unsigned NumParams = Proto ? Proto->getNumParams()
4291                        : FDecl && isa<FunctionDecl>(FDecl)
4292                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4293                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4294                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4295                        : 0;
4296 
4297     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4298       // Args[ArgIdx] can be null in malformed code.
4299       if (const Expr *Arg = Args[ArgIdx]) {
4300         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4301           checkVariadicArgument(Arg, CallType);
4302       }
4303     }
4304   }
4305 
4306   if (FDecl || Proto) {
4307     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4308 
4309     // Type safety checking.
4310     if (FDecl) {
4311       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4312         CheckArgumentWithTypeTag(I, Args, Loc);
4313     }
4314   }
4315 
4316   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4317     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4318     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4319     if (!Arg->isValueDependent()) {
4320       Expr::EvalResult Align;
4321       if (Arg->EvaluateAsInt(Align, Context)) {
4322         const llvm::APSInt &I = Align.Val.getInt();
4323         if (!I.isPowerOf2())
4324           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4325               << Arg->getSourceRange();
4326 
4327         if (I > Sema::MaximumAlignment)
4328           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4329               << Arg->getSourceRange() << Sema::MaximumAlignment;
4330       }
4331     }
4332   }
4333 
4334   if (FD)
4335     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4336 }
4337 
4338 /// CheckConstructorCall - Check a constructor call for correctness and safety
4339 /// properties not enforced by the C type system.
4340 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4341                                 ArrayRef<const Expr *> Args,
4342                                 const FunctionProtoType *Proto,
4343                                 SourceLocation Loc) {
4344   VariadicCallType CallType =
4345     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4346   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4347             Loc, SourceRange(), CallType);
4348 }
4349 
4350 /// CheckFunctionCall - Check a direct function call for various correctness
4351 /// and safety properties not strictly enforced by the C type system.
4352 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4353                              const FunctionProtoType *Proto) {
4354   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4355                               isa<CXXMethodDecl>(FDecl);
4356   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4357                           IsMemberOperatorCall;
4358   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4359                                                   TheCall->getCallee());
4360   Expr** Args = TheCall->getArgs();
4361   unsigned NumArgs = TheCall->getNumArgs();
4362 
4363   Expr *ImplicitThis = nullptr;
4364   if (IsMemberOperatorCall) {
4365     // If this is a call to a member operator, hide the first argument
4366     // from checkCall.
4367     // FIXME: Our choice of AST representation here is less than ideal.
4368     ImplicitThis = Args[0];
4369     ++Args;
4370     --NumArgs;
4371   } else if (IsMemberFunction)
4372     ImplicitThis =
4373         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4374 
4375   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4376             IsMemberFunction, TheCall->getRParenLoc(),
4377             TheCall->getCallee()->getSourceRange(), CallType);
4378 
4379   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4380   // None of the checks below are needed for functions that don't have
4381   // simple names (e.g., C++ conversion functions).
4382   if (!FnInfo)
4383     return false;
4384 
4385   CheckAbsoluteValueFunction(TheCall, FDecl);
4386   CheckMaxUnsignedZero(TheCall, FDecl);
4387 
4388   if (getLangOpts().ObjC)
4389     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4390 
4391   unsigned CMId = FDecl->getMemoryFunctionKind();
4392   if (CMId == 0)
4393     return false;
4394 
4395   // Handle memory setting and copying functions.
4396   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4397     CheckStrlcpycatArguments(TheCall, FnInfo);
4398   else if (CMId == Builtin::BIstrncat)
4399     CheckStrncatArguments(TheCall, FnInfo);
4400   else
4401     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4402 
4403   return false;
4404 }
4405 
4406 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4407                                ArrayRef<const Expr *> Args) {
4408   VariadicCallType CallType =
4409       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4410 
4411   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4412             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4413             CallType);
4414 
4415   return false;
4416 }
4417 
4418 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4419                             const FunctionProtoType *Proto) {
4420   QualType Ty;
4421   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4422     Ty = V->getType().getNonReferenceType();
4423   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4424     Ty = F->getType().getNonReferenceType();
4425   else
4426     return false;
4427 
4428   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4429       !Ty->isFunctionProtoType())
4430     return false;
4431 
4432   VariadicCallType CallType;
4433   if (!Proto || !Proto->isVariadic()) {
4434     CallType = VariadicDoesNotApply;
4435   } else if (Ty->isBlockPointerType()) {
4436     CallType = VariadicBlock;
4437   } else { // Ty->isFunctionPointerType()
4438     CallType = VariadicFunction;
4439   }
4440 
4441   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4442             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4443             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4444             TheCall->getCallee()->getSourceRange(), CallType);
4445 
4446   return false;
4447 }
4448 
4449 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4450 /// such as function pointers returned from functions.
4451 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4452   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4453                                                   TheCall->getCallee());
4454   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4455             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4456             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4457             TheCall->getCallee()->getSourceRange(), CallType);
4458 
4459   return false;
4460 }
4461 
4462 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4463   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4464     return false;
4465 
4466   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4467   switch (Op) {
4468   case AtomicExpr::AO__c11_atomic_init:
4469   case AtomicExpr::AO__opencl_atomic_init:
4470     llvm_unreachable("There is no ordering argument for an init");
4471 
4472   case AtomicExpr::AO__c11_atomic_load:
4473   case AtomicExpr::AO__opencl_atomic_load:
4474   case AtomicExpr::AO__atomic_load_n:
4475   case AtomicExpr::AO__atomic_load:
4476     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4477            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4478 
4479   case AtomicExpr::AO__c11_atomic_store:
4480   case AtomicExpr::AO__opencl_atomic_store:
4481   case AtomicExpr::AO__atomic_store:
4482   case AtomicExpr::AO__atomic_store_n:
4483     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4484            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4485            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4486 
4487   default:
4488     return true;
4489   }
4490 }
4491 
4492 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4493                                          AtomicExpr::AtomicOp Op) {
4494   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4495   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4496   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4497   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4498                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4499                          Op);
4500 }
4501 
4502 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4503                                  SourceLocation RParenLoc, MultiExprArg Args,
4504                                  AtomicExpr::AtomicOp Op,
4505                                  AtomicArgumentOrder ArgOrder) {
4506   // All the non-OpenCL operations take one of the following forms.
4507   // The OpenCL operations take the __c11 forms with one extra argument for
4508   // synchronization scope.
4509   enum {
4510     // C    __c11_atomic_init(A *, C)
4511     Init,
4512 
4513     // C    __c11_atomic_load(A *, int)
4514     Load,
4515 
4516     // void __atomic_load(A *, CP, int)
4517     LoadCopy,
4518 
4519     // void __atomic_store(A *, CP, int)
4520     Copy,
4521 
4522     // C    __c11_atomic_add(A *, M, int)
4523     Arithmetic,
4524 
4525     // C    __atomic_exchange_n(A *, CP, int)
4526     Xchg,
4527 
4528     // void __atomic_exchange(A *, C *, CP, int)
4529     GNUXchg,
4530 
4531     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4532     C11CmpXchg,
4533 
4534     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4535     GNUCmpXchg
4536   } Form = Init;
4537 
4538   const unsigned NumForm = GNUCmpXchg + 1;
4539   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4540   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4541   // where:
4542   //   C is an appropriate type,
4543   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4544   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4545   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4546   //   the int parameters are for orderings.
4547 
4548   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4549       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4550       "need to update code for modified forms");
4551   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4552                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4553                         AtomicExpr::AO__atomic_load,
4554                 "need to update code for modified C11 atomics");
4555   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4556                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4557   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4558                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4559                IsOpenCL;
4560   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4561              Op == AtomicExpr::AO__atomic_store_n ||
4562              Op == AtomicExpr::AO__atomic_exchange_n ||
4563              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4564   bool IsAddSub = false;
4565 
4566   switch (Op) {
4567   case AtomicExpr::AO__c11_atomic_init:
4568   case AtomicExpr::AO__opencl_atomic_init:
4569     Form = Init;
4570     break;
4571 
4572   case AtomicExpr::AO__c11_atomic_load:
4573   case AtomicExpr::AO__opencl_atomic_load:
4574   case AtomicExpr::AO__atomic_load_n:
4575     Form = Load;
4576     break;
4577 
4578   case AtomicExpr::AO__atomic_load:
4579     Form = LoadCopy;
4580     break;
4581 
4582   case AtomicExpr::AO__c11_atomic_store:
4583   case AtomicExpr::AO__opencl_atomic_store:
4584   case AtomicExpr::AO__atomic_store:
4585   case AtomicExpr::AO__atomic_store_n:
4586     Form = Copy;
4587     break;
4588 
4589   case AtomicExpr::AO__c11_atomic_fetch_add:
4590   case AtomicExpr::AO__c11_atomic_fetch_sub:
4591   case AtomicExpr::AO__opencl_atomic_fetch_add:
4592   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4593   case AtomicExpr::AO__atomic_fetch_add:
4594   case AtomicExpr::AO__atomic_fetch_sub:
4595   case AtomicExpr::AO__atomic_add_fetch:
4596   case AtomicExpr::AO__atomic_sub_fetch:
4597     IsAddSub = true;
4598     LLVM_FALLTHROUGH;
4599   case AtomicExpr::AO__c11_atomic_fetch_and:
4600   case AtomicExpr::AO__c11_atomic_fetch_or:
4601   case AtomicExpr::AO__c11_atomic_fetch_xor:
4602   case AtomicExpr::AO__opencl_atomic_fetch_and:
4603   case AtomicExpr::AO__opencl_atomic_fetch_or:
4604   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4605   case AtomicExpr::AO__atomic_fetch_and:
4606   case AtomicExpr::AO__atomic_fetch_or:
4607   case AtomicExpr::AO__atomic_fetch_xor:
4608   case AtomicExpr::AO__atomic_fetch_nand:
4609   case AtomicExpr::AO__atomic_and_fetch:
4610   case AtomicExpr::AO__atomic_or_fetch:
4611   case AtomicExpr::AO__atomic_xor_fetch:
4612   case AtomicExpr::AO__atomic_nand_fetch:
4613   case AtomicExpr::AO__c11_atomic_fetch_min:
4614   case AtomicExpr::AO__c11_atomic_fetch_max:
4615   case AtomicExpr::AO__opencl_atomic_fetch_min:
4616   case AtomicExpr::AO__opencl_atomic_fetch_max:
4617   case AtomicExpr::AO__atomic_min_fetch:
4618   case AtomicExpr::AO__atomic_max_fetch:
4619   case AtomicExpr::AO__atomic_fetch_min:
4620   case AtomicExpr::AO__atomic_fetch_max:
4621     Form = Arithmetic;
4622     break;
4623 
4624   case AtomicExpr::AO__c11_atomic_exchange:
4625   case AtomicExpr::AO__opencl_atomic_exchange:
4626   case AtomicExpr::AO__atomic_exchange_n:
4627     Form = Xchg;
4628     break;
4629 
4630   case AtomicExpr::AO__atomic_exchange:
4631     Form = GNUXchg;
4632     break;
4633 
4634   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4635   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4636   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4637   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4638     Form = C11CmpXchg;
4639     break;
4640 
4641   case AtomicExpr::AO__atomic_compare_exchange:
4642   case AtomicExpr::AO__atomic_compare_exchange_n:
4643     Form = GNUCmpXchg;
4644     break;
4645   }
4646 
4647   unsigned AdjustedNumArgs = NumArgs[Form];
4648   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4649     ++AdjustedNumArgs;
4650   // Check we have the right number of arguments.
4651   if (Args.size() < AdjustedNumArgs) {
4652     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4653         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4654         << ExprRange;
4655     return ExprError();
4656   } else if (Args.size() > AdjustedNumArgs) {
4657     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4658          diag::err_typecheck_call_too_many_args)
4659         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4660         << ExprRange;
4661     return ExprError();
4662   }
4663 
4664   // Inspect the first argument of the atomic operation.
4665   Expr *Ptr = Args[0];
4666   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4667   if (ConvertedPtr.isInvalid())
4668     return ExprError();
4669 
4670   Ptr = ConvertedPtr.get();
4671   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4672   if (!pointerType) {
4673     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4674         << Ptr->getType() << Ptr->getSourceRange();
4675     return ExprError();
4676   }
4677 
4678   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4679   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4680   QualType ValType = AtomTy; // 'C'
4681   if (IsC11) {
4682     if (!AtomTy->isAtomicType()) {
4683       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4684           << Ptr->getType() << Ptr->getSourceRange();
4685       return ExprError();
4686     }
4687     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4688         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4689       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4690           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4691           << Ptr->getSourceRange();
4692       return ExprError();
4693     }
4694     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4695   } else if (Form != Load && Form != LoadCopy) {
4696     if (ValType.isConstQualified()) {
4697       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4698           << Ptr->getType() << Ptr->getSourceRange();
4699       return ExprError();
4700     }
4701   }
4702 
4703   // For an arithmetic operation, the implied arithmetic must be well-formed.
4704   if (Form == Arithmetic) {
4705     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4706     if (IsAddSub && !ValType->isIntegerType()
4707         && !ValType->isPointerType()) {
4708       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4709           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4710       return ExprError();
4711     }
4712     if (!IsAddSub && !ValType->isIntegerType()) {
4713       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4714           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4715       return ExprError();
4716     }
4717     if (IsC11 && ValType->isPointerType() &&
4718         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4719                             diag::err_incomplete_type)) {
4720       return ExprError();
4721     }
4722   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4723     // For __atomic_*_n operations, the value type must be a scalar integral or
4724     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4725     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4726         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4727     return ExprError();
4728   }
4729 
4730   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4731       !AtomTy->isScalarType()) {
4732     // For GNU atomics, require a trivially-copyable type. This is not part of
4733     // the GNU atomics specification, but we enforce it for sanity.
4734     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4735         << Ptr->getType() << Ptr->getSourceRange();
4736     return ExprError();
4737   }
4738 
4739   switch (ValType.getObjCLifetime()) {
4740   case Qualifiers::OCL_None:
4741   case Qualifiers::OCL_ExplicitNone:
4742     // okay
4743     break;
4744 
4745   case Qualifiers::OCL_Weak:
4746   case Qualifiers::OCL_Strong:
4747   case Qualifiers::OCL_Autoreleasing:
4748     // FIXME: Can this happen? By this point, ValType should be known
4749     // to be trivially copyable.
4750     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4751         << ValType << Ptr->getSourceRange();
4752     return ExprError();
4753   }
4754 
4755   // All atomic operations have an overload which takes a pointer to a volatile
4756   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4757   // into the result or the other operands. Similarly atomic_load takes a
4758   // pointer to a const 'A'.
4759   ValType.removeLocalVolatile();
4760   ValType.removeLocalConst();
4761   QualType ResultType = ValType;
4762   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4763       Form == Init)
4764     ResultType = Context.VoidTy;
4765   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4766     ResultType = Context.BoolTy;
4767 
4768   // The type of a parameter passed 'by value'. In the GNU atomics, such
4769   // arguments are actually passed as pointers.
4770   QualType ByValType = ValType; // 'CP'
4771   bool IsPassedByAddress = false;
4772   if (!IsC11 && !IsN) {
4773     ByValType = Ptr->getType();
4774     IsPassedByAddress = true;
4775   }
4776 
4777   SmallVector<Expr *, 5> APIOrderedArgs;
4778   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4779     APIOrderedArgs.push_back(Args[0]);
4780     switch (Form) {
4781     case Init:
4782     case Load:
4783       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4784       break;
4785     case LoadCopy:
4786     case Copy:
4787     case Arithmetic:
4788     case Xchg:
4789       APIOrderedArgs.push_back(Args[2]); // Val1
4790       APIOrderedArgs.push_back(Args[1]); // Order
4791       break;
4792     case GNUXchg:
4793       APIOrderedArgs.push_back(Args[2]); // Val1
4794       APIOrderedArgs.push_back(Args[3]); // Val2
4795       APIOrderedArgs.push_back(Args[1]); // Order
4796       break;
4797     case C11CmpXchg:
4798       APIOrderedArgs.push_back(Args[2]); // Val1
4799       APIOrderedArgs.push_back(Args[4]); // Val2
4800       APIOrderedArgs.push_back(Args[1]); // Order
4801       APIOrderedArgs.push_back(Args[3]); // OrderFail
4802       break;
4803     case GNUCmpXchg:
4804       APIOrderedArgs.push_back(Args[2]); // Val1
4805       APIOrderedArgs.push_back(Args[4]); // Val2
4806       APIOrderedArgs.push_back(Args[5]); // Weak
4807       APIOrderedArgs.push_back(Args[1]); // Order
4808       APIOrderedArgs.push_back(Args[3]); // OrderFail
4809       break;
4810     }
4811   } else
4812     APIOrderedArgs.append(Args.begin(), Args.end());
4813 
4814   // The first argument's non-CV pointer type is used to deduce the type of
4815   // subsequent arguments, except for:
4816   //  - weak flag (always converted to bool)
4817   //  - memory order (always converted to int)
4818   //  - scope  (always converted to int)
4819   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4820     QualType Ty;
4821     if (i < NumVals[Form] + 1) {
4822       switch (i) {
4823       case 0:
4824         // The first argument is always a pointer. It has a fixed type.
4825         // It is always dereferenced, a nullptr is undefined.
4826         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4827         // Nothing else to do: we already know all we want about this pointer.
4828         continue;
4829       case 1:
4830         // The second argument is the non-atomic operand. For arithmetic, this
4831         // is always passed by value, and for a compare_exchange it is always
4832         // passed by address. For the rest, GNU uses by-address and C11 uses
4833         // by-value.
4834         assert(Form != Load);
4835         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4836           Ty = ValType;
4837         else if (Form == Copy || Form == Xchg) {
4838           if (IsPassedByAddress) {
4839             // The value pointer is always dereferenced, a nullptr is undefined.
4840             CheckNonNullArgument(*this, APIOrderedArgs[i],
4841                                  ExprRange.getBegin());
4842           }
4843           Ty = ByValType;
4844         } else if (Form == Arithmetic)
4845           Ty = Context.getPointerDiffType();
4846         else {
4847           Expr *ValArg = APIOrderedArgs[i];
4848           // The value pointer is always dereferenced, a nullptr is undefined.
4849           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4850           LangAS AS = LangAS::Default;
4851           // Keep address space of non-atomic pointer type.
4852           if (const PointerType *PtrTy =
4853                   ValArg->getType()->getAs<PointerType>()) {
4854             AS = PtrTy->getPointeeType().getAddressSpace();
4855           }
4856           Ty = Context.getPointerType(
4857               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4858         }
4859         break;
4860       case 2:
4861         // The third argument to compare_exchange / GNU exchange is the desired
4862         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4863         if (IsPassedByAddress)
4864           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4865         Ty = ByValType;
4866         break;
4867       case 3:
4868         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4869         Ty = Context.BoolTy;
4870         break;
4871       }
4872     } else {
4873       // The order(s) and scope are always converted to int.
4874       Ty = Context.IntTy;
4875     }
4876 
4877     InitializedEntity Entity =
4878         InitializedEntity::InitializeParameter(Context, Ty, false);
4879     ExprResult Arg = APIOrderedArgs[i];
4880     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4881     if (Arg.isInvalid())
4882       return true;
4883     APIOrderedArgs[i] = Arg.get();
4884   }
4885 
4886   // Permute the arguments into a 'consistent' order.
4887   SmallVector<Expr*, 5> SubExprs;
4888   SubExprs.push_back(Ptr);
4889   switch (Form) {
4890   case Init:
4891     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4892     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4893     break;
4894   case Load:
4895     SubExprs.push_back(APIOrderedArgs[1]); // Order
4896     break;
4897   case LoadCopy:
4898   case Copy:
4899   case Arithmetic:
4900   case Xchg:
4901     SubExprs.push_back(APIOrderedArgs[2]); // Order
4902     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4903     break;
4904   case GNUXchg:
4905     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4906     SubExprs.push_back(APIOrderedArgs[3]); // Order
4907     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4908     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4909     break;
4910   case C11CmpXchg:
4911     SubExprs.push_back(APIOrderedArgs[3]); // Order
4912     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4913     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4914     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4915     break;
4916   case GNUCmpXchg:
4917     SubExprs.push_back(APIOrderedArgs[4]); // Order
4918     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4919     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4920     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4921     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4922     break;
4923   }
4924 
4925   if (SubExprs.size() >= 2 && Form != Init) {
4926     llvm::APSInt Result(32);
4927     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4928         !isValidOrderingForOp(Result.getSExtValue(), Op))
4929       Diag(SubExprs[1]->getBeginLoc(),
4930            diag::warn_atomic_op_has_invalid_memory_order)
4931           << SubExprs[1]->getSourceRange();
4932   }
4933 
4934   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4935     auto *Scope = Args[Args.size() - 1];
4936     llvm::APSInt Result(32);
4937     if (Scope->isIntegerConstantExpr(Result, Context) &&
4938         !ScopeModel->isValid(Result.getZExtValue())) {
4939       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4940           << Scope->getSourceRange();
4941     }
4942     SubExprs.push_back(Scope);
4943   }
4944 
4945   AtomicExpr *AE = new (Context)
4946       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4947 
4948   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4949        Op == AtomicExpr::AO__c11_atomic_store ||
4950        Op == AtomicExpr::AO__opencl_atomic_load ||
4951        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4952       Context.AtomicUsesUnsupportedLibcall(AE))
4953     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4954         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4955              Op == AtomicExpr::AO__opencl_atomic_load)
4956                 ? 0
4957                 : 1);
4958 
4959   return AE;
4960 }
4961 
4962 /// checkBuiltinArgument - Given a call to a builtin function, perform
4963 /// normal type-checking on the given argument, updating the call in
4964 /// place.  This is useful when a builtin function requires custom
4965 /// type-checking for some of its arguments but not necessarily all of
4966 /// them.
4967 ///
4968 /// Returns true on error.
4969 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4970   FunctionDecl *Fn = E->getDirectCallee();
4971   assert(Fn && "builtin call without direct callee!");
4972 
4973   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4974   InitializedEntity Entity =
4975     InitializedEntity::InitializeParameter(S.Context, Param);
4976 
4977   ExprResult Arg = E->getArg(0);
4978   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4979   if (Arg.isInvalid())
4980     return true;
4981 
4982   E->setArg(ArgIndex, Arg.get());
4983   return false;
4984 }
4985 
4986 /// We have a call to a function like __sync_fetch_and_add, which is an
4987 /// overloaded function based on the pointer type of its first argument.
4988 /// The main BuildCallExpr routines have already promoted the types of
4989 /// arguments because all of these calls are prototyped as void(...).
4990 ///
4991 /// This function goes through and does final semantic checking for these
4992 /// builtins, as well as generating any warnings.
4993 ExprResult
4994 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4995   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4996   Expr *Callee = TheCall->getCallee();
4997   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4998   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4999 
5000   // Ensure that we have at least one argument to do type inference from.
5001   if (TheCall->getNumArgs() < 1) {
5002     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5003         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5004     return ExprError();
5005   }
5006 
5007   // Inspect the first argument of the atomic builtin.  This should always be
5008   // a pointer type, whose element is an integral scalar or pointer type.
5009   // Because it is a pointer type, we don't have to worry about any implicit
5010   // casts here.
5011   // FIXME: We don't allow floating point scalars as input.
5012   Expr *FirstArg = TheCall->getArg(0);
5013   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5014   if (FirstArgResult.isInvalid())
5015     return ExprError();
5016   FirstArg = FirstArgResult.get();
5017   TheCall->setArg(0, FirstArg);
5018 
5019   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5020   if (!pointerType) {
5021     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5022         << FirstArg->getType() << FirstArg->getSourceRange();
5023     return ExprError();
5024   }
5025 
5026   QualType ValType = pointerType->getPointeeType();
5027   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5028       !ValType->isBlockPointerType()) {
5029     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5030         << FirstArg->getType() << FirstArg->getSourceRange();
5031     return ExprError();
5032   }
5033 
5034   if (ValType.isConstQualified()) {
5035     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5036         << FirstArg->getType() << FirstArg->getSourceRange();
5037     return ExprError();
5038   }
5039 
5040   switch (ValType.getObjCLifetime()) {
5041   case Qualifiers::OCL_None:
5042   case Qualifiers::OCL_ExplicitNone:
5043     // okay
5044     break;
5045 
5046   case Qualifiers::OCL_Weak:
5047   case Qualifiers::OCL_Strong:
5048   case Qualifiers::OCL_Autoreleasing:
5049     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5050         << ValType << FirstArg->getSourceRange();
5051     return ExprError();
5052   }
5053 
5054   // Strip any qualifiers off ValType.
5055   ValType = ValType.getUnqualifiedType();
5056 
5057   // The majority of builtins return a value, but a few have special return
5058   // types, so allow them to override appropriately below.
5059   QualType ResultType = ValType;
5060 
5061   // We need to figure out which concrete builtin this maps onto.  For example,
5062   // __sync_fetch_and_add with a 2 byte object turns into
5063   // __sync_fetch_and_add_2.
5064 #define BUILTIN_ROW(x) \
5065   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5066     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5067 
5068   static const unsigned BuiltinIndices[][5] = {
5069     BUILTIN_ROW(__sync_fetch_and_add),
5070     BUILTIN_ROW(__sync_fetch_and_sub),
5071     BUILTIN_ROW(__sync_fetch_and_or),
5072     BUILTIN_ROW(__sync_fetch_and_and),
5073     BUILTIN_ROW(__sync_fetch_and_xor),
5074     BUILTIN_ROW(__sync_fetch_and_nand),
5075 
5076     BUILTIN_ROW(__sync_add_and_fetch),
5077     BUILTIN_ROW(__sync_sub_and_fetch),
5078     BUILTIN_ROW(__sync_and_and_fetch),
5079     BUILTIN_ROW(__sync_or_and_fetch),
5080     BUILTIN_ROW(__sync_xor_and_fetch),
5081     BUILTIN_ROW(__sync_nand_and_fetch),
5082 
5083     BUILTIN_ROW(__sync_val_compare_and_swap),
5084     BUILTIN_ROW(__sync_bool_compare_and_swap),
5085     BUILTIN_ROW(__sync_lock_test_and_set),
5086     BUILTIN_ROW(__sync_lock_release),
5087     BUILTIN_ROW(__sync_swap)
5088   };
5089 #undef BUILTIN_ROW
5090 
5091   // Determine the index of the size.
5092   unsigned SizeIndex;
5093   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5094   case 1: SizeIndex = 0; break;
5095   case 2: SizeIndex = 1; break;
5096   case 4: SizeIndex = 2; break;
5097   case 8: SizeIndex = 3; break;
5098   case 16: SizeIndex = 4; break;
5099   default:
5100     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5101         << FirstArg->getType() << FirstArg->getSourceRange();
5102     return ExprError();
5103   }
5104 
5105   // Each of these builtins has one pointer argument, followed by some number of
5106   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5107   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5108   // as the number of fixed args.
5109   unsigned BuiltinID = FDecl->getBuiltinID();
5110   unsigned BuiltinIndex, NumFixed = 1;
5111   bool WarnAboutSemanticsChange = false;
5112   switch (BuiltinID) {
5113   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5114   case Builtin::BI__sync_fetch_and_add:
5115   case Builtin::BI__sync_fetch_and_add_1:
5116   case Builtin::BI__sync_fetch_and_add_2:
5117   case Builtin::BI__sync_fetch_and_add_4:
5118   case Builtin::BI__sync_fetch_and_add_8:
5119   case Builtin::BI__sync_fetch_and_add_16:
5120     BuiltinIndex = 0;
5121     break;
5122 
5123   case Builtin::BI__sync_fetch_and_sub:
5124   case Builtin::BI__sync_fetch_and_sub_1:
5125   case Builtin::BI__sync_fetch_and_sub_2:
5126   case Builtin::BI__sync_fetch_and_sub_4:
5127   case Builtin::BI__sync_fetch_and_sub_8:
5128   case Builtin::BI__sync_fetch_and_sub_16:
5129     BuiltinIndex = 1;
5130     break;
5131 
5132   case Builtin::BI__sync_fetch_and_or:
5133   case Builtin::BI__sync_fetch_and_or_1:
5134   case Builtin::BI__sync_fetch_and_or_2:
5135   case Builtin::BI__sync_fetch_and_or_4:
5136   case Builtin::BI__sync_fetch_and_or_8:
5137   case Builtin::BI__sync_fetch_and_or_16:
5138     BuiltinIndex = 2;
5139     break;
5140 
5141   case Builtin::BI__sync_fetch_and_and:
5142   case Builtin::BI__sync_fetch_and_and_1:
5143   case Builtin::BI__sync_fetch_and_and_2:
5144   case Builtin::BI__sync_fetch_and_and_4:
5145   case Builtin::BI__sync_fetch_and_and_8:
5146   case Builtin::BI__sync_fetch_and_and_16:
5147     BuiltinIndex = 3;
5148     break;
5149 
5150   case Builtin::BI__sync_fetch_and_xor:
5151   case Builtin::BI__sync_fetch_and_xor_1:
5152   case Builtin::BI__sync_fetch_and_xor_2:
5153   case Builtin::BI__sync_fetch_and_xor_4:
5154   case Builtin::BI__sync_fetch_and_xor_8:
5155   case Builtin::BI__sync_fetch_and_xor_16:
5156     BuiltinIndex = 4;
5157     break;
5158 
5159   case Builtin::BI__sync_fetch_and_nand:
5160   case Builtin::BI__sync_fetch_and_nand_1:
5161   case Builtin::BI__sync_fetch_and_nand_2:
5162   case Builtin::BI__sync_fetch_and_nand_4:
5163   case Builtin::BI__sync_fetch_and_nand_8:
5164   case Builtin::BI__sync_fetch_and_nand_16:
5165     BuiltinIndex = 5;
5166     WarnAboutSemanticsChange = true;
5167     break;
5168 
5169   case Builtin::BI__sync_add_and_fetch:
5170   case Builtin::BI__sync_add_and_fetch_1:
5171   case Builtin::BI__sync_add_and_fetch_2:
5172   case Builtin::BI__sync_add_and_fetch_4:
5173   case Builtin::BI__sync_add_and_fetch_8:
5174   case Builtin::BI__sync_add_and_fetch_16:
5175     BuiltinIndex = 6;
5176     break;
5177 
5178   case Builtin::BI__sync_sub_and_fetch:
5179   case Builtin::BI__sync_sub_and_fetch_1:
5180   case Builtin::BI__sync_sub_and_fetch_2:
5181   case Builtin::BI__sync_sub_and_fetch_4:
5182   case Builtin::BI__sync_sub_and_fetch_8:
5183   case Builtin::BI__sync_sub_and_fetch_16:
5184     BuiltinIndex = 7;
5185     break;
5186 
5187   case Builtin::BI__sync_and_and_fetch:
5188   case Builtin::BI__sync_and_and_fetch_1:
5189   case Builtin::BI__sync_and_and_fetch_2:
5190   case Builtin::BI__sync_and_and_fetch_4:
5191   case Builtin::BI__sync_and_and_fetch_8:
5192   case Builtin::BI__sync_and_and_fetch_16:
5193     BuiltinIndex = 8;
5194     break;
5195 
5196   case Builtin::BI__sync_or_and_fetch:
5197   case Builtin::BI__sync_or_and_fetch_1:
5198   case Builtin::BI__sync_or_and_fetch_2:
5199   case Builtin::BI__sync_or_and_fetch_4:
5200   case Builtin::BI__sync_or_and_fetch_8:
5201   case Builtin::BI__sync_or_and_fetch_16:
5202     BuiltinIndex = 9;
5203     break;
5204 
5205   case Builtin::BI__sync_xor_and_fetch:
5206   case Builtin::BI__sync_xor_and_fetch_1:
5207   case Builtin::BI__sync_xor_and_fetch_2:
5208   case Builtin::BI__sync_xor_and_fetch_4:
5209   case Builtin::BI__sync_xor_and_fetch_8:
5210   case Builtin::BI__sync_xor_and_fetch_16:
5211     BuiltinIndex = 10;
5212     break;
5213 
5214   case Builtin::BI__sync_nand_and_fetch:
5215   case Builtin::BI__sync_nand_and_fetch_1:
5216   case Builtin::BI__sync_nand_and_fetch_2:
5217   case Builtin::BI__sync_nand_and_fetch_4:
5218   case Builtin::BI__sync_nand_and_fetch_8:
5219   case Builtin::BI__sync_nand_and_fetch_16:
5220     BuiltinIndex = 11;
5221     WarnAboutSemanticsChange = true;
5222     break;
5223 
5224   case Builtin::BI__sync_val_compare_and_swap:
5225   case Builtin::BI__sync_val_compare_and_swap_1:
5226   case Builtin::BI__sync_val_compare_and_swap_2:
5227   case Builtin::BI__sync_val_compare_and_swap_4:
5228   case Builtin::BI__sync_val_compare_and_swap_8:
5229   case Builtin::BI__sync_val_compare_and_swap_16:
5230     BuiltinIndex = 12;
5231     NumFixed = 2;
5232     break;
5233 
5234   case Builtin::BI__sync_bool_compare_and_swap:
5235   case Builtin::BI__sync_bool_compare_and_swap_1:
5236   case Builtin::BI__sync_bool_compare_and_swap_2:
5237   case Builtin::BI__sync_bool_compare_and_swap_4:
5238   case Builtin::BI__sync_bool_compare_and_swap_8:
5239   case Builtin::BI__sync_bool_compare_and_swap_16:
5240     BuiltinIndex = 13;
5241     NumFixed = 2;
5242     ResultType = Context.BoolTy;
5243     break;
5244 
5245   case Builtin::BI__sync_lock_test_and_set:
5246   case Builtin::BI__sync_lock_test_and_set_1:
5247   case Builtin::BI__sync_lock_test_and_set_2:
5248   case Builtin::BI__sync_lock_test_and_set_4:
5249   case Builtin::BI__sync_lock_test_and_set_8:
5250   case Builtin::BI__sync_lock_test_and_set_16:
5251     BuiltinIndex = 14;
5252     break;
5253 
5254   case Builtin::BI__sync_lock_release:
5255   case Builtin::BI__sync_lock_release_1:
5256   case Builtin::BI__sync_lock_release_2:
5257   case Builtin::BI__sync_lock_release_4:
5258   case Builtin::BI__sync_lock_release_8:
5259   case Builtin::BI__sync_lock_release_16:
5260     BuiltinIndex = 15;
5261     NumFixed = 0;
5262     ResultType = Context.VoidTy;
5263     break;
5264 
5265   case Builtin::BI__sync_swap:
5266   case Builtin::BI__sync_swap_1:
5267   case Builtin::BI__sync_swap_2:
5268   case Builtin::BI__sync_swap_4:
5269   case Builtin::BI__sync_swap_8:
5270   case Builtin::BI__sync_swap_16:
5271     BuiltinIndex = 16;
5272     break;
5273   }
5274 
5275   // Now that we know how many fixed arguments we expect, first check that we
5276   // have at least that many.
5277   if (TheCall->getNumArgs() < 1+NumFixed) {
5278     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5279         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5280         << Callee->getSourceRange();
5281     return ExprError();
5282   }
5283 
5284   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5285       << Callee->getSourceRange();
5286 
5287   if (WarnAboutSemanticsChange) {
5288     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5289         << Callee->getSourceRange();
5290   }
5291 
5292   // Get the decl for the concrete builtin from this, we can tell what the
5293   // concrete integer type we should convert to is.
5294   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5295   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5296   FunctionDecl *NewBuiltinDecl;
5297   if (NewBuiltinID == BuiltinID)
5298     NewBuiltinDecl = FDecl;
5299   else {
5300     // Perform builtin lookup to avoid redeclaring it.
5301     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5302     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5303     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5304     assert(Res.getFoundDecl());
5305     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5306     if (!NewBuiltinDecl)
5307       return ExprError();
5308   }
5309 
5310   // The first argument --- the pointer --- has a fixed type; we
5311   // deduce the types of the rest of the arguments accordingly.  Walk
5312   // the remaining arguments, converting them to the deduced value type.
5313   for (unsigned i = 0; i != NumFixed; ++i) {
5314     ExprResult Arg = TheCall->getArg(i+1);
5315 
5316     // GCC does an implicit conversion to the pointer or integer ValType.  This
5317     // can fail in some cases (1i -> int**), check for this error case now.
5318     // Initialize the argument.
5319     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5320                                                    ValType, /*consume*/ false);
5321     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5322     if (Arg.isInvalid())
5323       return ExprError();
5324 
5325     // Okay, we have something that *can* be converted to the right type.  Check
5326     // to see if there is a potentially weird extension going on here.  This can
5327     // happen when you do an atomic operation on something like an char* and
5328     // pass in 42.  The 42 gets converted to char.  This is even more strange
5329     // for things like 45.123 -> char, etc.
5330     // FIXME: Do this check.
5331     TheCall->setArg(i+1, Arg.get());
5332   }
5333 
5334   // Create a new DeclRefExpr to refer to the new decl.
5335   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5336       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5337       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5338       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5339 
5340   // Set the callee in the CallExpr.
5341   // FIXME: This loses syntactic information.
5342   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5343   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5344                                               CK_BuiltinFnToFnPtr);
5345   TheCall->setCallee(PromotedCall.get());
5346 
5347   // Change the result type of the call to match the original value type. This
5348   // is arbitrary, but the codegen for these builtins ins design to handle it
5349   // gracefully.
5350   TheCall->setType(ResultType);
5351 
5352   return TheCallResult;
5353 }
5354 
5355 /// SemaBuiltinNontemporalOverloaded - We have a call to
5356 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5357 /// overloaded function based on the pointer type of its last argument.
5358 ///
5359 /// This function goes through and does final semantic checking for these
5360 /// builtins.
5361 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5362   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5363   DeclRefExpr *DRE =
5364       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5365   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5366   unsigned BuiltinID = FDecl->getBuiltinID();
5367   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5368           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5369          "Unexpected nontemporal load/store builtin!");
5370   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5371   unsigned numArgs = isStore ? 2 : 1;
5372 
5373   // Ensure that we have the proper number of arguments.
5374   if (checkArgCount(*this, TheCall, numArgs))
5375     return ExprError();
5376 
5377   // Inspect the last argument of the nontemporal builtin.  This should always
5378   // be a pointer type, from which we imply the type of the memory access.
5379   // Because it is a pointer type, we don't have to worry about any implicit
5380   // casts here.
5381   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5382   ExprResult PointerArgResult =
5383       DefaultFunctionArrayLvalueConversion(PointerArg);
5384 
5385   if (PointerArgResult.isInvalid())
5386     return ExprError();
5387   PointerArg = PointerArgResult.get();
5388   TheCall->setArg(numArgs - 1, PointerArg);
5389 
5390   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5391   if (!pointerType) {
5392     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5393         << PointerArg->getType() << PointerArg->getSourceRange();
5394     return ExprError();
5395   }
5396 
5397   QualType ValType = pointerType->getPointeeType();
5398 
5399   // Strip any qualifiers off ValType.
5400   ValType = ValType.getUnqualifiedType();
5401   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5402       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5403       !ValType->isVectorType()) {
5404     Diag(DRE->getBeginLoc(),
5405          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5406         << PointerArg->getType() << PointerArg->getSourceRange();
5407     return ExprError();
5408   }
5409 
5410   if (!isStore) {
5411     TheCall->setType(ValType);
5412     return TheCallResult;
5413   }
5414 
5415   ExprResult ValArg = TheCall->getArg(0);
5416   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5417       Context, ValType, /*consume*/ false);
5418   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5419   if (ValArg.isInvalid())
5420     return ExprError();
5421 
5422   TheCall->setArg(0, ValArg.get());
5423   TheCall->setType(Context.VoidTy);
5424   return TheCallResult;
5425 }
5426 
5427 /// CheckObjCString - Checks that the argument to the builtin
5428 /// CFString constructor is correct
5429 /// Note: It might also make sense to do the UTF-16 conversion here (would
5430 /// simplify the backend).
5431 bool Sema::CheckObjCString(Expr *Arg) {
5432   Arg = Arg->IgnoreParenCasts();
5433   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5434 
5435   if (!Literal || !Literal->isAscii()) {
5436     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5437         << Arg->getSourceRange();
5438     return true;
5439   }
5440 
5441   if (Literal->containsNonAsciiOrNull()) {
5442     StringRef String = Literal->getString();
5443     unsigned NumBytes = String.size();
5444     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5445     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5446     llvm::UTF16 *ToPtr = &ToBuf[0];
5447 
5448     llvm::ConversionResult Result =
5449         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5450                                  ToPtr + NumBytes, llvm::strictConversion);
5451     // Check for conversion failure.
5452     if (Result != llvm::conversionOK)
5453       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5454           << Arg->getSourceRange();
5455   }
5456   return false;
5457 }
5458 
5459 /// CheckObjCString - Checks that the format string argument to the os_log()
5460 /// and os_trace() functions is correct, and converts it to const char *.
5461 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5462   Arg = Arg->IgnoreParenCasts();
5463   auto *Literal = dyn_cast<StringLiteral>(Arg);
5464   if (!Literal) {
5465     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5466       Literal = ObjcLiteral->getString();
5467     }
5468   }
5469 
5470   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5471     return ExprError(
5472         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5473         << Arg->getSourceRange());
5474   }
5475 
5476   ExprResult Result(Literal);
5477   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5478   InitializedEntity Entity =
5479       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5480   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5481   return Result;
5482 }
5483 
5484 /// Check that the user is calling the appropriate va_start builtin for the
5485 /// target and calling convention.
5486 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5487   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5488   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5489   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5490                     TT.getArch() == llvm::Triple::aarch64_32);
5491   bool IsWindows = TT.isOSWindows();
5492   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5493   if (IsX64 || IsAArch64) {
5494     CallingConv CC = CC_C;
5495     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5496       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5497     if (IsMSVAStart) {
5498       // Don't allow this in System V ABI functions.
5499       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5500         return S.Diag(Fn->getBeginLoc(),
5501                       diag::err_ms_va_start_used_in_sysv_function);
5502     } else {
5503       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5504       // On x64 Windows, don't allow this in System V ABI functions.
5505       // (Yes, that means there's no corresponding way to support variadic
5506       // System V ABI functions on Windows.)
5507       if ((IsWindows && CC == CC_X86_64SysV) ||
5508           (!IsWindows && CC == CC_Win64))
5509         return S.Diag(Fn->getBeginLoc(),
5510                       diag::err_va_start_used_in_wrong_abi_function)
5511                << !IsWindows;
5512     }
5513     return false;
5514   }
5515 
5516   if (IsMSVAStart)
5517     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5518   return false;
5519 }
5520 
5521 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5522                                              ParmVarDecl **LastParam = nullptr) {
5523   // Determine whether the current function, block, or obj-c method is variadic
5524   // and get its parameter list.
5525   bool IsVariadic = false;
5526   ArrayRef<ParmVarDecl *> Params;
5527   DeclContext *Caller = S.CurContext;
5528   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5529     IsVariadic = Block->isVariadic();
5530     Params = Block->parameters();
5531   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5532     IsVariadic = FD->isVariadic();
5533     Params = FD->parameters();
5534   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5535     IsVariadic = MD->isVariadic();
5536     // FIXME: This isn't correct for methods (results in bogus warning).
5537     Params = MD->parameters();
5538   } else if (isa<CapturedDecl>(Caller)) {
5539     // We don't support va_start in a CapturedDecl.
5540     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5541     return true;
5542   } else {
5543     // This must be some other declcontext that parses exprs.
5544     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5545     return true;
5546   }
5547 
5548   if (!IsVariadic) {
5549     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5550     return true;
5551   }
5552 
5553   if (LastParam)
5554     *LastParam = Params.empty() ? nullptr : Params.back();
5555 
5556   return false;
5557 }
5558 
5559 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5560 /// for validity.  Emit an error and return true on failure; return false
5561 /// on success.
5562 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5563   Expr *Fn = TheCall->getCallee();
5564 
5565   if (checkVAStartABI(*this, BuiltinID, Fn))
5566     return true;
5567 
5568   if (TheCall->getNumArgs() > 2) {
5569     Diag(TheCall->getArg(2)->getBeginLoc(),
5570          diag::err_typecheck_call_too_many_args)
5571         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5572         << Fn->getSourceRange()
5573         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5574                        (*(TheCall->arg_end() - 1))->getEndLoc());
5575     return true;
5576   }
5577 
5578   if (TheCall->getNumArgs() < 2) {
5579     return Diag(TheCall->getEndLoc(),
5580                 diag::err_typecheck_call_too_few_args_at_least)
5581            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5582   }
5583 
5584   // Type-check the first argument normally.
5585   if (checkBuiltinArgument(*this, TheCall, 0))
5586     return true;
5587 
5588   // Check that the current function is variadic, and get its last parameter.
5589   ParmVarDecl *LastParam;
5590   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5591     return true;
5592 
5593   // Verify that the second argument to the builtin is the last argument of the
5594   // current function or method.
5595   bool SecondArgIsLastNamedArgument = false;
5596   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5597 
5598   // These are valid if SecondArgIsLastNamedArgument is false after the next
5599   // block.
5600   QualType Type;
5601   SourceLocation ParamLoc;
5602   bool IsCRegister = false;
5603 
5604   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5605     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5606       SecondArgIsLastNamedArgument = PV == LastParam;
5607 
5608       Type = PV->getType();
5609       ParamLoc = PV->getLocation();
5610       IsCRegister =
5611           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5612     }
5613   }
5614 
5615   if (!SecondArgIsLastNamedArgument)
5616     Diag(TheCall->getArg(1)->getBeginLoc(),
5617          diag::warn_second_arg_of_va_start_not_last_named_param);
5618   else if (IsCRegister || Type->isReferenceType() ||
5619            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5620              // Promotable integers are UB, but enumerations need a bit of
5621              // extra checking to see what their promotable type actually is.
5622              if (!Type->isPromotableIntegerType())
5623                return false;
5624              if (!Type->isEnumeralType())
5625                return true;
5626              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5627              return !(ED &&
5628                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5629            }()) {
5630     unsigned Reason = 0;
5631     if (Type->isReferenceType())  Reason = 1;
5632     else if (IsCRegister)         Reason = 2;
5633     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5634     Diag(ParamLoc, diag::note_parameter_type) << Type;
5635   }
5636 
5637   TheCall->setType(Context.VoidTy);
5638   return false;
5639 }
5640 
5641 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5642   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5643   //                 const char *named_addr);
5644 
5645   Expr *Func = Call->getCallee();
5646 
5647   if (Call->getNumArgs() < 3)
5648     return Diag(Call->getEndLoc(),
5649                 diag::err_typecheck_call_too_few_args_at_least)
5650            << 0 /*function call*/ << 3 << Call->getNumArgs();
5651 
5652   // Type-check the first argument normally.
5653   if (checkBuiltinArgument(*this, Call, 0))
5654     return true;
5655 
5656   // Check that the current function is variadic.
5657   if (checkVAStartIsInVariadicFunction(*this, Func))
5658     return true;
5659 
5660   // __va_start on Windows does not validate the parameter qualifiers
5661 
5662   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5663   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5664 
5665   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5666   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5667 
5668   const QualType &ConstCharPtrTy =
5669       Context.getPointerType(Context.CharTy.withConst());
5670   if (!Arg1Ty->isPointerType() ||
5671       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5672     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5673         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5674         << 0                                      /* qualifier difference */
5675         << 3                                      /* parameter mismatch */
5676         << 2 << Arg1->getType() << ConstCharPtrTy;
5677 
5678   const QualType SizeTy = Context.getSizeType();
5679   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5680     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5681         << Arg2->getType() << SizeTy << 1 /* different class */
5682         << 0                              /* qualifier difference */
5683         << 3                              /* parameter mismatch */
5684         << 3 << Arg2->getType() << SizeTy;
5685 
5686   return false;
5687 }
5688 
5689 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5690 /// friends.  This is declared to take (...), so we have to check everything.
5691 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5692   if (TheCall->getNumArgs() < 2)
5693     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5694            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5695   if (TheCall->getNumArgs() > 2)
5696     return Diag(TheCall->getArg(2)->getBeginLoc(),
5697                 diag::err_typecheck_call_too_many_args)
5698            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5699            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5700                           (*(TheCall->arg_end() - 1))->getEndLoc());
5701 
5702   ExprResult OrigArg0 = TheCall->getArg(0);
5703   ExprResult OrigArg1 = TheCall->getArg(1);
5704 
5705   // Do standard promotions between the two arguments, returning their common
5706   // type.
5707   QualType Res = UsualArithmeticConversions(
5708       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5709   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5710     return true;
5711 
5712   // Make sure any conversions are pushed back into the call; this is
5713   // type safe since unordered compare builtins are declared as "_Bool
5714   // foo(...)".
5715   TheCall->setArg(0, OrigArg0.get());
5716   TheCall->setArg(1, OrigArg1.get());
5717 
5718   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5719     return false;
5720 
5721   // If the common type isn't a real floating type, then the arguments were
5722   // invalid for this operation.
5723   if (Res.isNull() || !Res->isRealFloatingType())
5724     return Diag(OrigArg0.get()->getBeginLoc(),
5725                 diag::err_typecheck_call_invalid_ordered_compare)
5726            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5727            << SourceRange(OrigArg0.get()->getBeginLoc(),
5728                           OrigArg1.get()->getEndLoc());
5729 
5730   return false;
5731 }
5732 
5733 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5734 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5735 /// to check everything. We expect the last argument to be a floating point
5736 /// value.
5737 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5738   if (TheCall->getNumArgs() < NumArgs)
5739     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5740            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5741   if (TheCall->getNumArgs() > NumArgs)
5742     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5743                 diag::err_typecheck_call_too_many_args)
5744            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5745            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5746                           (*(TheCall->arg_end() - 1))->getEndLoc());
5747 
5748   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5749   // on all preceding parameters just being int.  Try all of those.
5750   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5751     Expr *Arg = TheCall->getArg(i);
5752 
5753     if (Arg->isTypeDependent())
5754       return false;
5755 
5756     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5757 
5758     if (Res.isInvalid())
5759       return true;
5760     TheCall->setArg(i, Res.get());
5761   }
5762 
5763   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5764 
5765   if (OrigArg->isTypeDependent())
5766     return false;
5767 
5768   // Usual Unary Conversions will convert half to float, which we want for
5769   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5770   // type how it is, but do normal L->Rvalue conversions.
5771   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5772     OrigArg = UsualUnaryConversions(OrigArg).get();
5773   else
5774     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5775   TheCall->setArg(NumArgs - 1, OrigArg);
5776 
5777   // This operation requires a non-_Complex floating-point number.
5778   if (!OrigArg->getType()->isRealFloatingType())
5779     return Diag(OrigArg->getBeginLoc(),
5780                 diag::err_typecheck_call_invalid_unary_fp)
5781            << OrigArg->getType() << OrigArg->getSourceRange();
5782 
5783   return false;
5784 }
5785 
5786 // Customized Sema Checking for VSX builtins that have the following signature:
5787 // vector [...] builtinName(vector [...], vector [...], const int);
5788 // Which takes the same type of vectors (any legal vector type) for the first
5789 // two arguments and takes compile time constant for the third argument.
5790 // Example builtins are :
5791 // vector double vec_xxpermdi(vector double, vector double, int);
5792 // vector short vec_xxsldwi(vector short, vector short, int);
5793 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5794   unsigned ExpectedNumArgs = 3;
5795   if (TheCall->getNumArgs() < ExpectedNumArgs)
5796     return Diag(TheCall->getEndLoc(),
5797                 diag::err_typecheck_call_too_few_args_at_least)
5798            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5799            << TheCall->getSourceRange();
5800 
5801   if (TheCall->getNumArgs() > ExpectedNumArgs)
5802     return Diag(TheCall->getEndLoc(),
5803                 diag::err_typecheck_call_too_many_args_at_most)
5804            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5805            << TheCall->getSourceRange();
5806 
5807   // Check the third argument is a compile time constant
5808   llvm::APSInt Value;
5809   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5810     return Diag(TheCall->getBeginLoc(),
5811                 diag::err_vsx_builtin_nonconstant_argument)
5812            << 3 /* argument index */ << TheCall->getDirectCallee()
5813            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5814                           TheCall->getArg(2)->getEndLoc());
5815 
5816   QualType Arg1Ty = TheCall->getArg(0)->getType();
5817   QualType Arg2Ty = TheCall->getArg(1)->getType();
5818 
5819   // Check the type of argument 1 and argument 2 are vectors.
5820   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5821   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5822       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5823     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5824            << TheCall->getDirectCallee()
5825            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5826                           TheCall->getArg(1)->getEndLoc());
5827   }
5828 
5829   // Check the first two arguments are the same type.
5830   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5831     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5832            << TheCall->getDirectCallee()
5833            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5834                           TheCall->getArg(1)->getEndLoc());
5835   }
5836 
5837   // When default clang type checking is turned off and the customized type
5838   // checking is used, the returning type of the function must be explicitly
5839   // set. Otherwise it is _Bool by default.
5840   TheCall->setType(Arg1Ty);
5841 
5842   return false;
5843 }
5844 
5845 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5846 // This is declared to take (...), so we have to check everything.
5847 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5848   if (TheCall->getNumArgs() < 2)
5849     return ExprError(Diag(TheCall->getEndLoc(),
5850                           diag::err_typecheck_call_too_few_args_at_least)
5851                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5852                      << TheCall->getSourceRange());
5853 
5854   // Determine which of the following types of shufflevector we're checking:
5855   // 1) unary, vector mask: (lhs, mask)
5856   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5857   QualType resType = TheCall->getArg(0)->getType();
5858   unsigned numElements = 0;
5859 
5860   if (!TheCall->getArg(0)->isTypeDependent() &&
5861       !TheCall->getArg(1)->isTypeDependent()) {
5862     QualType LHSType = TheCall->getArg(0)->getType();
5863     QualType RHSType = TheCall->getArg(1)->getType();
5864 
5865     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5866       return ExprError(
5867           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5868           << TheCall->getDirectCallee()
5869           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5870                          TheCall->getArg(1)->getEndLoc()));
5871 
5872     numElements = LHSType->castAs<VectorType>()->getNumElements();
5873     unsigned numResElements = TheCall->getNumArgs() - 2;
5874 
5875     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5876     // with mask.  If so, verify that RHS is an integer vector type with the
5877     // same number of elts as lhs.
5878     if (TheCall->getNumArgs() == 2) {
5879       if (!RHSType->hasIntegerRepresentation() ||
5880           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5881         return ExprError(Diag(TheCall->getBeginLoc(),
5882                               diag::err_vec_builtin_incompatible_vector)
5883                          << TheCall->getDirectCallee()
5884                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5885                                         TheCall->getArg(1)->getEndLoc()));
5886     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5887       return ExprError(Diag(TheCall->getBeginLoc(),
5888                             diag::err_vec_builtin_incompatible_vector)
5889                        << TheCall->getDirectCallee()
5890                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5891                                       TheCall->getArg(1)->getEndLoc()));
5892     } else if (numElements != numResElements) {
5893       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5894       resType = Context.getVectorType(eltType, numResElements,
5895                                       VectorType::GenericVector);
5896     }
5897   }
5898 
5899   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5900     if (TheCall->getArg(i)->isTypeDependent() ||
5901         TheCall->getArg(i)->isValueDependent())
5902       continue;
5903 
5904     llvm::APSInt Result(32);
5905     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5906       return ExprError(Diag(TheCall->getBeginLoc(),
5907                             diag::err_shufflevector_nonconstant_argument)
5908                        << TheCall->getArg(i)->getSourceRange());
5909 
5910     // Allow -1 which will be translated to undef in the IR.
5911     if (Result.isSigned() && Result.isAllOnesValue())
5912       continue;
5913 
5914     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5915       return ExprError(Diag(TheCall->getBeginLoc(),
5916                             diag::err_shufflevector_argument_too_large)
5917                        << TheCall->getArg(i)->getSourceRange());
5918   }
5919 
5920   SmallVector<Expr*, 32> exprs;
5921 
5922   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5923     exprs.push_back(TheCall->getArg(i));
5924     TheCall->setArg(i, nullptr);
5925   }
5926 
5927   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5928                                          TheCall->getCallee()->getBeginLoc(),
5929                                          TheCall->getRParenLoc());
5930 }
5931 
5932 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5933 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5934                                        SourceLocation BuiltinLoc,
5935                                        SourceLocation RParenLoc) {
5936   ExprValueKind VK = VK_RValue;
5937   ExprObjectKind OK = OK_Ordinary;
5938   QualType DstTy = TInfo->getType();
5939   QualType SrcTy = E->getType();
5940 
5941   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5942     return ExprError(Diag(BuiltinLoc,
5943                           diag::err_convertvector_non_vector)
5944                      << E->getSourceRange());
5945   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5946     return ExprError(Diag(BuiltinLoc,
5947                           diag::err_convertvector_non_vector_type));
5948 
5949   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5950     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5951     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5952     if (SrcElts != DstElts)
5953       return ExprError(Diag(BuiltinLoc,
5954                             diag::err_convertvector_incompatible_vector)
5955                        << E->getSourceRange());
5956   }
5957 
5958   return new (Context)
5959       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5960 }
5961 
5962 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5963 // This is declared to take (const void*, ...) and can take two
5964 // optional constant int args.
5965 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5966   unsigned NumArgs = TheCall->getNumArgs();
5967 
5968   if (NumArgs > 3)
5969     return Diag(TheCall->getEndLoc(),
5970                 diag::err_typecheck_call_too_many_args_at_most)
5971            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5972 
5973   // Argument 0 is checked for us and the remaining arguments must be
5974   // constant integers.
5975   for (unsigned i = 1; i != NumArgs; ++i)
5976     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5977       return true;
5978 
5979   return false;
5980 }
5981 
5982 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5983 // __assume does not evaluate its arguments, and should warn if its argument
5984 // has side effects.
5985 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5986   Expr *Arg = TheCall->getArg(0);
5987   if (Arg->isInstantiationDependent()) return false;
5988 
5989   if (Arg->HasSideEffects(Context))
5990     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5991         << Arg->getSourceRange()
5992         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5993 
5994   return false;
5995 }
5996 
5997 /// Handle __builtin_alloca_with_align. This is declared
5998 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5999 /// than 8.
6000 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6001   // The alignment must be a constant integer.
6002   Expr *Arg = TheCall->getArg(1);
6003 
6004   // We can't check the value of a dependent argument.
6005   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6006     if (const auto *UE =
6007             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6008       if (UE->getKind() == UETT_AlignOf ||
6009           UE->getKind() == UETT_PreferredAlignOf)
6010         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6011             << Arg->getSourceRange();
6012 
6013     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6014 
6015     if (!Result.isPowerOf2())
6016       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6017              << Arg->getSourceRange();
6018 
6019     if (Result < Context.getCharWidth())
6020       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6021              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6022 
6023     if (Result > std::numeric_limits<int32_t>::max())
6024       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6025              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6026   }
6027 
6028   return false;
6029 }
6030 
6031 /// Handle __builtin_assume_aligned. This is declared
6032 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6033 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6034   unsigned NumArgs = TheCall->getNumArgs();
6035 
6036   if (NumArgs > 3)
6037     return Diag(TheCall->getEndLoc(),
6038                 diag::err_typecheck_call_too_many_args_at_most)
6039            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6040 
6041   // The alignment must be a constant integer.
6042   Expr *Arg = TheCall->getArg(1);
6043 
6044   // We can't check the value of a dependent argument.
6045   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6046     llvm::APSInt Result;
6047     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6048       return true;
6049 
6050     if (!Result.isPowerOf2())
6051       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6052              << Arg->getSourceRange();
6053 
6054     if (Result > Sema::MaximumAlignment)
6055       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6056           << Arg->getSourceRange() << Sema::MaximumAlignment;
6057   }
6058 
6059   if (NumArgs > 2) {
6060     ExprResult Arg(TheCall->getArg(2));
6061     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6062       Context.getSizeType(), false);
6063     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6064     if (Arg.isInvalid()) return true;
6065     TheCall->setArg(2, Arg.get());
6066   }
6067 
6068   return false;
6069 }
6070 
6071 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6072   unsigned BuiltinID =
6073       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6074   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6075 
6076   unsigned NumArgs = TheCall->getNumArgs();
6077   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6078   if (NumArgs < NumRequiredArgs) {
6079     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6080            << 0 /* function call */ << NumRequiredArgs << NumArgs
6081            << TheCall->getSourceRange();
6082   }
6083   if (NumArgs >= NumRequiredArgs + 0x100) {
6084     return Diag(TheCall->getEndLoc(),
6085                 diag::err_typecheck_call_too_many_args_at_most)
6086            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6087            << TheCall->getSourceRange();
6088   }
6089   unsigned i = 0;
6090 
6091   // For formatting call, check buffer arg.
6092   if (!IsSizeCall) {
6093     ExprResult Arg(TheCall->getArg(i));
6094     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6095         Context, Context.VoidPtrTy, false);
6096     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6097     if (Arg.isInvalid())
6098       return true;
6099     TheCall->setArg(i, Arg.get());
6100     i++;
6101   }
6102 
6103   // Check string literal arg.
6104   unsigned FormatIdx = i;
6105   {
6106     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6107     if (Arg.isInvalid())
6108       return true;
6109     TheCall->setArg(i, Arg.get());
6110     i++;
6111   }
6112 
6113   // Make sure variadic args are scalar.
6114   unsigned FirstDataArg = i;
6115   while (i < NumArgs) {
6116     ExprResult Arg = DefaultVariadicArgumentPromotion(
6117         TheCall->getArg(i), VariadicFunction, nullptr);
6118     if (Arg.isInvalid())
6119       return true;
6120     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6121     if (ArgSize.getQuantity() >= 0x100) {
6122       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6123              << i << (int)ArgSize.getQuantity() << 0xff
6124              << TheCall->getSourceRange();
6125     }
6126     TheCall->setArg(i, Arg.get());
6127     i++;
6128   }
6129 
6130   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6131   // call to avoid duplicate diagnostics.
6132   if (!IsSizeCall) {
6133     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6134     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6135     bool Success = CheckFormatArguments(
6136         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6137         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6138         CheckedVarArgs);
6139     if (!Success)
6140       return true;
6141   }
6142 
6143   if (IsSizeCall) {
6144     TheCall->setType(Context.getSizeType());
6145   } else {
6146     TheCall->setType(Context.VoidPtrTy);
6147   }
6148   return false;
6149 }
6150 
6151 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6152 /// TheCall is a constant expression.
6153 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6154                                   llvm::APSInt &Result) {
6155   Expr *Arg = TheCall->getArg(ArgNum);
6156   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6157   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6158 
6159   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6160 
6161   if (!Arg->isIntegerConstantExpr(Result, Context))
6162     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6163            << FDecl->getDeclName() << Arg->getSourceRange();
6164 
6165   return false;
6166 }
6167 
6168 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6169 /// TheCall is a constant expression in the range [Low, High].
6170 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6171                                        int Low, int High, bool RangeIsError) {
6172   if (isConstantEvaluated())
6173     return false;
6174   llvm::APSInt Result;
6175 
6176   // We can't check the value of a dependent argument.
6177   Expr *Arg = TheCall->getArg(ArgNum);
6178   if (Arg->isTypeDependent() || Arg->isValueDependent())
6179     return false;
6180 
6181   // Check constant-ness first.
6182   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6183     return true;
6184 
6185   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6186     if (RangeIsError)
6187       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6188              << Result.toString(10) << Low << High << Arg->getSourceRange();
6189     else
6190       // Defer the warning until we know if the code will be emitted so that
6191       // dead code can ignore this.
6192       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6193                           PDiag(diag::warn_argument_invalid_range)
6194                               << Result.toString(10) << Low << High
6195                               << Arg->getSourceRange());
6196   }
6197 
6198   return false;
6199 }
6200 
6201 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6202 /// TheCall is a constant expression is a multiple of Num..
6203 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6204                                           unsigned Num) {
6205   llvm::APSInt Result;
6206 
6207   // We can't check the value of a dependent argument.
6208   Expr *Arg = TheCall->getArg(ArgNum);
6209   if (Arg->isTypeDependent() || Arg->isValueDependent())
6210     return false;
6211 
6212   // Check constant-ness first.
6213   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6214     return true;
6215 
6216   if (Result.getSExtValue() % Num != 0)
6217     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6218            << Num << Arg->getSourceRange();
6219 
6220   return false;
6221 }
6222 
6223 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6224 /// constant expression representing a power of 2.
6225 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6226   llvm::APSInt Result;
6227 
6228   // We can't check the value of a dependent argument.
6229   Expr *Arg = TheCall->getArg(ArgNum);
6230   if (Arg->isTypeDependent() || Arg->isValueDependent())
6231     return false;
6232 
6233   // Check constant-ness first.
6234   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6235     return true;
6236 
6237   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6238   // and only if x is a power of 2.
6239   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6240     return false;
6241 
6242   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6243          << Arg->getSourceRange();
6244 }
6245 
6246 static bool IsShiftedByte(llvm::APSInt Value) {
6247   if (Value.isNegative())
6248     return false;
6249 
6250   // Check if it's a shifted byte, by shifting it down
6251   while (true) {
6252     // If the value fits in the bottom byte, the check passes.
6253     if (Value < 0x100)
6254       return true;
6255 
6256     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6257     // fails.
6258     if ((Value & 0xFF) != 0)
6259       return false;
6260 
6261     // If the bottom 8 bits are all 0, but something above that is nonzero,
6262     // then shifting the value right by 8 bits won't affect whether it's a
6263     // shifted byte or not. So do that, and go round again.
6264     Value >>= 8;
6265   }
6266 }
6267 
6268 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6269 /// a constant expression representing an arbitrary byte value shifted left by
6270 /// a multiple of 8 bits.
6271 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6272                                              unsigned ArgBits) {
6273   llvm::APSInt Result;
6274 
6275   // We can't check the value of a dependent argument.
6276   Expr *Arg = TheCall->getArg(ArgNum);
6277   if (Arg->isTypeDependent() || Arg->isValueDependent())
6278     return false;
6279 
6280   // Check constant-ness first.
6281   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6282     return true;
6283 
6284   // Truncate to the given size.
6285   Result = Result.getLoBits(ArgBits);
6286   Result.setIsUnsigned(true);
6287 
6288   if (IsShiftedByte(Result))
6289     return false;
6290 
6291   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6292          << Arg->getSourceRange();
6293 }
6294 
6295 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6296 /// TheCall is a constant expression representing either a shifted byte value,
6297 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6298 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6299 /// Arm MVE intrinsics.
6300 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6301                                                    int ArgNum,
6302                                                    unsigned ArgBits) {
6303   llvm::APSInt Result;
6304 
6305   // We can't check the value of a dependent argument.
6306   Expr *Arg = TheCall->getArg(ArgNum);
6307   if (Arg->isTypeDependent() || Arg->isValueDependent())
6308     return false;
6309 
6310   // Check constant-ness first.
6311   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6312     return true;
6313 
6314   // Truncate to the given size.
6315   Result = Result.getLoBits(ArgBits);
6316   Result.setIsUnsigned(true);
6317 
6318   // Check to see if it's in either of the required forms.
6319   if (IsShiftedByte(Result) ||
6320       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6321     return false;
6322 
6323   return Diag(TheCall->getBeginLoc(),
6324               diag::err_argument_not_shifted_byte_or_xxff)
6325          << Arg->getSourceRange();
6326 }
6327 
6328 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6329 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6330   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6331     if (checkArgCount(*this, TheCall, 2))
6332       return true;
6333     Expr *Arg0 = TheCall->getArg(0);
6334     Expr *Arg1 = TheCall->getArg(1);
6335 
6336     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6337     if (FirstArg.isInvalid())
6338       return true;
6339     QualType FirstArgType = FirstArg.get()->getType();
6340     if (!FirstArgType->isAnyPointerType())
6341       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6342                << "first" << FirstArgType << Arg0->getSourceRange();
6343     TheCall->setArg(0, FirstArg.get());
6344 
6345     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6346     if (SecArg.isInvalid())
6347       return true;
6348     QualType SecArgType = SecArg.get()->getType();
6349     if (!SecArgType->isIntegerType())
6350       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6351                << "second" << SecArgType << Arg1->getSourceRange();
6352 
6353     // Derive the return type from the pointer argument.
6354     TheCall->setType(FirstArgType);
6355     return false;
6356   }
6357 
6358   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6359     if (checkArgCount(*this, TheCall, 2))
6360       return true;
6361 
6362     Expr *Arg0 = TheCall->getArg(0);
6363     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6364     if (FirstArg.isInvalid())
6365       return true;
6366     QualType FirstArgType = FirstArg.get()->getType();
6367     if (!FirstArgType->isAnyPointerType())
6368       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6369                << "first" << FirstArgType << Arg0->getSourceRange();
6370     TheCall->setArg(0, FirstArg.get());
6371 
6372     // Derive the return type from the pointer argument.
6373     TheCall->setType(FirstArgType);
6374 
6375     // Second arg must be an constant in range [0,15]
6376     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6377   }
6378 
6379   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6380     if (checkArgCount(*this, TheCall, 2))
6381       return true;
6382     Expr *Arg0 = TheCall->getArg(0);
6383     Expr *Arg1 = TheCall->getArg(1);
6384 
6385     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6386     if (FirstArg.isInvalid())
6387       return true;
6388     QualType FirstArgType = FirstArg.get()->getType();
6389     if (!FirstArgType->isAnyPointerType())
6390       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6391                << "first" << FirstArgType << Arg0->getSourceRange();
6392 
6393     QualType SecArgType = Arg1->getType();
6394     if (!SecArgType->isIntegerType())
6395       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6396                << "second" << SecArgType << Arg1->getSourceRange();
6397     TheCall->setType(Context.IntTy);
6398     return false;
6399   }
6400 
6401   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6402       BuiltinID == AArch64::BI__builtin_arm_stg) {
6403     if (checkArgCount(*this, TheCall, 1))
6404       return true;
6405     Expr *Arg0 = TheCall->getArg(0);
6406     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6407     if (FirstArg.isInvalid())
6408       return true;
6409 
6410     QualType FirstArgType = FirstArg.get()->getType();
6411     if (!FirstArgType->isAnyPointerType())
6412       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6413                << "first" << FirstArgType << Arg0->getSourceRange();
6414     TheCall->setArg(0, FirstArg.get());
6415 
6416     // Derive the return type from the pointer argument.
6417     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6418       TheCall->setType(FirstArgType);
6419     return false;
6420   }
6421 
6422   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6423     Expr *ArgA = TheCall->getArg(0);
6424     Expr *ArgB = TheCall->getArg(1);
6425 
6426     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6427     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6428 
6429     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6430       return true;
6431 
6432     QualType ArgTypeA = ArgExprA.get()->getType();
6433     QualType ArgTypeB = ArgExprB.get()->getType();
6434 
6435     auto isNull = [&] (Expr *E) -> bool {
6436       return E->isNullPointerConstant(
6437                         Context, Expr::NPC_ValueDependentIsNotNull); };
6438 
6439     // argument should be either a pointer or null
6440     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6441       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6442         << "first" << ArgTypeA << ArgA->getSourceRange();
6443 
6444     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6445       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6446         << "second" << ArgTypeB << ArgB->getSourceRange();
6447 
6448     // Ensure Pointee types are compatible
6449     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6450         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6451       QualType pointeeA = ArgTypeA->getPointeeType();
6452       QualType pointeeB = ArgTypeB->getPointeeType();
6453       if (!Context.typesAreCompatible(
6454              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6455              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6456         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6457           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6458           << ArgB->getSourceRange();
6459       }
6460     }
6461 
6462     // at least one argument should be pointer type
6463     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6464       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6465         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6466 
6467     if (isNull(ArgA)) // adopt type of the other pointer
6468       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6469 
6470     if (isNull(ArgB))
6471       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6472 
6473     TheCall->setArg(0, ArgExprA.get());
6474     TheCall->setArg(1, ArgExprB.get());
6475     TheCall->setType(Context.LongLongTy);
6476     return false;
6477   }
6478   assert(false && "Unhandled ARM MTE intrinsic");
6479   return true;
6480 }
6481 
6482 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6483 /// TheCall is an ARM/AArch64 special register string literal.
6484 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6485                                     int ArgNum, unsigned ExpectedFieldNum,
6486                                     bool AllowName) {
6487   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6488                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6489                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6490                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6491                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6492                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6493   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6494                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6495                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6496                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6497                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6498                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6499   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6500 
6501   // We can't check the value of a dependent argument.
6502   Expr *Arg = TheCall->getArg(ArgNum);
6503   if (Arg->isTypeDependent() || Arg->isValueDependent())
6504     return false;
6505 
6506   // Check if the argument is a string literal.
6507   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6508     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6509            << Arg->getSourceRange();
6510 
6511   // Check the type of special register given.
6512   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6513   SmallVector<StringRef, 6> Fields;
6514   Reg.split(Fields, ":");
6515 
6516   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6517     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6518            << Arg->getSourceRange();
6519 
6520   // If the string is the name of a register then we cannot check that it is
6521   // valid here but if the string is of one the forms described in ACLE then we
6522   // can check that the supplied fields are integers and within the valid
6523   // ranges.
6524   if (Fields.size() > 1) {
6525     bool FiveFields = Fields.size() == 5;
6526 
6527     bool ValidString = true;
6528     if (IsARMBuiltin) {
6529       ValidString &= Fields[0].startswith_lower("cp") ||
6530                      Fields[0].startswith_lower("p");
6531       if (ValidString)
6532         Fields[0] =
6533           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6534 
6535       ValidString &= Fields[2].startswith_lower("c");
6536       if (ValidString)
6537         Fields[2] = Fields[2].drop_front(1);
6538 
6539       if (FiveFields) {
6540         ValidString &= Fields[3].startswith_lower("c");
6541         if (ValidString)
6542           Fields[3] = Fields[3].drop_front(1);
6543       }
6544     }
6545 
6546     SmallVector<int, 5> Ranges;
6547     if (FiveFields)
6548       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6549     else
6550       Ranges.append({15, 7, 15});
6551 
6552     for (unsigned i=0; i<Fields.size(); ++i) {
6553       int IntField;
6554       ValidString &= !Fields[i].getAsInteger(10, IntField);
6555       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6556     }
6557 
6558     if (!ValidString)
6559       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6560              << Arg->getSourceRange();
6561   } else if (IsAArch64Builtin && Fields.size() == 1) {
6562     // If the register name is one of those that appear in the condition below
6563     // and the special register builtin being used is one of the write builtins,
6564     // then we require that the argument provided for writing to the register
6565     // is an integer constant expression. This is because it will be lowered to
6566     // an MSR (immediate) instruction, so we need to know the immediate at
6567     // compile time.
6568     if (TheCall->getNumArgs() != 2)
6569       return false;
6570 
6571     std::string RegLower = Reg.lower();
6572     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6573         RegLower != "pan" && RegLower != "uao")
6574       return false;
6575 
6576     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6577   }
6578 
6579   return false;
6580 }
6581 
6582 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6583 /// This checks that the target supports __builtin_longjmp and
6584 /// that val is a constant 1.
6585 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6586   if (!Context.getTargetInfo().hasSjLjLowering())
6587     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6588            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6589 
6590   Expr *Arg = TheCall->getArg(1);
6591   llvm::APSInt Result;
6592 
6593   // TODO: This is less than ideal. Overload this to take a value.
6594   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6595     return true;
6596 
6597   if (Result != 1)
6598     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6599            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6600 
6601   return false;
6602 }
6603 
6604 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6605 /// This checks that the target supports __builtin_setjmp.
6606 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6607   if (!Context.getTargetInfo().hasSjLjLowering())
6608     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6609            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6610   return false;
6611 }
6612 
6613 namespace {
6614 
6615 class UncoveredArgHandler {
6616   enum { Unknown = -1, AllCovered = -2 };
6617 
6618   signed FirstUncoveredArg = Unknown;
6619   SmallVector<const Expr *, 4> DiagnosticExprs;
6620 
6621 public:
6622   UncoveredArgHandler() = default;
6623 
6624   bool hasUncoveredArg() const {
6625     return (FirstUncoveredArg >= 0);
6626   }
6627 
6628   unsigned getUncoveredArg() const {
6629     assert(hasUncoveredArg() && "no uncovered argument");
6630     return FirstUncoveredArg;
6631   }
6632 
6633   void setAllCovered() {
6634     // A string has been found with all arguments covered, so clear out
6635     // the diagnostics.
6636     DiagnosticExprs.clear();
6637     FirstUncoveredArg = AllCovered;
6638   }
6639 
6640   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6641     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6642 
6643     // Don't update if a previous string covers all arguments.
6644     if (FirstUncoveredArg == AllCovered)
6645       return;
6646 
6647     // UncoveredArgHandler tracks the highest uncovered argument index
6648     // and with it all the strings that match this index.
6649     if (NewFirstUncoveredArg == FirstUncoveredArg)
6650       DiagnosticExprs.push_back(StrExpr);
6651     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6652       DiagnosticExprs.clear();
6653       DiagnosticExprs.push_back(StrExpr);
6654       FirstUncoveredArg = NewFirstUncoveredArg;
6655     }
6656   }
6657 
6658   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6659 };
6660 
6661 enum StringLiteralCheckType {
6662   SLCT_NotALiteral,
6663   SLCT_UncheckedLiteral,
6664   SLCT_CheckedLiteral
6665 };
6666 
6667 } // namespace
6668 
6669 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6670                                      BinaryOperatorKind BinOpKind,
6671                                      bool AddendIsRight) {
6672   unsigned BitWidth = Offset.getBitWidth();
6673   unsigned AddendBitWidth = Addend.getBitWidth();
6674   // There might be negative interim results.
6675   if (Addend.isUnsigned()) {
6676     Addend = Addend.zext(++AddendBitWidth);
6677     Addend.setIsSigned(true);
6678   }
6679   // Adjust the bit width of the APSInts.
6680   if (AddendBitWidth > BitWidth) {
6681     Offset = Offset.sext(AddendBitWidth);
6682     BitWidth = AddendBitWidth;
6683   } else if (BitWidth > AddendBitWidth) {
6684     Addend = Addend.sext(BitWidth);
6685   }
6686 
6687   bool Ov = false;
6688   llvm::APSInt ResOffset = Offset;
6689   if (BinOpKind == BO_Add)
6690     ResOffset = Offset.sadd_ov(Addend, Ov);
6691   else {
6692     assert(AddendIsRight && BinOpKind == BO_Sub &&
6693            "operator must be add or sub with addend on the right");
6694     ResOffset = Offset.ssub_ov(Addend, Ov);
6695   }
6696 
6697   // We add an offset to a pointer here so we should support an offset as big as
6698   // possible.
6699   if (Ov) {
6700     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6701            "index (intermediate) result too big");
6702     Offset = Offset.sext(2 * BitWidth);
6703     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6704     return;
6705   }
6706 
6707   Offset = ResOffset;
6708 }
6709 
6710 namespace {
6711 
6712 // This is a wrapper class around StringLiteral to support offsetted string
6713 // literals as format strings. It takes the offset into account when returning
6714 // the string and its length or the source locations to display notes correctly.
6715 class FormatStringLiteral {
6716   const StringLiteral *FExpr;
6717   int64_t Offset;
6718 
6719  public:
6720   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6721       : FExpr(fexpr), Offset(Offset) {}
6722 
6723   StringRef getString() const {
6724     return FExpr->getString().drop_front(Offset);
6725   }
6726 
6727   unsigned getByteLength() const {
6728     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6729   }
6730 
6731   unsigned getLength() const { return FExpr->getLength() - Offset; }
6732   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6733 
6734   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6735 
6736   QualType getType() const { return FExpr->getType(); }
6737 
6738   bool isAscii() const { return FExpr->isAscii(); }
6739   bool isWide() const { return FExpr->isWide(); }
6740   bool isUTF8() const { return FExpr->isUTF8(); }
6741   bool isUTF16() const { return FExpr->isUTF16(); }
6742   bool isUTF32() const { return FExpr->isUTF32(); }
6743   bool isPascal() const { return FExpr->isPascal(); }
6744 
6745   SourceLocation getLocationOfByte(
6746       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6747       const TargetInfo &Target, unsigned *StartToken = nullptr,
6748       unsigned *StartTokenByteOffset = nullptr) const {
6749     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6750                                     StartToken, StartTokenByteOffset);
6751   }
6752 
6753   SourceLocation getBeginLoc() const LLVM_READONLY {
6754     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6755   }
6756 
6757   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6758 };
6759 
6760 }  // namespace
6761 
6762 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6763                               const Expr *OrigFormatExpr,
6764                               ArrayRef<const Expr *> Args,
6765                               bool HasVAListArg, unsigned format_idx,
6766                               unsigned firstDataArg,
6767                               Sema::FormatStringType Type,
6768                               bool inFunctionCall,
6769                               Sema::VariadicCallType CallType,
6770                               llvm::SmallBitVector &CheckedVarArgs,
6771                               UncoveredArgHandler &UncoveredArg,
6772                               bool IgnoreStringsWithoutSpecifiers);
6773 
6774 // Determine if an expression is a string literal or constant string.
6775 // If this function returns false on the arguments to a function expecting a
6776 // format string, we will usually need to emit a warning.
6777 // True string literals are then checked by CheckFormatString.
6778 static StringLiteralCheckType
6779 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6780                       bool HasVAListArg, unsigned format_idx,
6781                       unsigned firstDataArg, Sema::FormatStringType Type,
6782                       Sema::VariadicCallType CallType, bool InFunctionCall,
6783                       llvm::SmallBitVector &CheckedVarArgs,
6784                       UncoveredArgHandler &UncoveredArg,
6785                       llvm::APSInt Offset,
6786                       bool IgnoreStringsWithoutSpecifiers = false) {
6787   if (S.isConstantEvaluated())
6788     return SLCT_NotALiteral;
6789  tryAgain:
6790   assert(Offset.isSigned() && "invalid offset");
6791 
6792   if (E->isTypeDependent() || E->isValueDependent())
6793     return SLCT_NotALiteral;
6794 
6795   E = E->IgnoreParenCasts();
6796 
6797   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6798     // Technically -Wformat-nonliteral does not warn about this case.
6799     // The behavior of printf and friends in this case is implementation
6800     // dependent.  Ideally if the format string cannot be null then
6801     // it should have a 'nonnull' attribute in the function prototype.
6802     return SLCT_UncheckedLiteral;
6803 
6804   switch (E->getStmtClass()) {
6805   case Stmt::BinaryConditionalOperatorClass:
6806   case Stmt::ConditionalOperatorClass: {
6807     // The expression is a literal if both sub-expressions were, and it was
6808     // completely checked only if both sub-expressions were checked.
6809     const AbstractConditionalOperator *C =
6810         cast<AbstractConditionalOperator>(E);
6811 
6812     // Determine whether it is necessary to check both sub-expressions, for
6813     // example, because the condition expression is a constant that can be
6814     // evaluated at compile time.
6815     bool CheckLeft = true, CheckRight = true;
6816 
6817     bool Cond;
6818     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6819                                                  S.isConstantEvaluated())) {
6820       if (Cond)
6821         CheckRight = false;
6822       else
6823         CheckLeft = false;
6824     }
6825 
6826     // We need to maintain the offsets for the right and the left hand side
6827     // separately to check if every possible indexed expression is a valid
6828     // string literal. They might have different offsets for different string
6829     // literals in the end.
6830     StringLiteralCheckType Left;
6831     if (!CheckLeft)
6832       Left = SLCT_UncheckedLiteral;
6833     else {
6834       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6835                                    HasVAListArg, format_idx, firstDataArg,
6836                                    Type, CallType, InFunctionCall,
6837                                    CheckedVarArgs, UncoveredArg, Offset,
6838                                    IgnoreStringsWithoutSpecifiers);
6839       if (Left == SLCT_NotALiteral || !CheckRight) {
6840         return Left;
6841       }
6842     }
6843 
6844     StringLiteralCheckType Right = checkFormatStringExpr(
6845         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6846         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6847         IgnoreStringsWithoutSpecifiers);
6848 
6849     return (CheckLeft && Left < Right) ? Left : Right;
6850   }
6851 
6852   case Stmt::ImplicitCastExprClass:
6853     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6854     goto tryAgain;
6855 
6856   case Stmt::OpaqueValueExprClass:
6857     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6858       E = src;
6859       goto tryAgain;
6860     }
6861     return SLCT_NotALiteral;
6862 
6863   case Stmt::PredefinedExprClass:
6864     // While __func__, etc., are technically not string literals, they
6865     // cannot contain format specifiers and thus are not a security
6866     // liability.
6867     return SLCT_UncheckedLiteral;
6868 
6869   case Stmt::DeclRefExprClass: {
6870     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6871 
6872     // As an exception, do not flag errors for variables binding to
6873     // const string literals.
6874     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6875       bool isConstant = false;
6876       QualType T = DR->getType();
6877 
6878       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6879         isConstant = AT->getElementType().isConstant(S.Context);
6880       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6881         isConstant = T.isConstant(S.Context) &&
6882                      PT->getPointeeType().isConstant(S.Context);
6883       } else if (T->isObjCObjectPointerType()) {
6884         // In ObjC, there is usually no "const ObjectPointer" type,
6885         // so don't check if the pointee type is constant.
6886         isConstant = T.isConstant(S.Context);
6887       }
6888 
6889       if (isConstant) {
6890         if (const Expr *Init = VD->getAnyInitializer()) {
6891           // Look through initializers like const char c[] = { "foo" }
6892           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6893             if (InitList->isStringLiteralInit())
6894               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6895           }
6896           return checkFormatStringExpr(S, Init, Args,
6897                                        HasVAListArg, format_idx,
6898                                        firstDataArg, Type, CallType,
6899                                        /*InFunctionCall*/ false, CheckedVarArgs,
6900                                        UncoveredArg, Offset);
6901         }
6902       }
6903 
6904       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6905       // special check to see if the format string is a function parameter
6906       // of the function calling the printf function.  If the function
6907       // has an attribute indicating it is a printf-like function, then we
6908       // should suppress warnings concerning non-literals being used in a call
6909       // to a vprintf function.  For example:
6910       //
6911       // void
6912       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6913       //      va_list ap;
6914       //      va_start(ap, fmt);
6915       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6916       //      ...
6917       // }
6918       if (HasVAListArg) {
6919         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6920           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6921             int PVIndex = PV->getFunctionScopeIndex() + 1;
6922             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6923               // adjust for implicit parameter
6924               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6925                 if (MD->isInstance())
6926                   ++PVIndex;
6927               // We also check if the formats are compatible.
6928               // We can't pass a 'scanf' string to a 'printf' function.
6929               if (PVIndex == PVFormat->getFormatIdx() &&
6930                   Type == S.GetFormatStringType(PVFormat))
6931                 return SLCT_UncheckedLiteral;
6932             }
6933           }
6934         }
6935       }
6936     }
6937 
6938     return SLCT_NotALiteral;
6939   }
6940 
6941   case Stmt::CallExprClass:
6942   case Stmt::CXXMemberCallExprClass: {
6943     const CallExpr *CE = cast<CallExpr>(E);
6944     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6945       bool IsFirst = true;
6946       StringLiteralCheckType CommonResult;
6947       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6948         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6949         StringLiteralCheckType Result = checkFormatStringExpr(
6950             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6951             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6952             IgnoreStringsWithoutSpecifiers);
6953         if (IsFirst) {
6954           CommonResult = Result;
6955           IsFirst = false;
6956         }
6957       }
6958       if (!IsFirst)
6959         return CommonResult;
6960 
6961       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6962         unsigned BuiltinID = FD->getBuiltinID();
6963         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6964             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6965           const Expr *Arg = CE->getArg(0);
6966           return checkFormatStringExpr(S, Arg, Args,
6967                                        HasVAListArg, format_idx,
6968                                        firstDataArg, Type, CallType,
6969                                        InFunctionCall, CheckedVarArgs,
6970                                        UncoveredArg, Offset,
6971                                        IgnoreStringsWithoutSpecifiers);
6972         }
6973       }
6974     }
6975 
6976     return SLCT_NotALiteral;
6977   }
6978   case Stmt::ObjCMessageExprClass: {
6979     const auto *ME = cast<ObjCMessageExpr>(E);
6980     if (const auto *MD = ME->getMethodDecl()) {
6981       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6982         // As a special case heuristic, if we're using the method -[NSBundle
6983         // localizedStringForKey:value:table:], ignore any key strings that lack
6984         // format specifiers. The idea is that if the key doesn't have any
6985         // format specifiers then its probably just a key to map to the
6986         // localized strings. If it does have format specifiers though, then its
6987         // likely that the text of the key is the format string in the
6988         // programmer's language, and should be checked.
6989         const ObjCInterfaceDecl *IFace;
6990         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6991             IFace->getIdentifier()->isStr("NSBundle") &&
6992             MD->getSelector().isKeywordSelector(
6993                 {"localizedStringForKey", "value", "table"})) {
6994           IgnoreStringsWithoutSpecifiers = true;
6995         }
6996 
6997         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6998         return checkFormatStringExpr(
6999             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7000             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7001             IgnoreStringsWithoutSpecifiers);
7002       }
7003     }
7004 
7005     return SLCT_NotALiteral;
7006   }
7007   case Stmt::ObjCStringLiteralClass:
7008   case Stmt::StringLiteralClass: {
7009     const StringLiteral *StrE = nullptr;
7010 
7011     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7012       StrE = ObjCFExpr->getString();
7013     else
7014       StrE = cast<StringLiteral>(E);
7015 
7016     if (StrE) {
7017       if (Offset.isNegative() || Offset > StrE->getLength()) {
7018         // TODO: It would be better to have an explicit warning for out of
7019         // bounds literals.
7020         return SLCT_NotALiteral;
7021       }
7022       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7023       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7024                         firstDataArg, Type, InFunctionCall, CallType,
7025                         CheckedVarArgs, UncoveredArg,
7026                         IgnoreStringsWithoutSpecifiers);
7027       return SLCT_CheckedLiteral;
7028     }
7029 
7030     return SLCT_NotALiteral;
7031   }
7032   case Stmt::BinaryOperatorClass: {
7033     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7034 
7035     // A string literal + an int offset is still a string literal.
7036     if (BinOp->isAdditiveOp()) {
7037       Expr::EvalResult LResult, RResult;
7038 
7039       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7040           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7041       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7042           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7043 
7044       if (LIsInt != RIsInt) {
7045         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7046 
7047         if (LIsInt) {
7048           if (BinOpKind == BO_Add) {
7049             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7050             E = BinOp->getRHS();
7051             goto tryAgain;
7052           }
7053         } else {
7054           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7055           E = BinOp->getLHS();
7056           goto tryAgain;
7057         }
7058       }
7059     }
7060 
7061     return SLCT_NotALiteral;
7062   }
7063   case Stmt::UnaryOperatorClass: {
7064     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7065     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7066     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7067       Expr::EvalResult IndexResult;
7068       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7069                                        Expr::SE_NoSideEffects,
7070                                        S.isConstantEvaluated())) {
7071         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7072                    /*RHS is int*/ true);
7073         E = ASE->getBase();
7074         goto tryAgain;
7075       }
7076     }
7077 
7078     return SLCT_NotALiteral;
7079   }
7080 
7081   default:
7082     return SLCT_NotALiteral;
7083   }
7084 }
7085 
7086 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7087   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7088       .Case("scanf", FST_Scanf)
7089       .Cases("printf", "printf0", FST_Printf)
7090       .Cases("NSString", "CFString", FST_NSString)
7091       .Case("strftime", FST_Strftime)
7092       .Case("strfmon", FST_Strfmon)
7093       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7094       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7095       .Case("os_trace", FST_OSLog)
7096       .Case("os_log", FST_OSLog)
7097       .Default(FST_Unknown);
7098 }
7099 
7100 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7101 /// functions) for correct use of format strings.
7102 /// Returns true if a format string has been fully checked.
7103 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7104                                 ArrayRef<const Expr *> Args,
7105                                 bool IsCXXMember,
7106                                 VariadicCallType CallType,
7107                                 SourceLocation Loc, SourceRange Range,
7108                                 llvm::SmallBitVector &CheckedVarArgs) {
7109   FormatStringInfo FSI;
7110   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7111     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7112                                 FSI.FirstDataArg, GetFormatStringType(Format),
7113                                 CallType, Loc, Range, CheckedVarArgs);
7114   return false;
7115 }
7116 
7117 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7118                                 bool HasVAListArg, unsigned format_idx,
7119                                 unsigned firstDataArg, FormatStringType Type,
7120                                 VariadicCallType CallType,
7121                                 SourceLocation Loc, SourceRange Range,
7122                                 llvm::SmallBitVector &CheckedVarArgs) {
7123   // CHECK: printf/scanf-like function is called with no format string.
7124   if (format_idx >= Args.size()) {
7125     Diag(Loc, diag::warn_missing_format_string) << Range;
7126     return false;
7127   }
7128 
7129   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7130 
7131   // CHECK: format string is not a string literal.
7132   //
7133   // Dynamically generated format strings are difficult to
7134   // automatically vet at compile time.  Requiring that format strings
7135   // are string literals: (1) permits the checking of format strings by
7136   // the compiler and thereby (2) can practically remove the source of
7137   // many format string exploits.
7138 
7139   // Format string can be either ObjC string (e.g. @"%d") or
7140   // C string (e.g. "%d")
7141   // ObjC string uses the same format specifiers as C string, so we can use
7142   // the same format string checking logic for both ObjC and C strings.
7143   UncoveredArgHandler UncoveredArg;
7144   StringLiteralCheckType CT =
7145       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7146                             format_idx, firstDataArg, Type, CallType,
7147                             /*IsFunctionCall*/ true, CheckedVarArgs,
7148                             UncoveredArg,
7149                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7150 
7151   // Generate a diagnostic where an uncovered argument is detected.
7152   if (UncoveredArg.hasUncoveredArg()) {
7153     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7154     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7155     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7156   }
7157 
7158   if (CT != SLCT_NotALiteral)
7159     // Literal format string found, check done!
7160     return CT == SLCT_CheckedLiteral;
7161 
7162   // Strftime is particular as it always uses a single 'time' argument,
7163   // so it is safe to pass a non-literal string.
7164   if (Type == FST_Strftime)
7165     return false;
7166 
7167   // Do not emit diag when the string param is a macro expansion and the
7168   // format is either NSString or CFString. This is a hack to prevent
7169   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7170   // which are usually used in place of NS and CF string literals.
7171   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7172   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7173     return false;
7174 
7175   // If there are no arguments specified, warn with -Wformat-security, otherwise
7176   // warn only with -Wformat-nonliteral.
7177   if (Args.size() == firstDataArg) {
7178     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7179       << OrigFormatExpr->getSourceRange();
7180     switch (Type) {
7181     default:
7182       break;
7183     case FST_Kprintf:
7184     case FST_FreeBSDKPrintf:
7185     case FST_Printf:
7186       Diag(FormatLoc, diag::note_format_security_fixit)
7187         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7188       break;
7189     case FST_NSString:
7190       Diag(FormatLoc, diag::note_format_security_fixit)
7191         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7192       break;
7193     }
7194   } else {
7195     Diag(FormatLoc, diag::warn_format_nonliteral)
7196       << OrigFormatExpr->getSourceRange();
7197   }
7198   return false;
7199 }
7200 
7201 namespace {
7202 
7203 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7204 protected:
7205   Sema &S;
7206   const FormatStringLiteral *FExpr;
7207   const Expr *OrigFormatExpr;
7208   const Sema::FormatStringType FSType;
7209   const unsigned FirstDataArg;
7210   const unsigned NumDataArgs;
7211   const char *Beg; // Start of format string.
7212   const bool HasVAListArg;
7213   ArrayRef<const Expr *> Args;
7214   unsigned FormatIdx;
7215   llvm::SmallBitVector CoveredArgs;
7216   bool usesPositionalArgs = false;
7217   bool atFirstArg = true;
7218   bool inFunctionCall;
7219   Sema::VariadicCallType CallType;
7220   llvm::SmallBitVector &CheckedVarArgs;
7221   UncoveredArgHandler &UncoveredArg;
7222 
7223 public:
7224   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7225                      const Expr *origFormatExpr,
7226                      const Sema::FormatStringType type, unsigned firstDataArg,
7227                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7228                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7229                      bool inFunctionCall, Sema::VariadicCallType callType,
7230                      llvm::SmallBitVector &CheckedVarArgs,
7231                      UncoveredArgHandler &UncoveredArg)
7232       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7233         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7234         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7235         inFunctionCall(inFunctionCall), CallType(callType),
7236         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7237     CoveredArgs.resize(numDataArgs);
7238     CoveredArgs.reset();
7239   }
7240 
7241   void DoneProcessing();
7242 
7243   void HandleIncompleteSpecifier(const char *startSpecifier,
7244                                  unsigned specifierLen) override;
7245 
7246   void HandleInvalidLengthModifier(
7247                            const analyze_format_string::FormatSpecifier &FS,
7248                            const analyze_format_string::ConversionSpecifier &CS,
7249                            const char *startSpecifier, unsigned specifierLen,
7250                            unsigned DiagID);
7251 
7252   void HandleNonStandardLengthModifier(
7253                     const analyze_format_string::FormatSpecifier &FS,
7254                     const char *startSpecifier, unsigned specifierLen);
7255 
7256   void HandleNonStandardConversionSpecifier(
7257                     const analyze_format_string::ConversionSpecifier &CS,
7258                     const char *startSpecifier, unsigned specifierLen);
7259 
7260   void HandlePosition(const char *startPos, unsigned posLen) override;
7261 
7262   void HandleInvalidPosition(const char *startSpecifier,
7263                              unsigned specifierLen,
7264                              analyze_format_string::PositionContext p) override;
7265 
7266   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7267 
7268   void HandleNullChar(const char *nullCharacter) override;
7269 
7270   template <typename Range>
7271   static void
7272   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7273                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7274                        bool IsStringLocation, Range StringRange,
7275                        ArrayRef<FixItHint> Fixit = None);
7276 
7277 protected:
7278   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7279                                         const char *startSpec,
7280                                         unsigned specifierLen,
7281                                         const char *csStart, unsigned csLen);
7282 
7283   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7284                                          const char *startSpec,
7285                                          unsigned specifierLen);
7286 
7287   SourceRange getFormatStringRange();
7288   CharSourceRange getSpecifierRange(const char *startSpecifier,
7289                                     unsigned specifierLen);
7290   SourceLocation getLocationOfByte(const char *x);
7291 
7292   const Expr *getDataArg(unsigned i) const;
7293 
7294   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7295                     const analyze_format_string::ConversionSpecifier &CS,
7296                     const char *startSpecifier, unsigned specifierLen,
7297                     unsigned argIndex);
7298 
7299   template <typename Range>
7300   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7301                             bool IsStringLocation, Range StringRange,
7302                             ArrayRef<FixItHint> Fixit = None);
7303 };
7304 
7305 } // namespace
7306 
7307 SourceRange CheckFormatHandler::getFormatStringRange() {
7308   return OrigFormatExpr->getSourceRange();
7309 }
7310 
7311 CharSourceRange CheckFormatHandler::
7312 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7313   SourceLocation Start = getLocationOfByte(startSpecifier);
7314   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7315 
7316   // Advance the end SourceLocation by one due to half-open ranges.
7317   End = End.getLocWithOffset(1);
7318 
7319   return CharSourceRange::getCharRange(Start, End);
7320 }
7321 
7322 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7323   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7324                                   S.getLangOpts(), S.Context.getTargetInfo());
7325 }
7326 
7327 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7328                                                    unsigned specifierLen){
7329   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7330                        getLocationOfByte(startSpecifier),
7331                        /*IsStringLocation*/true,
7332                        getSpecifierRange(startSpecifier, specifierLen));
7333 }
7334 
7335 void CheckFormatHandler::HandleInvalidLengthModifier(
7336     const analyze_format_string::FormatSpecifier &FS,
7337     const analyze_format_string::ConversionSpecifier &CS,
7338     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7339   using namespace analyze_format_string;
7340 
7341   const LengthModifier &LM = FS.getLengthModifier();
7342   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7343 
7344   // See if we know how to fix this length modifier.
7345   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7346   if (FixedLM) {
7347     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7348                          getLocationOfByte(LM.getStart()),
7349                          /*IsStringLocation*/true,
7350                          getSpecifierRange(startSpecifier, specifierLen));
7351 
7352     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7353       << FixedLM->toString()
7354       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7355 
7356   } else {
7357     FixItHint Hint;
7358     if (DiagID == diag::warn_format_nonsensical_length)
7359       Hint = FixItHint::CreateRemoval(LMRange);
7360 
7361     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7362                          getLocationOfByte(LM.getStart()),
7363                          /*IsStringLocation*/true,
7364                          getSpecifierRange(startSpecifier, specifierLen),
7365                          Hint);
7366   }
7367 }
7368 
7369 void CheckFormatHandler::HandleNonStandardLengthModifier(
7370     const analyze_format_string::FormatSpecifier &FS,
7371     const char *startSpecifier, unsigned specifierLen) {
7372   using namespace analyze_format_string;
7373 
7374   const LengthModifier &LM = FS.getLengthModifier();
7375   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7376 
7377   // See if we know how to fix this length modifier.
7378   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7379   if (FixedLM) {
7380     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7381                            << LM.toString() << 0,
7382                          getLocationOfByte(LM.getStart()),
7383                          /*IsStringLocation*/true,
7384                          getSpecifierRange(startSpecifier, specifierLen));
7385 
7386     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7387       << FixedLM->toString()
7388       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7389 
7390   } else {
7391     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7392                            << LM.toString() << 0,
7393                          getLocationOfByte(LM.getStart()),
7394                          /*IsStringLocation*/true,
7395                          getSpecifierRange(startSpecifier, specifierLen));
7396   }
7397 }
7398 
7399 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7400     const analyze_format_string::ConversionSpecifier &CS,
7401     const char *startSpecifier, unsigned specifierLen) {
7402   using namespace analyze_format_string;
7403 
7404   // See if we know how to fix this conversion specifier.
7405   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7406   if (FixedCS) {
7407     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7408                           << CS.toString() << /*conversion specifier*/1,
7409                          getLocationOfByte(CS.getStart()),
7410                          /*IsStringLocation*/true,
7411                          getSpecifierRange(startSpecifier, specifierLen));
7412 
7413     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7414     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7415       << FixedCS->toString()
7416       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7417   } else {
7418     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7419                           << CS.toString() << /*conversion specifier*/1,
7420                          getLocationOfByte(CS.getStart()),
7421                          /*IsStringLocation*/true,
7422                          getSpecifierRange(startSpecifier, specifierLen));
7423   }
7424 }
7425 
7426 void CheckFormatHandler::HandlePosition(const char *startPos,
7427                                         unsigned posLen) {
7428   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7429                                getLocationOfByte(startPos),
7430                                /*IsStringLocation*/true,
7431                                getSpecifierRange(startPos, posLen));
7432 }
7433 
7434 void
7435 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7436                                      analyze_format_string::PositionContext p) {
7437   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7438                          << (unsigned) p,
7439                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7440                        getSpecifierRange(startPos, posLen));
7441 }
7442 
7443 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7444                                             unsigned posLen) {
7445   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7446                                getLocationOfByte(startPos),
7447                                /*IsStringLocation*/true,
7448                                getSpecifierRange(startPos, posLen));
7449 }
7450 
7451 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7452   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7453     // The presence of a null character is likely an error.
7454     EmitFormatDiagnostic(
7455       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7456       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7457       getFormatStringRange());
7458   }
7459 }
7460 
7461 // Note that this may return NULL if there was an error parsing or building
7462 // one of the argument expressions.
7463 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7464   return Args[FirstDataArg + i];
7465 }
7466 
7467 void CheckFormatHandler::DoneProcessing() {
7468   // Does the number of data arguments exceed the number of
7469   // format conversions in the format string?
7470   if (!HasVAListArg) {
7471       // Find any arguments that weren't covered.
7472     CoveredArgs.flip();
7473     signed notCoveredArg = CoveredArgs.find_first();
7474     if (notCoveredArg >= 0) {
7475       assert((unsigned)notCoveredArg < NumDataArgs);
7476       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7477     } else {
7478       UncoveredArg.setAllCovered();
7479     }
7480   }
7481 }
7482 
7483 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7484                                    const Expr *ArgExpr) {
7485   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7486          "Invalid state");
7487 
7488   if (!ArgExpr)
7489     return;
7490 
7491   SourceLocation Loc = ArgExpr->getBeginLoc();
7492 
7493   if (S.getSourceManager().isInSystemMacro(Loc))
7494     return;
7495 
7496   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7497   for (auto E : DiagnosticExprs)
7498     PDiag << E->getSourceRange();
7499 
7500   CheckFormatHandler::EmitFormatDiagnostic(
7501                                   S, IsFunctionCall, DiagnosticExprs[0],
7502                                   PDiag, Loc, /*IsStringLocation*/false,
7503                                   DiagnosticExprs[0]->getSourceRange());
7504 }
7505 
7506 bool
7507 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7508                                                      SourceLocation Loc,
7509                                                      const char *startSpec,
7510                                                      unsigned specifierLen,
7511                                                      const char *csStart,
7512                                                      unsigned csLen) {
7513   bool keepGoing = true;
7514   if (argIndex < NumDataArgs) {
7515     // Consider the argument coverered, even though the specifier doesn't
7516     // make sense.
7517     CoveredArgs.set(argIndex);
7518   }
7519   else {
7520     // If argIndex exceeds the number of data arguments we
7521     // don't issue a warning because that is just a cascade of warnings (and
7522     // they may have intended '%%' anyway). We don't want to continue processing
7523     // the format string after this point, however, as we will like just get
7524     // gibberish when trying to match arguments.
7525     keepGoing = false;
7526   }
7527 
7528   StringRef Specifier(csStart, csLen);
7529 
7530   // If the specifier in non-printable, it could be the first byte of a UTF-8
7531   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7532   // hex value.
7533   std::string CodePointStr;
7534   if (!llvm::sys::locale::isPrint(*csStart)) {
7535     llvm::UTF32 CodePoint;
7536     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7537     const llvm::UTF8 *E =
7538         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7539     llvm::ConversionResult Result =
7540         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7541 
7542     if (Result != llvm::conversionOK) {
7543       unsigned char FirstChar = *csStart;
7544       CodePoint = (llvm::UTF32)FirstChar;
7545     }
7546 
7547     llvm::raw_string_ostream OS(CodePointStr);
7548     if (CodePoint < 256)
7549       OS << "\\x" << llvm::format("%02x", CodePoint);
7550     else if (CodePoint <= 0xFFFF)
7551       OS << "\\u" << llvm::format("%04x", CodePoint);
7552     else
7553       OS << "\\U" << llvm::format("%08x", CodePoint);
7554     OS.flush();
7555     Specifier = CodePointStr;
7556   }
7557 
7558   EmitFormatDiagnostic(
7559       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7560       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7561 
7562   return keepGoing;
7563 }
7564 
7565 void
7566 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7567                                                       const char *startSpec,
7568                                                       unsigned specifierLen) {
7569   EmitFormatDiagnostic(
7570     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7571     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7572 }
7573 
7574 bool
7575 CheckFormatHandler::CheckNumArgs(
7576   const analyze_format_string::FormatSpecifier &FS,
7577   const analyze_format_string::ConversionSpecifier &CS,
7578   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7579 
7580   if (argIndex >= NumDataArgs) {
7581     PartialDiagnostic PDiag = FS.usesPositionalArg()
7582       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7583            << (argIndex+1) << NumDataArgs)
7584       : S.PDiag(diag::warn_printf_insufficient_data_args);
7585     EmitFormatDiagnostic(
7586       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7587       getSpecifierRange(startSpecifier, specifierLen));
7588 
7589     // Since more arguments than conversion tokens are given, by extension
7590     // all arguments are covered, so mark this as so.
7591     UncoveredArg.setAllCovered();
7592     return false;
7593   }
7594   return true;
7595 }
7596 
7597 template<typename Range>
7598 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7599                                               SourceLocation Loc,
7600                                               bool IsStringLocation,
7601                                               Range StringRange,
7602                                               ArrayRef<FixItHint> FixIt) {
7603   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7604                        Loc, IsStringLocation, StringRange, FixIt);
7605 }
7606 
7607 /// If the format string is not within the function call, emit a note
7608 /// so that the function call and string are in diagnostic messages.
7609 ///
7610 /// \param InFunctionCall if true, the format string is within the function
7611 /// call and only one diagnostic message will be produced.  Otherwise, an
7612 /// extra note will be emitted pointing to location of the format string.
7613 ///
7614 /// \param ArgumentExpr the expression that is passed as the format string
7615 /// argument in the function call.  Used for getting locations when two
7616 /// diagnostics are emitted.
7617 ///
7618 /// \param PDiag the callee should already have provided any strings for the
7619 /// diagnostic message.  This function only adds locations and fixits
7620 /// to diagnostics.
7621 ///
7622 /// \param Loc primary location for diagnostic.  If two diagnostics are
7623 /// required, one will be at Loc and a new SourceLocation will be created for
7624 /// the other one.
7625 ///
7626 /// \param IsStringLocation if true, Loc points to the format string should be
7627 /// used for the note.  Otherwise, Loc points to the argument list and will
7628 /// be used with PDiag.
7629 ///
7630 /// \param StringRange some or all of the string to highlight.  This is
7631 /// templated so it can accept either a CharSourceRange or a SourceRange.
7632 ///
7633 /// \param FixIt optional fix it hint for the format string.
7634 template <typename Range>
7635 void CheckFormatHandler::EmitFormatDiagnostic(
7636     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7637     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7638     Range StringRange, ArrayRef<FixItHint> FixIt) {
7639   if (InFunctionCall) {
7640     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7641     D << StringRange;
7642     D << FixIt;
7643   } else {
7644     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7645       << ArgumentExpr->getSourceRange();
7646 
7647     const Sema::SemaDiagnosticBuilder &Note =
7648       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7649              diag::note_format_string_defined);
7650 
7651     Note << StringRange;
7652     Note << FixIt;
7653   }
7654 }
7655 
7656 //===--- CHECK: Printf format string checking ------------------------------===//
7657 
7658 namespace {
7659 
7660 class CheckPrintfHandler : public CheckFormatHandler {
7661 public:
7662   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7663                      const Expr *origFormatExpr,
7664                      const Sema::FormatStringType type, unsigned firstDataArg,
7665                      unsigned numDataArgs, bool isObjC, const char *beg,
7666                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7667                      unsigned formatIdx, bool inFunctionCall,
7668                      Sema::VariadicCallType CallType,
7669                      llvm::SmallBitVector &CheckedVarArgs,
7670                      UncoveredArgHandler &UncoveredArg)
7671       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7672                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7673                            inFunctionCall, CallType, CheckedVarArgs,
7674                            UncoveredArg) {}
7675 
7676   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7677 
7678   /// Returns true if '%@' specifiers are allowed in the format string.
7679   bool allowsObjCArg() const {
7680     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7681            FSType == Sema::FST_OSTrace;
7682   }
7683 
7684   bool HandleInvalidPrintfConversionSpecifier(
7685                                       const analyze_printf::PrintfSpecifier &FS,
7686                                       const char *startSpecifier,
7687                                       unsigned specifierLen) override;
7688 
7689   void handleInvalidMaskType(StringRef MaskType) override;
7690 
7691   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7692                              const char *startSpecifier,
7693                              unsigned specifierLen) override;
7694   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7695                        const char *StartSpecifier,
7696                        unsigned SpecifierLen,
7697                        const Expr *E);
7698 
7699   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7700                     const char *startSpecifier, unsigned specifierLen);
7701   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7702                            const analyze_printf::OptionalAmount &Amt,
7703                            unsigned type,
7704                            const char *startSpecifier, unsigned specifierLen);
7705   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7706                   const analyze_printf::OptionalFlag &flag,
7707                   const char *startSpecifier, unsigned specifierLen);
7708   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7709                          const analyze_printf::OptionalFlag &ignoredFlag,
7710                          const analyze_printf::OptionalFlag &flag,
7711                          const char *startSpecifier, unsigned specifierLen);
7712   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7713                            const Expr *E);
7714 
7715   void HandleEmptyObjCModifierFlag(const char *startFlag,
7716                                    unsigned flagLen) override;
7717 
7718   void HandleInvalidObjCModifierFlag(const char *startFlag,
7719                                             unsigned flagLen) override;
7720 
7721   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7722                                            const char *flagsEnd,
7723                                            const char *conversionPosition)
7724                                              override;
7725 };
7726 
7727 } // namespace
7728 
7729 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7730                                       const analyze_printf::PrintfSpecifier &FS,
7731                                       const char *startSpecifier,
7732                                       unsigned specifierLen) {
7733   const analyze_printf::PrintfConversionSpecifier &CS =
7734     FS.getConversionSpecifier();
7735 
7736   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7737                                           getLocationOfByte(CS.getStart()),
7738                                           startSpecifier, specifierLen,
7739                                           CS.getStart(), CS.getLength());
7740 }
7741 
7742 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7743   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7744 }
7745 
7746 bool CheckPrintfHandler::HandleAmount(
7747                                const analyze_format_string::OptionalAmount &Amt,
7748                                unsigned k, const char *startSpecifier,
7749                                unsigned specifierLen) {
7750   if (Amt.hasDataArgument()) {
7751     if (!HasVAListArg) {
7752       unsigned argIndex = Amt.getArgIndex();
7753       if (argIndex >= NumDataArgs) {
7754         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7755                                << k,
7756                              getLocationOfByte(Amt.getStart()),
7757                              /*IsStringLocation*/true,
7758                              getSpecifierRange(startSpecifier, specifierLen));
7759         // Don't do any more checking.  We will just emit
7760         // spurious errors.
7761         return false;
7762       }
7763 
7764       // Type check the data argument.  It should be an 'int'.
7765       // Although not in conformance with C99, we also allow the argument to be
7766       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7767       // doesn't emit a warning for that case.
7768       CoveredArgs.set(argIndex);
7769       const Expr *Arg = getDataArg(argIndex);
7770       if (!Arg)
7771         return false;
7772 
7773       QualType T = Arg->getType();
7774 
7775       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7776       assert(AT.isValid());
7777 
7778       if (!AT.matchesType(S.Context, T)) {
7779         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7780                                << k << AT.getRepresentativeTypeName(S.Context)
7781                                << T << Arg->getSourceRange(),
7782                              getLocationOfByte(Amt.getStart()),
7783                              /*IsStringLocation*/true,
7784                              getSpecifierRange(startSpecifier, specifierLen));
7785         // Don't do any more checking.  We will just emit
7786         // spurious errors.
7787         return false;
7788       }
7789     }
7790   }
7791   return true;
7792 }
7793 
7794 void CheckPrintfHandler::HandleInvalidAmount(
7795                                       const analyze_printf::PrintfSpecifier &FS,
7796                                       const analyze_printf::OptionalAmount &Amt,
7797                                       unsigned type,
7798                                       const char *startSpecifier,
7799                                       unsigned specifierLen) {
7800   const analyze_printf::PrintfConversionSpecifier &CS =
7801     FS.getConversionSpecifier();
7802 
7803   FixItHint fixit =
7804     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7805       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7806                                  Amt.getConstantLength()))
7807       : FixItHint();
7808 
7809   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7810                          << type << CS.toString(),
7811                        getLocationOfByte(Amt.getStart()),
7812                        /*IsStringLocation*/true,
7813                        getSpecifierRange(startSpecifier, specifierLen),
7814                        fixit);
7815 }
7816 
7817 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7818                                     const analyze_printf::OptionalFlag &flag,
7819                                     const char *startSpecifier,
7820                                     unsigned specifierLen) {
7821   // Warn about pointless flag with a fixit removal.
7822   const analyze_printf::PrintfConversionSpecifier &CS =
7823     FS.getConversionSpecifier();
7824   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7825                          << flag.toString() << CS.toString(),
7826                        getLocationOfByte(flag.getPosition()),
7827                        /*IsStringLocation*/true,
7828                        getSpecifierRange(startSpecifier, specifierLen),
7829                        FixItHint::CreateRemoval(
7830                          getSpecifierRange(flag.getPosition(), 1)));
7831 }
7832 
7833 void CheckPrintfHandler::HandleIgnoredFlag(
7834                                 const analyze_printf::PrintfSpecifier &FS,
7835                                 const analyze_printf::OptionalFlag &ignoredFlag,
7836                                 const analyze_printf::OptionalFlag &flag,
7837                                 const char *startSpecifier,
7838                                 unsigned specifierLen) {
7839   // Warn about ignored flag with a fixit removal.
7840   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7841                          << ignoredFlag.toString() << flag.toString(),
7842                        getLocationOfByte(ignoredFlag.getPosition()),
7843                        /*IsStringLocation*/true,
7844                        getSpecifierRange(startSpecifier, specifierLen),
7845                        FixItHint::CreateRemoval(
7846                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7847 }
7848 
7849 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7850                                                      unsigned flagLen) {
7851   // Warn about an empty flag.
7852   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7853                        getLocationOfByte(startFlag),
7854                        /*IsStringLocation*/true,
7855                        getSpecifierRange(startFlag, flagLen));
7856 }
7857 
7858 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7859                                                        unsigned flagLen) {
7860   // Warn about an invalid flag.
7861   auto Range = getSpecifierRange(startFlag, flagLen);
7862   StringRef flag(startFlag, flagLen);
7863   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7864                       getLocationOfByte(startFlag),
7865                       /*IsStringLocation*/true,
7866                       Range, FixItHint::CreateRemoval(Range));
7867 }
7868 
7869 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7870     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7871     // Warn about using '[...]' without a '@' conversion.
7872     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7873     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7874     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7875                          getLocationOfByte(conversionPosition),
7876                          /*IsStringLocation*/true,
7877                          Range, FixItHint::CreateRemoval(Range));
7878 }
7879 
7880 // Determines if the specified is a C++ class or struct containing
7881 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7882 // "c_str()").
7883 template<typename MemberKind>
7884 static llvm::SmallPtrSet<MemberKind*, 1>
7885 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7886   const RecordType *RT = Ty->getAs<RecordType>();
7887   llvm::SmallPtrSet<MemberKind*, 1> Results;
7888 
7889   if (!RT)
7890     return Results;
7891   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7892   if (!RD || !RD->getDefinition())
7893     return Results;
7894 
7895   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7896                  Sema::LookupMemberName);
7897   R.suppressDiagnostics();
7898 
7899   // We just need to include all members of the right kind turned up by the
7900   // filter, at this point.
7901   if (S.LookupQualifiedName(R, RT->getDecl()))
7902     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7903       NamedDecl *decl = (*I)->getUnderlyingDecl();
7904       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7905         Results.insert(FK);
7906     }
7907   return Results;
7908 }
7909 
7910 /// Check if we could call '.c_str()' on an object.
7911 ///
7912 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7913 /// allow the call, or if it would be ambiguous).
7914 bool Sema::hasCStrMethod(const Expr *E) {
7915   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7916 
7917   MethodSet Results =
7918       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7919   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7920        MI != ME; ++MI)
7921     if ((*MI)->getMinRequiredArguments() == 0)
7922       return true;
7923   return false;
7924 }
7925 
7926 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7927 // better diagnostic if so. AT is assumed to be valid.
7928 // Returns true when a c_str() conversion method is found.
7929 bool CheckPrintfHandler::checkForCStrMembers(
7930     const analyze_printf::ArgType &AT, const Expr *E) {
7931   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7932 
7933   MethodSet Results =
7934       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7935 
7936   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7937        MI != ME; ++MI) {
7938     const CXXMethodDecl *Method = *MI;
7939     if (Method->getMinRequiredArguments() == 0 &&
7940         AT.matchesType(S.Context, Method->getReturnType())) {
7941       // FIXME: Suggest parens if the expression needs them.
7942       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7943       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7944           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7945       return true;
7946     }
7947   }
7948 
7949   return false;
7950 }
7951 
7952 bool
7953 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7954                                             &FS,
7955                                           const char *startSpecifier,
7956                                           unsigned specifierLen) {
7957   using namespace analyze_format_string;
7958   using namespace analyze_printf;
7959 
7960   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7961 
7962   if (FS.consumesDataArgument()) {
7963     if (atFirstArg) {
7964         atFirstArg = false;
7965         usesPositionalArgs = FS.usesPositionalArg();
7966     }
7967     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7968       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7969                                         startSpecifier, specifierLen);
7970       return false;
7971     }
7972   }
7973 
7974   // First check if the field width, precision, and conversion specifier
7975   // have matching data arguments.
7976   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7977                     startSpecifier, specifierLen)) {
7978     return false;
7979   }
7980 
7981   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7982                     startSpecifier, specifierLen)) {
7983     return false;
7984   }
7985 
7986   if (!CS.consumesDataArgument()) {
7987     // FIXME: Technically specifying a precision or field width here
7988     // makes no sense.  Worth issuing a warning at some point.
7989     return true;
7990   }
7991 
7992   // Consume the argument.
7993   unsigned argIndex = FS.getArgIndex();
7994   if (argIndex < NumDataArgs) {
7995     // The check to see if the argIndex is valid will come later.
7996     // We set the bit here because we may exit early from this
7997     // function if we encounter some other error.
7998     CoveredArgs.set(argIndex);
7999   }
8000 
8001   // FreeBSD kernel extensions.
8002   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8003       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8004     // We need at least two arguments.
8005     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8006       return false;
8007 
8008     // Claim the second argument.
8009     CoveredArgs.set(argIndex + 1);
8010 
8011     // Type check the first argument (int for %b, pointer for %D)
8012     const Expr *Ex = getDataArg(argIndex);
8013     const analyze_printf::ArgType &AT =
8014       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8015         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8016     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8017       EmitFormatDiagnostic(
8018           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8019               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8020               << false << Ex->getSourceRange(),
8021           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8022           getSpecifierRange(startSpecifier, specifierLen));
8023 
8024     // Type check the second argument (char * for both %b and %D)
8025     Ex = getDataArg(argIndex + 1);
8026     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8027     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8028       EmitFormatDiagnostic(
8029           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8030               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8031               << false << Ex->getSourceRange(),
8032           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8033           getSpecifierRange(startSpecifier, specifierLen));
8034 
8035      return true;
8036   }
8037 
8038   // Check for using an Objective-C specific conversion specifier
8039   // in a non-ObjC literal.
8040   if (!allowsObjCArg() && CS.isObjCArg()) {
8041     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8042                                                   specifierLen);
8043   }
8044 
8045   // %P can only be used with os_log.
8046   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8047     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8048                                                   specifierLen);
8049   }
8050 
8051   // %n is not allowed with os_log.
8052   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8053     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8054                          getLocationOfByte(CS.getStart()),
8055                          /*IsStringLocation*/ false,
8056                          getSpecifierRange(startSpecifier, specifierLen));
8057 
8058     return true;
8059   }
8060 
8061   // Only scalars are allowed for os_trace.
8062   if (FSType == Sema::FST_OSTrace &&
8063       (CS.getKind() == ConversionSpecifier::PArg ||
8064        CS.getKind() == ConversionSpecifier::sArg ||
8065        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8066     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8067                                                   specifierLen);
8068   }
8069 
8070   // Check for use of public/private annotation outside of os_log().
8071   if (FSType != Sema::FST_OSLog) {
8072     if (FS.isPublic().isSet()) {
8073       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8074                                << "public",
8075                            getLocationOfByte(FS.isPublic().getPosition()),
8076                            /*IsStringLocation*/ false,
8077                            getSpecifierRange(startSpecifier, specifierLen));
8078     }
8079     if (FS.isPrivate().isSet()) {
8080       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8081                                << "private",
8082                            getLocationOfByte(FS.isPrivate().getPosition()),
8083                            /*IsStringLocation*/ false,
8084                            getSpecifierRange(startSpecifier, specifierLen));
8085     }
8086   }
8087 
8088   // Check for invalid use of field width
8089   if (!FS.hasValidFieldWidth()) {
8090     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8091         startSpecifier, specifierLen);
8092   }
8093 
8094   // Check for invalid use of precision
8095   if (!FS.hasValidPrecision()) {
8096     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8097         startSpecifier, specifierLen);
8098   }
8099 
8100   // Precision is mandatory for %P specifier.
8101   if (CS.getKind() == ConversionSpecifier::PArg &&
8102       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8103     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8104                          getLocationOfByte(startSpecifier),
8105                          /*IsStringLocation*/ false,
8106                          getSpecifierRange(startSpecifier, specifierLen));
8107   }
8108 
8109   // Check each flag does not conflict with any other component.
8110   if (!FS.hasValidThousandsGroupingPrefix())
8111     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8112   if (!FS.hasValidLeadingZeros())
8113     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8114   if (!FS.hasValidPlusPrefix())
8115     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8116   if (!FS.hasValidSpacePrefix())
8117     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8118   if (!FS.hasValidAlternativeForm())
8119     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8120   if (!FS.hasValidLeftJustified())
8121     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8122 
8123   // Check that flags are not ignored by another flag
8124   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8125     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8126         startSpecifier, specifierLen);
8127   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8128     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8129             startSpecifier, specifierLen);
8130 
8131   // Check the length modifier is valid with the given conversion specifier.
8132   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8133                                  S.getLangOpts()))
8134     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8135                                 diag::warn_format_nonsensical_length);
8136   else if (!FS.hasStandardLengthModifier())
8137     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8138   else if (!FS.hasStandardLengthConversionCombination())
8139     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8140                                 diag::warn_format_non_standard_conversion_spec);
8141 
8142   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8143     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8144 
8145   // The remaining checks depend on the data arguments.
8146   if (HasVAListArg)
8147     return true;
8148 
8149   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8150     return false;
8151 
8152   const Expr *Arg = getDataArg(argIndex);
8153   if (!Arg)
8154     return true;
8155 
8156   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8157 }
8158 
8159 static bool requiresParensToAddCast(const Expr *E) {
8160   // FIXME: We should have a general way to reason about operator
8161   // precedence and whether parens are actually needed here.
8162   // Take care of a few common cases where they aren't.
8163   const Expr *Inside = E->IgnoreImpCasts();
8164   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8165     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8166 
8167   switch (Inside->getStmtClass()) {
8168   case Stmt::ArraySubscriptExprClass:
8169   case Stmt::CallExprClass:
8170   case Stmt::CharacterLiteralClass:
8171   case Stmt::CXXBoolLiteralExprClass:
8172   case Stmt::DeclRefExprClass:
8173   case Stmt::FloatingLiteralClass:
8174   case Stmt::IntegerLiteralClass:
8175   case Stmt::MemberExprClass:
8176   case Stmt::ObjCArrayLiteralClass:
8177   case Stmt::ObjCBoolLiteralExprClass:
8178   case Stmt::ObjCBoxedExprClass:
8179   case Stmt::ObjCDictionaryLiteralClass:
8180   case Stmt::ObjCEncodeExprClass:
8181   case Stmt::ObjCIvarRefExprClass:
8182   case Stmt::ObjCMessageExprClass:
8183   case Stmt::ObjCPropertyRefExprClass:
8184   case Stmt::ObjCStringLiteralClass:
8185   case Stmt::ObjCSubscriptRefExprClass:
8186   case Stmt::ParenExprClass:
8187   case Stmt::StringLiteralClass:
8188   case Stmt::UnaryOperatorClass:
8189     return false;
8190   default:
8191     return true;
8192   }
8193 }
8194 
8195 static std::pair<QualType, StringRef>
8196 shouldNotPrintDirectly(const ASTContext &Context,
8197                        QualType IntendedTy,
8198                        const Expr *E) {
8199   // Use a 'while' to peel off layers of typedefs.
8200   QualType TyTy = IntendedTy;
8201   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8202     StringRef Name = UserTy->getDecl()->getName();
8203     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8204       .Case("CFIndex", Context.getNSIntegerType())
8205       .Case("NSInteger", Context.getNSIntegerType())
8206       .Case("NSUInteger", Context.getNSUIntegerType())
8207       .Case("SInt32", Context.IntTy)
8208       .Case("UInt32", Context.UnsignedIntTy)
8209       .Default(QualType());
8210 
8211     if (!CastTy.isNull())
8212       return std::make_pair(CastTy, Name);
8213 
8214     TyTy = UserTy->desugar();
8215   }
8216 
8217   // Strip parens if necessary.
8218   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8219     return shouldNotPrintDirectly(Context,
8220                                   PE->getSubExpr()->getType(),
8221                                   PE->getSubExpr());
8222 
8223   // If this is a conditional expression, then its result type is constructed
8224   // via usual arithmetic conversions and thus there might be no necessary
8225   // typedef sugar there.  Recurse to operands to check for NSInteger &
8226   // Co. usage condition.
8227   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8228     QualType TrueTy, FalseTy;
8229     StringRef TrueName, FalseName;
8230 
8231     std::tie(TrueTy, TrueName) =
8232       shouldNotPrintDirectly(Context,
8233                              CO->getTrueExpr()->getType(),
8234                              CO->getTrueExpr());
8235     std::tie(FalseTy, FalseName) =
8236       shouldNotPrintDirectly(Context,
8237                              CO->getFalseExpr()->getType(),
8238                              CO->getFalseExpr());
8239 
8240     if (TrueTy == FalseTy)
8241       return std::make_pair(TrueTy, TrueName);
8242     else if (TrueTy.isNull())
8243       return std::make_pair(FalseTy, FalseName);
8244     else if (FalseTy.isNull())
8245       return std::make_pair(TrueTy, TrueName);
8246   }
8247 
8248   return std::make_pair(QualType(), StringRef());
8249 }
8250 
8251 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8252 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8253 /// type do not count.
8254 static bool
8255 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8256   QualType From = ICE->getSubExpr()->getType();
8257   QualType To = ICE->getType();
8258   // It's an integer promotion if the destination type is the promoted
8259   // source type.
8260   if (ICE->getCastKind() == CK_IntegralCast &&
8261       From->isPromotableIntegerType() &&
8262       S.Context.getPromotedIntegerType(From) == To)
8263     return true;
8264   // Look through vector types, since we do default argument promotion for
8265   // those in OpenCL.
8266   if (const auto *VecTy = From->getAs<ExtVectorType>())
8267     From = VecTy->getElementType();
8268   if (const auto *VecTy = To->getAs<ExtVectorType>())
8269     To = VecTy->getElementType();
8270   // It's a floating promotion if the source type is a lower rank.
8271   return ICE->getCastKind() == CK_FloatingCast &&
8272          S.Context.getFloatingTypeOrder(From, To) < 0;
8273 }
8274 
8275 bool
8276 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8277                                     const char *StartSpecifier,
8278                                     unsigned SpecifierLen,
8279                                     const Expr *E) {
8280   using namespace analyze_format_string;
8281   using namespace analyze_printf;
8282 
8283   // Now type check the data expression that matches the
8284   // format specifier.
8285   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8286   if (!AT.isValid())
8287     return true;
8288 
8289   QualType ExprTy = E->getType();
8290   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8291     ExprTy = TET->getUnderlyingExpr()->getType();
8292   }
8293 
8294   // Diagnose attempts to print a boolean value as a character. Unlike other
8295   // -Wformat diagnostics, this is fine from a type perspective, but it still
8296   // doesn't make sense.
8297   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8298       E->isKnownToHaveBooleanValue()) {
8299     const CharSourceRange &CSR =
8300         getSpecifierRange(StartSpecifier, SpecifierLen);
8301     SmallString<4> FSString;
8302     llvm::raw_svector_ostream os(FSString);
8303     FS.toString(os);
8304     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8305                              << FSString,
8306                          E->getExprLoc(), false, CSR);
8307     return true;
8308   }
8309 
8310   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8311   if (Match == analyze_printf::ArgType::Match)
8312     return true;
8313 
8314   // Look through argument promotions for our error message's reported type.
8315   // This includes the integral and floating promotions, but excludes array
8316   // and function pointer decay (seeing that an argument intended to be a
8317   // string has type 'char [6]' is probably more confusing than 'char *') and
8318   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8319   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8320     if (isArithmeticArgumentPromotion(S, ICE)) {
8321       E = ICE->getSubExpr();
8322       ExprTy = E->getType();
8323 
8324       // Check if we didn't match because of an implicit cast from a 'char'
8325       // or 'short' to an 'int'.  This is done because printf is a varargs
8326       // function.
8327       if (ICE->getType() == S.Context.IntTy ||
8328           ICE->getType() == S.Context.UnsignedIntTy) {
8329         // All further checking is done on the subexpression
8330         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8331             AT.matchesType(S.Context, ExprTy);
8332         if (ImplicitMatch == analyze_printf::ArgType::Match)
8333           return true;
8334         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8335             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8336           Match = ImplicitMatch;
8337       }
8338     }
8339   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8340     // Special case for 'a', which has type 'int' in C.
8341     // Note, however, that we do /not/ want to treat multibyte constants like
8342     // 'MooV' as characters! This form is deprecated but still exists.
8343     if (ExprTy == S.Context.IntTy)
8344       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8345         ExprTy = S.Context.CharTy;
8346   }
8347 
8348   // Look through enums to their underlying type.
8349   bool IsEnum = false;
8350   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8351     ExprTy = EnumTy->getDecl()->getIntegerType();
8352     IsEnum = true;
8353   }
8354 
8355   // %C in an Objective-C context prints a unichar, not a wchar_t.
8356   // If the argument is an integer of some kind, believe the %C and suggest
8357   // a cast instead of changing the conversion specifier.
8358   QualType IntendedTy = ExprTy;
8359   if (isObjCContext() &&
8360       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8361     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8362         !ExprTy->isCharType()) {
8363       // 'unichar' is defined as a typedef of unsigned short, but we should
8364       // prefer using the typedef if it is visible.
8365       IntendedTy = S.Context.UnsignedShortTy;
8366 
8367       // While we are here, check if the value is an IntegerLiteral that happens
8368       // to be within the valid range.
8369       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8370         const llvm::APInt &V = IL->getValue();
8371         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8372           return true;
8373       }
8374 
8375       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8376                           Sema::LookupOrdinaryName);
8377       if (S.LookupName(Result, S.getCurScope())) {
8378         NamedDecl *ND = Result.getFoundDecl();
8379         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8380           if (TD->getUnderlyingType() == IntendedTy)
8381             IntendedTy = S.Context.getTypedefType(TD);
8382       }
8383     }
8384   }
8385 
8386   // Special-case some of Darwin's platform-independence types by suggesting
8387   // casts to primitive types that are known to be large enough.
8388   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8389   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8390     QualType CastTy;
8391     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8392     if (!CastTy.isNull()) {
8393       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8394       // (long in ASTContext). Only complain to pedants.
8395       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8396           (AT.isSizeT() || AT.isPtrdiffT()) &&
8397           AT.matchesType(S.Context, CastTy))
8398         Match = ArgType::NoMatchPedantic;
8399       IntendedTy = CastTy;
8400       ShouldNotPrintDirectly = true;
8401     }
8402   }
8403 
8404   // We may be able to offer a FixItHint if it is a supported type.
8405   PrintfSpecifier fixedFS = FS;
8406   bool Success =
8407       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8408 
8409   if (Success) {
8410     // Get the fix string from the fixed format specifier
8411     SmallString<16> buf;
8412     llvm::raw_svector_ostream os(buf);
8413     fixedFS.toString(os);
8414 
8415     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8416 
8417     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8418       unsigned Diag;
8419       switch (Match) {
8420       case ArgType::Match: llvm_unreachable("expected non-matching");
8421       case ArgType::NoMatchPedantic:
8422         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8423         break;
8424       case ArgType::NoMatchTypeConfusion:
8425         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8426         break;
8427       case ArgType::NoMatch:
8428         Diag = diag::warn_format_conversion_argument_type_mismatch;
8429         break;
8430       }
8431 
8432       // In this case, the specifier is wrong and should be changed to match
8433       // the argument.
8434       EmitFormatDiagnostic(S.PDiag(Diag)
8435                                << AT.getRepresentativeTypeName(S.Context)
8436                                << IntendedTy << IsEnum << E->getSourceRange(),
8437                            E->getBeginLoc(),
8438                            /*IsStringLocation*/ false, SpecRange,
8439                            FixItHint::CreateReplacement(SpecRange, os.str()));
8440     } else {
8441       // The canonical type for formatting this value is different from the
8442       // actual type of the expression. (This occurs, for example, with Darwin's
8443       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8444       // should be printed as 'long' for 64-bit compatibility.)
8445       // Rather than emitting a normal format/argument mismatch, we want to
8446       // add a cast to the recommended type (and correct the format string
8447       // if necessary).
8448       SmallString<16> CastBuf;
8449       llvm::raw_svector_ostream CastFix(CastBuf);
8450       CastFix << "(";
8451       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8452       CastFix << ")";
8453 
8454       SmallVector<FixItHint,4> Hints;
8455       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8456         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8457 
8458       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8459         // If there's already a cast present, just replace it.
8460         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8461         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8462 
8463       } else if (!requiresParensToAddCast(E)) {
8464         // If the expression has high enough precedence,
8465         // just write the C-style cast.
8466         Hints.push_back(
8467             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8468       } else {
8469         // Otherwise, add parens around the expression as well as the cast.
8470         CastFix << "(";
8471         Hints.push_back(
8472             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8473 
8474         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8475         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8476       }
8477 
8478       if (ShouldNotPrintDirectly) {
8479         // The expression has a type that should not be printed directly.
8480         // We extract the name from the typedef because we don't want to show
8481         // the underlying type in the diagnostic.
8482         StringRef Name;
8483         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8484           Name = TypedefTy->getDecl()->getName();
8485         else
8486           Name = CastTyName;
8487         unsigned Diag = Match == ArgType::NoMatchPedantic
8488                             ? diag::warn_format_argument_needs_cast_pedantic
8489                             : diag::warn_format_argument_needs_cast;
8490         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8491                                            << E->getSourceRange(),
8492                              E->getBeginLoc(), /*IsStringLocation=*/false,
8493                              SpecRange, Hints);
8494       } else {
8495         // In this case, the expression could be printed using a different
8496         // specifier, but we've decided that the specifier is probably correct
8497         // and we should cast instead. Just use the normal warning message.
8498         EmitFormatDiagnostic(
8499             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8500                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8501                 << E->getSourceRange(),
8502             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8503       }
8504     }
8505   } else {
8506     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8507                                                    SpecifierLen);
8508     // Since the warning for passing non-POD types to variadic functions
8509     // was deferred until now, we emit a warning for non-POD
8510     // arguments here.
8511     switch (S.isValidVarArgType(ExprTy)) {
8512     case Sema::VAK_Valid:
8513     case Sema::VAK_ValidInCXX11: {
8514       unsigned Diag;
8515       switch (Match) {
8516       case ArgType::Match: llvm_unreachable("expected non-matching");
8517       case ArgType::NoMatchPedantic:
8518         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8519         break;
8520       case ArgType::NoMatchTypeConfusion:
8521         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8522         break;
8523       case ArgType::NoMatch:
8524         Diag = diag::warn_format_conversion_argument_type_mismatch;
8525         break;
8526       }
8527 
8528       EmitFormatDiagnostic(
8529           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8530                         << IsEnum << CSR << E->getSourceRange(),
8531           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8532       break;
8533     }
8534     case Sema::VAK_Undefined:
8535     case Sema::VAK_MSVCUndefined:
8536       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8537                                << S.getLangOpts().CPlusPlus11 << ExprTy
8538                                << CallType
8539                                << AT.getRepresentativeTypeName(S.Context) << CSR
8540                                << E->getSourceRange(),
8541                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8542       checkForCStrMembers(AT, E);
8543       break;
8544 
8545     case Sema::VAK_Invalid:
8546       if (ExprTy->isObjCObjectType())
8547         EmitFormatDiagnostic(
8548             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8549                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8550                 << AT.getRepresentativeTypeName(S.Context) << CSR
8551                 << E->getSourceRange(),
8552             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8553       else
8554         // FIXME: If this is an initializer list, suggest removing the braces
8555         // or inserting a cast to the target type.
8556         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8557             << isa<InitListExpr>(E) << ExprTy << CallType
8558             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8559       break;
8560     }
8561 
8562     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8563            "format string specifier index out of range");
8564     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8565   }
8566 
8567   return true;
8568 }
8569 
8570 //===--- CHECK: Scanf format string checking ------------------------------===//
8571 
8572 namespace {
8573 
8574 class CheckScanfHandler : public CheckFormatHandler {
8575 public:
8576   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8577                     const Expr *origFormatExpr, Sema::FormatStringType type,
8578                     unsigned firstDataArg, unsigned numDataArgs,
8579                     const char *beg, bool hasVAListArg,
8580                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8581                     bool inFunctionCall, Sema::VariadicCallType CallType,
8582                     llvm::SmallBitVector &CheckedVarArgs,
8583                     UncoveredArgHandler &UncoveredArg)
8584       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8585                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8586                            inFunctionCall, CallType, CheckedVarArgs,
8587                            UncoveredArg) {}
8588 
8589   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8590                             const char *startSpecifier,
8591                             unsigned specifierLen) override;
8592 
8593   bool HandleInvalidScanfConversionSpecifier(
8594           const analyze_scanf::ScanfSpecifier &FS,
8595           const char *startSpecifier,
8596           unsigned specifierLen) override;
8597 
8598   void HandleIncompleteScanList(const char *start, const char *end) override;
8599 };
8600 
8601 } // namespace
8602 
8603 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8604                                                  const char *end) {
8605   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8606                        getLocationOfByte(end), /*IsStringLocation*/true,
8607                        getSpecifierRange(start, end - start));
8608 }
8609 
8610 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8611                                         const analyze_scanf::ScanfSpecifier &FS,
8612                                         const char *startSpecifier,
8613                                         unsigned specifierLen) {
8614   const analyze_scanf::ScanfConversionSpecifier &CS =
8615     FS.getConversionSpecifier();
8616 
8617   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8618                                           getLocationOfByte(CS.getStart()),
8619                                           startSpecifier, specifierLen,
8620                                           CS.getStart(), CS.getLength());
8621 }
8622 
8623 bool CheckScanfHandler::HandleScanfSpecifier(
8624                                        const analyze_scanf::ScanfSpecifier &FS,
8625                                        const char *startSpecifier,
8626                                        unsigned specifierLen) {
8627   using namespace analyze_scanf;
8628   using namespace analyze_format_string;
8629 
8630   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8631 
8632   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8633   // be used to decide if we are using positional arguments consistently.
8634   if (FS.consumesDataArgument()) {
8635     if (atFirstArg) {
8636       atFirstArg = false;
8637       usesPositionalArgs = FS.usesPositionalArg();
8638     }
8639     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8640       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8641                                         startSpecifier, specifierLen);
8642       return false;
8643     }
8644   }
8645 
8646   // Check if the field with is non-zero.
8647   const OptionalAmount &Amt = FS.getFieldWidth();
8648   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8649     if (Amt.getConstantAmount() == 0) {
8650       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8651                                                    Amt.getConstantLength());
8652       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8653                            getLocationOfByte(Amt.getStart()),
8654                            /*IsStringLocation*/true, R,
8655                            FixItHint::CreateRemoval(R));
8656     }
8657   }
8658 
8659   if (!FS.consumesDataArgument()) {
8660     // FIXME: Technically specifying a precision or field width here
8661     // makes no sense.  Worth issuing a warning at some point.
8662     return true;
8663   }
8664 
8665   // Consume the argument.
8666   unsigned argIndex = FS.getArgIndex();
8667   if (argIndex < NumDataArgs) {
8668       // The check to see if the argIndex is valid will come later.
8669       // We set the bit here because we may exit early from this
8670       // function if we encounter some other error.
8671     CoveredArgs.set(argIndex);
8672   }
8673 
8674   // Check the length modifier is valid with the given conversion specifier.
8675   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8676                                  S.getLangOpts()))
8677     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8678                                 diag::warn_format_nonsensical_length);
8679   else if (!FS.hasStandardLengthModifier())
8680     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8681   else if (!FS.hasStandardLengthConversionCombination())
8682     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8683                                 diag::warn_format_non_standard_conversion_spec);
8684 
8685   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8686     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8687 
8688   // The remaining checks depend on the data arguments.
8689   if (HasVAListArg)
8690     return true;
8691 
8692   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8693     return false;
8694 
8695   // Check that the argument type matches the format specifier.
8696   const Expr *Ex = getDataArg(argIndex);
8697   if (!Ex)
8698     return true;
8699 
8700   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8701 
8702   if (!AT.isValid()) {
8703     return true;
8704   }
8705 
8706   analyze_format_string::ArgType::MatchKind Match =
8707       AT.matchesType(S.Context, Ex->getType());
8708   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8709   if (Match == analyze_format_string::ArgType::Match)
8710     return true;
8711 
8712   ScanfSpecifier fixedFS = FS;
8713   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8714                                  S.getLangOpts(), S.Context);
8715 
8716   unsigned Diag =
8717       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8718                : diag::warn_format_conversion_argument_type_mismatch;
8719 
8720   if (Success) {
8721     // Get the fix string from the fixed format specifier.
8722     SmallString<128> buf;
8723     llvm::raw_svector_ostream os(buf);
8724     fixedFS.toString(os);
8725 
8726     EmitFormatDiagnostic(
8727         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8728                       << Ex->getType() << false << Ex->getSourceRange(),
8729         Ex->getBeginLoc(),
8730         /*IsStringLocation*/ false,
8731         getSpecifierRange(startSpecifier, specifierLen),
8732         FixItHint::CreateReplacement(
8733             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8734   } else {
8735     EmitFormatDiagnostic(S.PDiag(Diag)
8736                              << AT.getRepresentativeTypeName(S.Context)
8737                              << Ex->getType() << false << Ex->getSourceRange(),
8738                          Ex->getBeginLoc(),
8739                          /*IsStringLocation*/ false,
8740                          getSpecifierRange(startSpecifier, specifierLen));
8741   }
8742 
8743   return true;
8744 }
8745 
8746 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8747                               const Expr *OrigFormatExpr,
8748                               ArrayRef<const Expr *> Args,
8749                               bool HasVAListArg, unsigned format_idx,
8750                               unsigned firstDataArg,
8751                               Sema::FormatStringType Type,
8752                               bool inFunctionCall,
8753                               Sema::VariadicCallType CallType,
8754                               llvm::SmallBitVector &CheckedVarArgs,
8755                               UncoveredArgHandler &UncoveredArg,
8756                               bool IgnoreStringsWithoutSpecifiers) {
8757   // CHECK: is the format string a wide literal?
8758   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8759     CheckFormatHandler::EmitFormatDiagnostic(
8760         S, inFunctionCall, Args[format_idx],
8761         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8762         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8763     return;
8764   }
8765 
8766   // Str - The format string.  NOTE: this is NOT null-terminated!
8767   StringRef StrRef = FExpr->getString();
8768   const char *Str = StrRef.data();
8769   // Account for cases where the string literal is truncated in a declaration.
8770   const ConstantArrayType *T =
8771     S.Context.getAsConstantArrayType(FExpr->getType());
8772   assert(T && "String literal not of constant array type!");
8773   size_t TypeSize = T->getSize().getZExtValue();
8774   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8775   const unsigned numDataArgs = Args.size() - firstDataArg;
8776 
8777   if (IgnoreStringsWithoutSpecifiers &&
8778       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8779           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8780     return;
8781 
8782   // Emit a warning if the string literal is truncated and does not contain an
8783   // embedded null character.
8784   if (TypeSize <= StrRef.size() &&
8785       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8786     CheckFormatHandler::EmitFormatDiagnostic(
8787         S, inFunctionCall, Args[format_idx],
8788         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8789         FExpr->getBeginLoc(),
8790         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8791     return;
8792   }
8793 
8794   // CHECK: empty format string?
8795   if (StrLen == 0 && numDataArgs > 0) {
8796     CheckFormatHandler::EmitFormatDiagnostic(
8797         S, inFunctionCall, Args[format_idx],
8798         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8799         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8800     return;
8801   }
8802 
8803   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8804       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8805       Type == Sema::FST_OSTrace) {
8806     CheckPrintfHandler H(
8807         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8808         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8809         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8810         CheckedVarArgs, UncoveredArg);
8811 
8812     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8813                                                   S.getLangOpts(),
8814                                                   S.Context.getTargetInfo(),
8815                                             Type == Sema::FST_FreeBSDKPrintf))
8816       H.DoneProcessing();
8817   } else if (Type == Sema::FST_Scanf) {
8818     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8819                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8820                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8821 
8822     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8823                                                  S.getLangOpts(),
8824                                                  S.Context.getTargetInfo()))
8825       H.DoneProcessing();
8826   } // TODO: handle other formats
8827 }
8828 
8829 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8830   // Str - The format string.  NOTE: this is NOT null-terminated!
8831   StringRef StrRef = FExpr->getString();
8832   const char *Str = StrRef.data();
8833   // Account for cases where the string literal is truncated in a declaration.
8834   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8835   assert(T && "String literal not of constant array type!");
8836   size_t TypeSize = T->getSize().getZExtValue();
8837   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8838   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8839                                                          getLangOpts(),
8840                                                          Context.getTargetInfo());
8841 }
8842 
8843 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8844 
8845 // Returns the related absolute value function that is larger, of 0 if one
8846 // does not exist.
8847 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8848   switch (AbsFunction) {
8849   default:
8850     return 0;
8851 
8852   case Builtin::BI__builtin_abs:
8853     return Builtin::BI__builtin_labs;
8854   case Builtin::BI__builtin_labs:
8855     return Builtin::BI__builtin_llabs;
8856   case Builtin::BI__builtin_llabs:
8857     return 0;
8858 
8859   case Builtin::BI__builtin_fabsf:
8860     return Builtin::BI__builtin_fabs;
8861   case Builtin::BI__builtin_fabs:
8862     return Builtin::BI__builtin_fabsl;
8863   case Builtin::BI__builtin_fabsl:
8864     return 0;
8865 
8866   case Builtin::BI__builtin_cabsf:
8867     return Builtin::BI__builtin_cabs;
8868   case Builtin::BI__builtin_cabs:
8869     return Builtin::BI__builtin_cabsl;
8870   case Builtin::BI__builtin_cabsl:
8871     return 0;
8872 
8873   case Builtin::BIabs:
8874     return Builtin::BIlabs;
8875   case Builtin::BIlabs:
8876     return Builtin::BIllabs;
8877   case Builtin::BIllabs:
8878     return 0;
8879 
8880   case Builtin::BIfabsf:
8881     return Builtin::BIfabs;
8882   case Builtin::BIfabs:
8883     return Builtin::BIfabsl;
8884   case Builtin::BIfabsl:
8885     return 0;
8886 
8887   case Builtin::BIcabsf:
8888    return Builtin::BIcabs;
8889   case Builtin::BIcabs:
8890     return Builtin::BIcabsl;
8891   case Builtin::BIcabsl:
8892     return 0;
8893   }
8894 }
8895 
8896 // Returns the argument type of the absolute value function.
8897 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8898                                              unsigned AbsType) {
8899   if (AbsType == 0)
8900     return QualType();
8901 
8902   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8903   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8904   if (Error != ASTContext::GE_None)
8905     return QualType();
8906 
8907   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8908   if (!FT)
8909     return QualType();
8910 
8911   if (FT->getNumParams() != 1)
8912     return QualType();
8913 
8914   return FT->getParamType(0);
8915 }
8916 
8917 // Returns the best absolute value function, or zero, based on type and
8918 // current absolute value function.
8919 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8920                                    unsigned AbsFunctionKind) {
8921   unsigned BestKind = 0;
8922   uint64_t ArgSize = Context.getTypeSize(ArgType);
8923   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8924        Kind = getLargerAbsoluteValueFunction(Kind)) {
8925     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8926     if (Context.getTypeSize(ParamType) >= ArgSize) {
8927       if (BestKind == 0)
8928         BestKind = Kind;
8929       else if (Context.hasSameType(ParamType, ArgType)) {
8930         BestKind = Kind;
8931         break;
8932       }
8933     }
8934   }
8935   return BestKind;
8936 }
8937 
8938 enum AbsoluteValueKind {
8939   AVK_Integer,
8940   AVK_Floating,
8941   AVK_Complex
8942 };
8943 
8944 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8945   if (T->isIntegralOrEnumerationType())
8946     return AVK_Integer;
8947   if (T->isRealFloatingType())
8948     return AVK_Floating;
8949   if (T->isAnyComplexType())
8950     return AVK_Complex;
8951 
8952   llvm_unreachable("Type not integer, floating, or complex");
8953 }
8954 
8955 // Changes the absolute value function to a different type.  Preserves whether
8956 // the function is a builtin.
8957 static unsigned changeAbsFunction(unsigned AbsKind,
8958                                   AbsoluteValueKind ValueKind) {
8959   switch (ValueKind) {
8960   case AVK_Integer:
8961     switch (AbsKind) {
8962     default:
8963       return 0;
8964     case Builtin::BI__builtin_fabsf:
8965     case Builtin::BI__builtin_fabs:
8966     case Builtin::BI__builtin_fabsl:
8967     case Builtin::BI__builtin_cabsf:
8968     case Builtin::BI__builtin_cabs:
8969     case Builtin::BI__builtin_cabsl:
8970       return Builtin::BI__builtin_abs;
8971     case Builtin::BIfabsf:
8972     case Builtin::BIfabs:
8973     case Builtin::BIfabsl:
8974     case Builtin::BIcabsf:
8975     case Builtin::BIcabs:
8976     case Builtin::BIcabsl:
8977       return Builtin::BIabs;
8978     }
8979   case AVK_Floating:
8980     switch (AbsKind) {
8981     default:
8982       return 0;
8983     case Builtin::BI__builtin_abs:
8984     case Builtin::BI__builtin_labs:
8985     case Builtin::BI__builtin_llabs:
8986     case Builtin::BI__builtin_cabsf:
8987     case Builtin::BI__builtin_cabs:
8988     case Builtin::BI__builtin_cabsl:
8989       return Builtin::BI__builtin_fabsf;
8990     case Builtin::BIabs:
8991     case Builtin::BIlabs:
8992     case Builtin::BIllabs:
8993     case Builtin::BIcabsf:
8994     case Builtin::BIcabs:
8995     case Builtin::BIcabsl:
8996       return Builtin::BIfabsf;
8997     }
8998   case AVK_Complex:
8999     switch (AbsKind) {
9000     default:
9001       return 0;
9002     case Builtin::BI__builtin_abs:
9003     case Builtin::BI__builtin_labs:
9004     case Builtin::BI__builtin_llabs:
9005     case Builtin::BI__builtin_fabsf:
9006     case Builtin::BI__builtin_fabs:
9007     case Builtin::BI__builtin_fabsl:
9008       return Builtin::BI__builtin_cabsf;
9009     case Builtin::BIabs:
9010     case Builtin::BIlabs:
9011     case Builtin::BIllabs:
9012     case Builtin::BIfabsf:
9013     case Builtin::BIfabs:
9014     case Builtin::BIfabsl:
9015       return Builtin::BIcabsf;
9016     }
9017   }
9018   llvm_unreachable("Unable to convert function");
9019 }
9020 
9021 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9022   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9023   if (!FnInfo)
9024     return 0;
9025 
9026   switch (FDecl->getBuiltinID()) {
9027   default:
9028     return 0;
9029   case Builtin::BI__builtin_abs:
9030   case Builtin::BI__builtin_fabs:
9031   case Builtin::BI__builtin_fabsf:
9032   case Builtin::BI__builtin_fabsl:
9033   case Builtin::BI__builtin_labs:
9034   case Builtin::BI__builtin_llabs:
9035   case Builtin::BI__builtin_cabs:
9036   case Builtin::BI__builtin_cabsf:
9037   case Builtin::BI__builtin_cabsl:
9038   case Builtin::BIabs:
9039   case Builtin::BIlabs:
9040   case Builtin::BIllabs:
9041   case Builtin::BIfabs:
9042   case Builtin::BIfabsf:
9043   case Builtin::BIfabsl:
9044   case Builtin::BIcabs:
9045   case Builtin::BIcabsf:
9046   case Builtin::BIcabsl:
9047     return FDecl->getBuiltinID();
9048   }
9049   llvm_unreachable("Unknown Builtin type");
9050 }
9051 
9052 // If the replacement is valid, emit a note with replacement function.
9053 // Additionally, suggest including the proper header if not already included.
9054 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9055                             unsigned AbsKind, QualType ArgType) {
9056   bool EmitHeaderHint = true;
9057   const char *HeaderName = nullptr;
9058   const char *FunctionName = nullptr;
9059   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9060     FunctionName = "std::abs";
9061     if (ArgType->isIntegralOrEnumerationType()) {
9062       HeaderName = "cstdlib";
9063     } else if (ArgType->isRealFloatingType()) {
9064       HeaderName = "cmath";
9065     } else {
9066       llvm_unreachable("Invalid Type");
9067     }
9068 
9069     // Lookup all std::abs
9070     if (NamespaceDecl *Std = S.getStdNamespace()) {
9071       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9072       R.suppressDiagnostics();
9073       S.LookupQualifiedName(R, Std);
9074 
9075       for (const auto *I : R) {
9076         const FunctionDecl *FDecl = nullptr;
9077         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9078           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9079         } else {
9080           FDecl = dyn_cast<FunctionDecl>(I);
9081         }
9082         if (!FDecl)
9083           continue;
9084 
9085         // Found std::abs(), check that they are the right ones.
9086         if (FDecl->getNumParams() != 1)
9087           continue;
9088 
9089         // Check that the parameter type can handle the argument.
9090         QualType ParamType = FDecl->getParamDecl(0)->getType();
9091         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9092             S.Context.getTypeSize(ArgType) <=
9093                 S.Context.getTypeSize(ParamType)) {
9094           // Found a function, don't need the header hint.
9095           EmitHeaderHint = false;
9096           break;
9097         }
9098       }
9099     }
9100   } else {
9101     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9102     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9103 
9104     if (HeaderName) {
9105       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9106       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9107       R.suppressDiagnostics();
9108       S.LookupName(R, S.getCurScope());
9109 
9110       if (R.isSingleResult()) {
9111         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9112         if (FD && FD->getBuiltinID() == AbsKind) {
9113           EmitHeaderHint = false;
9114         } else {
9115           return;
9116         }
9117       } else if (!R.empty()) {
9118         return;
9119       }
9120     }
9121   }
9122 
9123   S.Diag(Loc, diag::note_replace_abs_function)
9124       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9125 
9126   if (!HeaderName)
9127     return;
9128 
9129   if (!EmitHeaderHint)
9130     return;
9131 
9132   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9133                                                     << FunctionName;
9134 }
9135 
9136 template <std::size_t StrLen>
9137 static bool IsStdFunction(const FunctionDecl *FDecl,
9138                           const char (&Str)[StrLen]) {
9139   if (!FDecl)
9140     return false;
9141   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9142     return false;
9143   if (!FDecl->isInStdNamespace())
9144     return false;
9145 
9146   return true;
9147 }
9148 
9149 // Warn when using the wrong abs() function.
9150 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9151                                       const FunctionDecl *FDecl) {
9152   if (Call->getNumArgs() != 1)
9153     return;
9154 
9155   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9156   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9157   if (AbsKind == 0 && !IsStdAbs)
9158     return;
9159 
9160   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9161   QualType ParamType = Call->getArg(0)->getType();
9162 
9163   // Unsigned types cannot be negative.  Suggest removing the absolute value
9164   // function call.
9165   if (ArgType->isUnsignedIntegerType()) {
9166     const char *FunctionName =
9167         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9168     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9169     Diag(Call->getExprLoc(), diag::note_remove_abs)
9170         << FunctionName
9171         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9172     return;
9173   }
9174 
9175   // Taking the absolute value of a pointer is very suspicious, they probably
9176   // wanted to index into an array, dereference a pointer, call a function, etc.
9177   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9178     unsigned DiagType = 0;
9179     if (ArgType->isFunctionType())
9180       DiagType = 1;
9181     else if (ArgType->isArrayType())
9182       DiagType = 2;
9183 
9184     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9185     return;
9186   }
9187 
9188   // std::abs has overloads which prevent most of the absolute value problems
9189   // from occurring.
9190   if (IsStdAbs)
9191     return;
9192 
9193   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9194   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9195 
9196   // The argument and parameter are the same kind.  Check if they are the right
9197   // size.
9198   if (ArgValueKind == ParamValueKind) {
9199     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9200       return;
9201 
9202     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9203     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9204         << FDecl << ArgType << ParamType;
9205 
9206     if (NewAbsKind == 0)
9207       return;
9208 
9209     emitReplacement(*this, Call->getExprLoc(),
9210                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9211     return;
9212   }
9213 
9214   // ArgValueKind != ParamValueKind
9215   // The wrong type of absolute value function was used.  Attempt to find the
9216   // proper one.
9217   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9218   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9219   if (NewAbsKind == 0)
9220     return;
9221 
9222   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9223       << FDecl << ParamValueKind << ArgValueKind;
9224 
9225   emitReplacement(*this, Call->getExprLoc(),
9226                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9227 }
9228 
9229 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9230 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9231                                 const FunctionDecl *FDecl) {
9232   if (!Call || !FDecl) return;
9233 
9234   // Ignore template specializations and macros.
9235   if (inTemplateInstantiation()) return;
9236   if (Call->getExprLoc().isMacroID()) return;
9237 
9238   // Only care about the one template argument, two function parameter std::max
9239   if (Call->getNumArgs() != 2) return;
9240   if (!IsStdFunction(FDecl, "max")) return;
9241   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9242   if (!ArgList) return;
9243   if (ArgList->size() != 1) return;
9244 
9245   // Check that template type argument is unsigned integer.
9246   const auto& TA = ArgList->get(0);
9247   if (TA.getKind() != TemplateArgument::Type) return;
9248   QualType ArgType = TA.getAsType();
9249   if (!ArgType->isUnsignedIntegerType()) return;
9250 
9251   // See if either argument is a literal zero.
9252   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9253     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9254     if (!MTE) return false;
9255     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9256     if (!Num) return false;
9257     if (Num->getValue() != 0) return false;
9258     return true;
9259   };
9260 
9261   const Expr *FirstArg = Call->getArg(0);
9262   const Expr *SecondArg = Call->getArg(1);
9263   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9264   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9265 
9266   // Only warn when exactly one argument is zero.
9267   if (IsFirstArgZero == IsSecondArgZero) return;
9268 
9269   SourceRange FirstRange = FirstArg->getSourceRange();
9270   SourceRange SecondRange = SecondArg->getSourceRange();
9271 
9272   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9273 
9274   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9275       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9276 
9277   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9278   SourceRange RemovalRange;
9279   if (IsFirstArgZero) {
9280     RemovalRange = SourceRange(FirstRange.getBegin(),
9281                                SecondRange.getBegin().getLocWithOffset(-1));
9282   } else {
9283     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9284                                SecondRange.getEnd());
9285   }
9286 
9287   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9288         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9289         << FixItHint::CreateRemoval(RemovalRange);
9290 }
9291 
9292 //===--- CHECK: Standard memory functions ---------------------------------===//
9293 
9294 /// Takes the expression passed to the size_t parameter of functions
9295 /// such as memcmp, strncat, etc and warns if it's a comparison.
9296 ///
9297 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9298 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9299                                            IdentifierInfo *FnName,
9300                                            SourceLocation FnLoc,
9301                                            SourceLocation RParenLoc) {
9302   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9303   if (!Size)
9304     return false;
9305 
9306   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9307   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9308     return false;
9309 
9310   SourceRange SizeRange = Size->getSourceRange();
9311   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9312       << SizeRange << FnName;
9313   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9314       << FnName
9315       << FixItHint::CreateInsertion(
9316              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9317       << FixItHint::CreateRemoval(RParenLoc);
9318   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9319       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9320       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9321                                     ")");
9322 
9323   return true;
9324 }
9325 
9326 /// Determine whether the given type is or contains a dynamic class type
9327 /// (e.g., whether it has a vtable).
9328 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9329                                                      bool &IsContained) {
9330   // Look through array types while ignoring qualifiers.
9331   const Type *Ty = T->getBaseElementTypeUnsafe();
9332   IsContained = false;
9333 
9334   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9335   RD = RD ? RD->getDefinition() : nullptr;
9336   if (!RD || RD->isInvalidDecl())
9337     return nullptr;
9338 
9339   if (RD->isDynamicClass())
9340     return RD;
9341 
9342   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9343   // It's impossible for a class to transitively contain itself by value, so
9344   // infinite recursion is impossible.
9345   for (auto *FD : RD->fields()) {
9346     bool SubContained;
9347     if (const CXXRecordDecl *ContainedRD =
9348             getContainedDynamicClass(FD->getType(), SubContained)) {
9349       IsContained = true;
9350       return ContainedRD;
9351     }
9352   }
9353 
9354   return nullptr;
9355 }
9356 
9357 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9358   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9359     if (Unary->getKind() == UETT_SizeOf)
9360       return Unary;
9361   return nullptr;
9362 }
9363 
9364 /// If E is a sizeof expression, returns its argument expression,
9365 /// otherwise returns NULL.
9366 static const Expr *getSizeOfExprArg(const Expr *E) {
9367   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9368     if (!SizeOf->isArgumentType())
9369       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9370   return nullptr;
9371 }
9372 
9373 /// If E is a sizeof expression, returns its argument type.
9374 static QualType getSizeOfArgType(const Expr *E) {
9375   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9376     return SizeOf->getTypeOfArgument();
9377   return QualType();
9378 }
9379 
9380 namespace {
9381 
9382 struct SearchNonTrivialToInitializeField
9383     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9384   using Super =
9385       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9386 
9387   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9388 
9389   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9390                      SourceLocation SL) {
9391     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9392       asDerived().visitArray(PDIK, AT, SL);
9393       return;
9394     }
9395 
9396     Super::visitWithKind(PDIK, FT, SL);
9397   }
9398 
9399   void visitARCStrong(QualType FT, SourceLocation SL) {
9400     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9401   }
9402   void visitARCWeak(QualType FT, SourceLocation SL) {
9403     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9404   }
9405   void visitStruct(QualType FT, SourceLocation SL) {
9406     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9407       visit(FD->getType(), FD->getLocation());
9408   }
9409   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9410                   const ArrayType *AT, SourceLocation SL) {
9411     visit(getContext().getBaseElementType(AT), SL);
9412   }
9413   void visitTrivial(QualType FT, SourceLocation SL) {}
9414 
9415   static void diag(QualType RT, const Expr *E, Sema &S) {
9416     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9417   }
9418 
9419   ASTContext &getContext() { return S.getASTContext(); }
9420 
9421   const Expr *E;
9422   Sema &S;
9423 };
9424 
9425 struct SearchNonTrivialToCopyField
9426     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9427   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9428 
9429   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9430 
9431   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9432                      SourceLocation SL) {
9433     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9434       asDerived().visitArray(PCK, AT, SL);
9435       return;
9436     }
9437 
9438     Super::visitWithKind(PCK, FT, SL);
9439   }
9440 
9441   void visitARCStrong(QualType FT, SourceLocation SL) {
9442     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9443   }
9444   void visitARCWeak(QualType FT, SourceLocation SL) {
9445     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9446   }
9447   void visitStruct(QualType FT, SourceLocation SL) {
9448     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9449       visit(FD->getType(), FD->getLocation());
9450   }
9451   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9452                   SourceLocation SL) {
9453     visit(getContext().getBaseElementType(AT), SL);
9454   }
9455   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9456                 SourceLocation SL) {}
9457   void visitTrivial(QualType FT, SourceLocation SL) {}
9458   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9459 
9460   static void diag(QualType RT, const Expr *E, Sema &S) {
9461     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9462   }
9463 
9464   ASTContext &getContext() { return S.getASTContext(); }
9465 
9466   const Expr *E;
9467   Sema &S;
9468 };
9469 
9470 }
9471 
9472 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9473 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9474   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9475 
9476   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9477     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9478       return false;
9479 
9480     return doesExprLikelyComputeSize(BO->getLHS()) ||
9481            doesExprLikelyComputeSize(BO->getRHS());
9482   }
9483 
9484   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9485 }
9486 
9487 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9488 ///
9489 /// \code
9490 ///   #define MACRO 0
9491 ///   foo(MACRO);
9492 ///   foo(0);
9493 /// \endcode
9494 ///
9495 /// This should return true for the first call to foo, but not for the second
9496 /// (regardless of whether foo is a macro or function).
9497 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9498                                         SourceLocation CallLoc,
9499                                         SourceLocation ArgLoc) {
9500   if (!CallLoc.isMacroID())
9501     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9502 
9503   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9504          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9505 }
9506 
9507 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9508 /// last two arguments transposed.
9509 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9510   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9511     return;
9512 
9513   const Expr *SizeArg =
9514     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9515 
9516   auto isLiteralZero = [](const Expr *E) {
9517     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9518   };
9519 
9520   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9521   SourceLocation CallLoc = Call->getRParenLoc();
9522   SourceManager &SM = S.getSourceManager();
9523   if (isLiteralZero(SizeArg) &&
9524       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9525 
9526     SourceLocation DiagLoc = SizeArg->getExprLoc();
9527 
9528     // Some platforms #define bzero to __builtin_memset. See if this is the
9529     // case, and if so, emit a better diagnostic.
9530     if (BId == Builtin::BIbzero ||
9531         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9532                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9533       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9534       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9535     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9536       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9537       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9538     }
9539     return;
9540   }
9541 
9542   // If the second argument to a memset is a sizeof expression and the third
9543   // isn't, this is also likely an error. This should catch
9544   // 'memset(buf, sizeof(buf), 0xff)'.
9545   if (BId == Builtin::BImemset &&
9546       doesExprLikelyComputeSize(Call->getArg(1)) &&
9547       !doesExprLikelyComputeSize(Call->getArg(2))) {
9548     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9549     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9550     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9551     return;
9552   }
9553 }
9554 
9555 /// Check for dangerous or invalid arguments to memset().
9556 ///
9557 /// This issues warnings on known problematic, dangerous or unspecified
9558 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9559 /// function calls.
9560 ///
9561 /// \param Call The call expression to diagnose.
9562 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9563                                    unsigned BId,
9564                                    IdentifierInfo *FnName) {
9565   assert(BId != 0);
9566 
9567   // It is possible to have a non-standard definition of memset.  Validate
9568   // we have enough arguments, and if not, abort further checking.
9569   unsigned ExpectedNumArgs =
9570       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9571   if (Call->getNumArgs() < ExpectedNumArgs)
9572     return;
9573 
9574   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9575                       BId == Builtin::BIstrndup ? 1 : 2);
9576   unsigned LenArg =
9577       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9578   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9579 
9580   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9581                                      Call->getBeginLoc(), Call->getRParenLoc()))
9582     return;
9583 
9584   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9585   CheckMemaccessSize(*this, BId, Call);
9586 
9587   // We have special checking when the length is a sizeof expression.
9588   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9589   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9590   llvm::FoldingSetNodeID SizeOfArgID;
9591 
9592   // Although widely used, 'bzero' is not a standard function. Be more strict
9593   // with the argument types before allowing diagnostics and only allow the
9594   // form bzero(ptr, sizeof(...)).
9595   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9596   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9597     return;
9598 
9599   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9600     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9601     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9602 
9603     QualType DestTy = Dest->getType();
9604     QualType PointeeTy;
9605     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9606       PointeeTy = DestPtrTy->getPointeeType();
9607 
9608       // Never warn about void type pointers. This can be used to suppress
9609       // false positives.
9610       if (PointeeTy->isVoidType())
9611         continue;
9612 
9613       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9614       // actually comparing the expressions for equality. Because computing the
9615       // expression IDs can be expensive, we only do this if the diagnostic is
9616       // enabled.
9617       if (SizeOfArg &&
9618           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9619                            SizeOfArg->getExprLoc())) {
9620         // We only compute IDs for expressions if the warning is enabled, and
9621         // cache the sizeof arg's ID.
9622         if (SizeOfArgID == llvm::FoldingSetNodeID())
9623           SizeOfArg->Profile(SizeOfArgID, Context, true);
9624         llvm::FoldingSetNodeID DestID;
9625         Dest->Profile(DestID, Context, true);
9626         if (DestID == SizeOfArgID) {
9627           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9628           //       over sizeof(src) as well.
9629           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9630           StringRef ReadableName = FnName->getName();
9631 
9632           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9633             if (UnaryOp->getOpcode() == UO_AddrOf)
9634               ActionIdx = 1; // If its an address-of operator, just remove it.
9635           if (!PointeeTy->isIncompleteType() &&
9636               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9637             ActionIdx = 2; // If the pointee's size is sizeof(char),
9638                            // suggest an explicit length.
9639 
9640           // If the function is defined as a builtin macro, do not show macro
9641           // expansion.
9642           SourceLocation SL = SizeOfArg->getExprLoc();
9643           SourceRange DSR = Dest->getSourceRange();
9644           SourceRange SSR = SizeOfArg->getSourceRange();
9645           SourceManager &SM = getSourceManager();
9646 
9647           if (SM.isMacroArgExpansion(SL)) {
9648             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9649             SL = SM.getSpellingLoc(SL);
9650             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9651                              SM.getSpellingLoc(DSR.getEnd()));
9652             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9653                              SM.getSpellingLoc(SSR.getEnd()));
9654           }
9655 
9656           DiagRuntimeBehavior(SL, SizeOfArg,
9657                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9658                                 << ReadableName
9659                                 << PointeeTy
9660                                 << DestTy
9661                                 << DSR
9662                                 << SSR);
9663           DiagRuntimeBehavior(SL, SizeOfArg,
9664                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9665                                 << ActionIdx
9666                                 << SSR);
9667 
9668           break;
9669         }
9670       }
9671 
9672       // Also check for cases where the sizeof argument is the exact same
9673       // type as the memory argument, and where it points to a user-defined
9674       // record type.
9675       if (SizeOfArgTy != QualType()) {
9676         if (PointeeTy->isRecordType() &&
9677             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9678           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9679                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9680                                 << FnName << SizeOfArgTy << ArgIdx
9681                                 << PointeeTy << Dest->getSourceRange()
9682                                 << LenExpr->getSourceRange());
9683           break;
9684         }
9685       }
9686     } else if (DestTy->isArrayType()) {
9687       PointeeTy = DestTy;
9688     }
9689 
9690     if (PointeeTy == QualType())
9691       continue;
9692 
9693     // Always complain about dynamic classes.
9694     bool IsContained;
9695     if (const CXXRecordDecl *ContainedRD =
9696             getContainedDynamicClass(PointeeTy, IsContained)) {
9697 
9698       unsigned OperationType = 0;
9699       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9700       // "overwritten" if we're warning about the destination for any call
9701       // but memcmp; otherwise a verb appropriate to the call.
9702       if (ArgIdx != 0 || IsCmp) {
9703         if (BId == Builtin::BImemcpy)
9704           OperationType = 1;
9705         else if(BId == Builtin::BImemmove)
9706           OperationType = 2;
9707         else if (IsCmp)
9708           OperationType = 3;
9709       }
9710 
9711       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9712                           PDiag(diag::warn_dyn_class_memaccess)
9713                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9714                               << IsContained << ContainedRD << OperationType
9715                               << Call->getCallee()->getSourceRange());
9716     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9717              BId != Builtin::BImemset)
9718       DiagRuntimeBehavior(
9719         Dest->getExprLoc(), Dest,
9720         PDiag(diag::warn_arc_object_memaccess)
9721           << ArgIdx << FnName << PointeeTy
9722           << Call->getCallee()->getSourceRange());
9723     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9724       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9725           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9726         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9727                             PDiag(diag::warn_cstruct_memaccess)
9728                                 << ArgIdx << FnName << PointeeTy << 0);
9729         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9730       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9731                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9732         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9733                             PDiag(diag::warn_cstruct_memaccess)
9734                                 << ArgIdx << FnName << PointeeTy << 1);
9735         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9736       } else {
9737         continue;
9738       }
9739     } else
9740       continue;
9741 
9742     DiagRuntimeBehavior(
9743       Dest->getExprLoc(), Dest,
9744       PDiag(diag::note_bad_memaccess_silence)
9745         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9746     break;
9747   }
9748 }
9749 
9750 // A little helper routine: ignore addition and subtraction of integer literals.
9751 // This intentionally does not ignore all integer constant expressions because
9752 // we don't want to remove sizeof().
9753 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9754   Ex = Ex->IgnoreParenCasts();
9755 
9756   while (true) {
9757     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9758     if (!BO || !BO->isAdditiveOp())
9759       break;
9760 
9761     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9762     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9763 
9764     if (isa<IntegerLiteral>(RHS))
9765       Ex = LHS;
9766     else if (isa<IntegerLiteral>(LHS))
9767       Ex = RHS;
9768     else
9769       break;
9770   }
9771 
9772   return Ex;
9773 }
9774 
9775 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9776                                                       ASTContext &Context) {
9777   // Only handle constant-sized or VLAs, but not flexible members.
9778   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9779     // Only issue the FIXIT for arrays of size > 1.
9780     if (CAT->getSize().getSExtValue() <= 1)
9781       return false;
9782   } else if (!Ty->isVariableArrayType()) {
9783     return false;
9784   }
9785   return true;
9786 }
9787 
9788 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9789 // be the size of the source, instead of the destination.
9790 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9791                                     IdentifierInfo *FnName) {
9792 
9793   // Don't crash if the user has the wrong number of arguments
9794   unsigned NumArgs = Call->getNumArgs();
9795   if ((NumArgs != 3) && (NumArgs != 4))
9796     return;
9797 
9798   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9799   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9800   const Expr *CompareWithSrc = nullptr;
9801 
9802   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9803                                      Call->getBeginLoc(), Call->getRParenLoc()))
9804     return;
9805 
9806   // Look for 'strlcpy(dst, x, sizeof(x))'
9807   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9808     CompareWithSrc = Ex;
9809   else {
9810     // Look for 'strlcpy(dst, x, strlen(x))'
9811     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9812       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9813           SizeCall->getNumArgs() == 1)
9814         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9815     }
9816   }
9817 
9818   if (!CompareWithSrc)
9819     return;
9820 
9821   // Determine if the argument to sizeof/strlen is equal to the source
9822   // argument.  In principle there's all kinds of things you could do
9823   // here, for instance creating an == expression and evaluating it with
9824   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9825   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9826   if (!SrcArgDRE)
9827     return;
9828 
9829   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9830   if (!CompareWithSrcDRE ||
9831       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9832     return;
9833 
9834   const Expr *OriginalSizeArg = Call->getArg(2);
9835   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9836       << OriginalSizeArg->getSourceRange() << FnName;
9837 
9838   // Output a FIXIT hint if the destination is an array (rather than a
9839   // pointer to an array).  This could be enhanced to handle some
9840   // pointers if we know the actual size, like if DstArg is 'array+2'
9841   // we could say 'sizeof(array)-2'.
9842   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9843   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9844     return;
9845 
9846   SmallString<128> sizeString;
9847   llvm::raw_svector_ostream OS(sizeString);
9848   OS << "sizeof(";
9849   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9850   OS << ")";
9851 
9852   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9853       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9854                                       OS.str());
9855 }
9856 
9857 /// Check if two expressions refer to the same declaration.
9858 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9859   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9860     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9861       return D1->getDecl() == D2->getDecl();
9862   return false;
9863 }
9864 
9865 static const Expr *getStrlenExprArg(const Expr *E) {
9866   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9867     const FunctionDecl *FD = CE->getDirectCallee();
9868     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9869       return nullptr;
9870     return CE->getArg(0)->IgnoreParenCasts();
9871   }
9872   return nullptr;
9873 }
9874 
9875 // Warn on anti-patterns as the 'size' argument to strncat.
9876 // The correct size argument should look like following:
9877 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9878 void Sema::CheckStrncatArguments(const CallExpr *CE,
9879                                  IdentifierInfo *FnName) {
9880   // Don't crash if the user has the wrong number of arguments.
9881   if (CE->getNumArgs() < 3)
9882     return;
9883   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9884   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9885   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9886 
9887   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9888                                      CE->getRParenLoc()))
9889     return;
9890 
9891   // Identify common expressions, which are wrongly used as the size argument
9892   // to strncat and may lead to buffer overflows.
9893   unsigned PatternType = 0;
9894   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9895     // - sizeof(dst)
9896     if (referToTheSameDecl(SizeOfArg, DstArg))
9897       PatternType = 1;
9898     // - sizeof(src)
9899     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9900       PatternType = 2;
9901   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9902     if (BE->getOpcode() == BO_Sub) {
9903       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9904       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9905       // - sizeof(dst) - strlen(dst)
9906       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9907           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9908         PatternType = 1;
9909       // - sizeof(src) - (anything)
9910       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9911         PatternType = 2;
9912     }
9913   }
9914 
9915   if (PatternType == 0)
9916     return;
9917 
9918   // Generate the diagnostic.
9919   SourceLocation SL = LenArg->getBeginLoc();
9920   SourceRange SR = LenArg->getSourceRange();
9921   SourceManager &SM = getSourceManager();
9922 
9923   // If the function is defined as a builtin macro, do not show macro expansion.
9924   if (SM.isMacroArgExpansion(SL)) {
9925     SL = SM.getSpellingLoc(SL);
9926     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9927                      SM.getSpellingLoc(SR.getEnd()));
9928   }
9929 
9930   // Check if the destination is an array (rather than a pointer to an array).
9931   QualType DstTy = DstArg->getType();
9932   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9933                                                                     Context);
9934   if (!isKnownSizeArray) {
9935     if (PatternType == 1)
9936       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9937     else
9938       Diag(SL, diag::warn_strncat_src_size) << SR;
9939     return;
9940   }
9941 
9942   if (PatternType == 1)
9943     Diag(SL, diag::warn_strncat_large_size) << SR;
9944   else
9945     Diag(SL, diag::warn_strncat_src_size) << SR;
9946 
9947   SmallString<128> sizeString;
9948   llvm::raw_svector_ostream OS(sizeString);
9949   OS << "sizeof(";
9950   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9951   OS << ") - ";
9952   OS << "strlen(";
9953   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9954   OS << ") - 1";
9955 
9956   Diag(SL, diag::note_strncat_wrong_size)
9957     << FixItHint::CreateReplacement(SR, OS.str());
9958 }
9959 
9960 void
9961 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9962                          SourceLocation ReturnLoc,
9963                          bool isObjCMethod,
9964                          const AttrVec *Attrs,
9965                          const FunctionDecl *FD) {
9966   // Check if the return value is null but should not be.
9967   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9968        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9969       CheckNonNullExpr(*this, RetValExp))
9970     Diag(ReturnLoc, diag::warn_null_ret)
9971       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9972 
9973   // C++11 [basic.stc.dynamic.allocation]p4:
9974   //   If an allocation function declared with a non-throwing
9975   //   exception-specification fails to allocate storage, it shall return
9976   //   a null pointer. Any other allocation function that fails to allocate
9977   //   storage shall indicate failure only by throwing an exception [...]
9978   if (FD) {
9979     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9980     if (Op == OO_New || Op == OO_Array_New) {
9981       const FunctionProtoType *Proto
9982         = FD->getType()->castAs<FunctionProtoType>();
9983       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9984           CheckNonNullExpr(*this, RetValExp))
9985         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9986           << FD << getLangOpts().CPlusPlus11;
9987     }
9988   }
9989 }
9990 
9991 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9992 
9993 /// Check for comparisons of floating point operands using != and ==.
9994 /// Issue a warning if these are no self-comparisons, as they are not likely
9995 /// to do what the programmer intended.
9996 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9997   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9998   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9999 
10000   // Special case: check for x == x (which is OK).
10001   // Do not emit warnings for such cases.
10002   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10003     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10004       if (DRL->getDecl() == DRR->getDecl())
10005         return;
10006 
10007   // Special case: check for comparisons against literals that can be exactly
10008   //  represented by APFloat.  In such cases, do not emit a warning.  This
10009   //  is a heuristic: often comparison against such literals are used to
10010   //  detect if a value in a variable has not changed.  This clearly can
10011   //  lead to false negatives.
10012   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10013     if (FLL->isExact())
10014       return;
10015   } else
10016     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10017       if (FLR->isExact())
10018         return;
10019 
10020   // Check for comparisons with builtin types.
10021   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10022     if (CL->getBuiltinCallee())
10023       return;
10024 
10025   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10026     if (CR->getBuiltinCallee())
10027       return;
10028 
10029   // Emit the diagnostic.
10030   Diag(Loc, diag::warn_floatingpoint_eq)
10031     << LHS->getSourceRange() << RHS->getSourceRange();
10032 }
10033 
10034 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10035 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10036 
10037 namespace {
10038 
10039 /// Structure recording the 'active' range of an integer-valued
10040 /// expression.
10041 struct IntRange {
10042   /// The number of bits active in the int.
10043   unsigned Width;
10044 
10045   /// True if the int is known not to have negative values.
10046   bool NonNegative;
10047 
10048   IntRange(unsigned Width, bool NonNegative)
10049       : Width(Width), NonNegative(NonNegative) {}
10050 
10051   /// Returns the range of the bool type.
10052   static IntRange forBoolType() {
10053     return IntRange(1, true);
10054   }
10055 
10056   /// Returns the range of an opaque value of the given integral type.
10057   static IntRange forValueOfType(ASTContext &C, QualType T) {
10058     return forValueOfCanonicalType(C,
10059                           T->getCanonicalTypeInternal().getTypePtr());
10060   }
10061 
10062   /// Returns the range of an opaque value of a canonical integral type.
10063   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10064     assert(T->isCanonicalUnqualified());
10065 
10066     if (const VectorType *VT = dyn_cast<VectorType>(T))
10067       T = VT->getElementType().getTypePtr();
10068     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10069       T = CT->getElementType().getTypePtr();
10070     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10071       T = AT->getValueType().getTypePtr();
10072 
10073     if (!C.getLangOpts().CPlusPlus) {
10074       // For enum types in C code, use the underlying datatype.
10075       if (const EnumType *ET = dyn_cast<EnumType>(T))
10076         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10077     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10078       // For enum types in C++, use the known bit width of the enumerators.
10079       EnumDecl *Enum = ET->getDecl();
10080       // In C++11, enums can have a fixed underlying type. Use this type to
10081       // compute the range.
10082       if (Enum->isFixed()) {
10083         return IntRange(C.getIntWidth(QualType(T, 0)),
10084                         !ET->isSignedIntegerOrEnumerationType());
10085       }
10086 
10087       unsigned NumPositive = Enum->getNumPositiveBits();
10088       unsigned NumNegative = Enum->getNumNegativeBits();
10089 
10090       if (NumNegative == 0)
10091         return IntRange(NumPositive, true/*NonNegative*/);
10092       else
10093         return IntRange(std::max(NumPositive + 1, NumNegative),
10094                         false/*NonNegative*/);
10095     }
10096 
10097     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10098       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10099 
10100     const BuiltinType *BT = cast<BuiltinType>(T);
10101     assert(BT->isInteger());
10102 
10103     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10104   }
10105 
10106   /// Returns the "target" range of a canonical integral type, i.e.
10107   /// the range of values expressible in the type.
10108   ///
10109   /// This matches forValueOfCanonicalType except that enums have the
10110   /// full range of their type, not the range of their enumerators.
10111   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10112     assert(T->isCanonicalUnqualified());
10113 
10114     if (const VectorType *VT = dyn_cast<VectorType>(T))
10115       T = VT->getElementType().getTypePtr();
10116     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10117       T = CT->getElementType().getTypePtr();
10118     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10119       T = AT->getValueType().getTypePtr();
10120     if (const EnumType *ET = dyn_cast<EnumType>(T))
10121       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10122 
10123     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10124       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10125 
10126     const BuiltinType *BT = cast<BuiltinType>(T);
10127     assert(BT->isInteger());
10128 
10129     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10130   }
10131 
10132   /// Returns the supremum of two ranges: i.e. their conservative merge.
10133   static IntRange join(IntRange L, IntRange R) {
10134     return IntRange(std::max(L.Width, R.Width),
10135                     L.NonNegative && R.NonNegative);
10136   }
10137 
10138   /// Returns the infinum of two ranges: i.e. their aggressive merge.
10139   static IntRange meet(IntRange L, IntRange R) {
10140     return IntRange(std::min(L.Width, R.Width),
10141                     L.NonNegative || R.NonNegative);
10142   }
10143 };
10144 
10145 } // namespace
10146 
10147 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10148                               unsigned MaxWidth) {
10149   if (value.isSigned() && value.isNegative())
10150     return IntRange(value.getMinSignedBits(), false);
10151 
10152   if (value.getBitWidth() > MaxWidth)
10153     value = value.trunc(MaxWidth);
10154 
10155   // isNonNegative() just checks the sign bit without considering
10156   // signedness.
10157   return IntRange(value.getActiveBits(), true);
10158 }
10159 
10160 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10161                               unsigned MaxWidth) {
10162   if (result.isInt())
10163     return GetValueRange(C, result.getInt(), MaxWidth);
10164 
10165   if (result.isVector()) {
10166     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10167     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10168       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10169       R = IntRange::join(R, El);
10170     }
10171     return R;
10172   }
10173 
10174   if (result.isComplexInt()) {
10175     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10176     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10177     return IntRange::join(R, I);
10178   }
10179 
10180   // This can happen with lossless casts to intptr_t of "based" lvalues.
10181   // Assume it might use arbitrary bits.
10182   // FIXME: The only reason we need to pass the type in here is to get
10183   // the sign right on this one case.  It would be nice if APValue
10184   // preserved this.
10185   assert(result.isLValue() || result.isAddrLabelDiff());
10186   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10187 }
10188 
10189 static QualType GetExprType(const Expr *E) {
10190   QualType Ty = E->getType();
10191   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10192     Ty = AtomicRHS->getValueType();
10193   return Ty;
10194 }
10195 
10196 /// Pseudo-evaluate the given integer expression, estimating the
10197 /// range of values it might take.
10198 ///
10199 /// \param MaxWidth - the width to which the value will be truncated
10200 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10201                              bool InConstantContext) {
10202   E = E->IgnoreParens();
10203 
10204   // Try a full evaluation first.
10205   Expr::EvalResult result;
10206   if (E->EvaluateAsRValue(result, C, InConstantContext))
10207     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10208 
10209   // I think we only want to look through implicit casts here; if the
10210   // user has an explicit widening cast, we should treat the value as
10211   // being of the new, wider type.
10212   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10213     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10214       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10215 
10216     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10217 
10218     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10219                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10220 
10221     // Assume that non-integer casts can span the full range of the type.
10222     if (!isIntegerCast)
10223       return OutputTypeRange;
10224 
10225     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10226                                      std::min(MaxWidth, OutputTypeRange.Width),
10227                                      InConstantContext);
10228 
10229     // Bail out if the subexpr's range is as wide as the cast type.
10230     if (SubRange.Width >= OutputTypeRange.Width)
10231       return OutputTypeRange;
10232 
10233     // Otherwise, we take the smaller width, and we're non-negative if
10234     // either the output type or the subexpr is.
10235     return IntRange(SubRange.Width,
10236                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10237   }
10238 
10239   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10240     // If we can fold the condition, just take that operand.
10241     bool CondResult;
10242     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10243       return GetExprRange(C,
10244                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10245                           MaxWidth, InConstantContext);
10246 
10247     // Otherwise, conservatively merge.
10248     IntRange L =
10249         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10250     IntRange R =
10251         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10252     return IntRange::join(L, R);
10253   }
10254 
10255   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10256     switch (BO->getOpcode()) {
10257     case BO_Cmp:
10258       llvm_unreachable("builtin <=> should have class type");
10259 
10260     // Boolean-valued operations are single-bit and positive.
10261     case BO_LAnd:
10262     case BO_LOr:
10263     case BO_LT:
10264     case BO_GT:
10265     case BO_LE:
10266     case BO_GE:
10267     case BO_EQ:
10268     case BO_NE:
10269       return IntRange::forBoolType();
10270 
10271     // The type of the assignments is the type of the LHS, so the RHS
10272     // is not necessarily the same type.
10273     case BO_MulAssign:
10274     case BO_DivAssign:
10275     case BO_RemAssign:
10276     case BO_AddAssign:
10277     case BO_SubAssign:
10278     case BO_XorAssign:
10279     case BO_OrAssign:
10280       // TODO: bitfields?
10281       return IntRange::forValueOfType(C, GetExprType(E));
10282 
10283     // Simple assignments just pass through the RHS, which will have
10284     // been coerced to the LHS type.
10285     case BO_Assign:
10286       // TODO: bitfields?
10287       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10288 
10289     // Operations with opaque sources are black-listed.
10290     case BO_PtrMemD:
10291     case BO_PtrMemI:
10292       return IntRange::forValueOfType(C, GetExprType(E));
10293 
10294     // Bitwise-and uses the *infinum* of the two source ranges.
10295     case BO_And:
10296     case BO_AndAssign:
10297       return IntRange::meet(
10298           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10299           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10300 
10301     // Left shift gets black-listed based on a judgement call.
10302     case BO_Shl:
10303       // ...except that we want to treat '1 << (blah)' as logically
10304       // positive.  It's an important idiom.
10305       if (IntegerLiteral *I
10306             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10307         if (I->getValue() == 1) {
10308           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10309           return IntRange(R.Width, /*NonNegative*/ true);
10310         }
10311       }
10312       LLVM_FALLTHROUGH;
10313 
10314     case BO_ShlAssign:
10315       return IntRange::forValueOfType(C, GetExprType(E));
10316 
10317     // Right shift by a constant can narrow its left argument.
10318     case BO_Shr:
10319     case BO_ShrAssign: {
10320       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10321 
10322       // If the shift amount is a positive constant, drop the width by
10323       // that much.
10324       llvm::APSInt shift;
10325       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10326           shift.isNonNegative()) {
10327         unsigned zext = shift.getZExtValue();
10328         if (zext >= L.Width)
10329           L.Width = (L.NonNegative ? 0 : 1);
10330         else
10331           L.Width -= zext;
10332       }
10333 
10334       return L;
10335     }
10336 
10337     // Comma acts as its right operand.
10338     case BO_Comma:
10339       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10340 
10341     // Black-list pointer subtractions.
10342     case BO_Sub:
10343       if (BO->getLHS()->getType()->isPointerType())
10344         return IntRange::forValueOfType(C, GetExprType(E));
10345       break;
10346 
10347     // The width of a division result is mostly determined by the size
10348     // of the LHS.
10349     case BO_Div: {
10350       // Don't 'pre-truncate' the operands.
10351       unsigned opWidth = C.getIntWidth(GetExprType(E));
10352       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10353 
10354       // If the divisor is constant, use that.
10355       llvm::APSInt divisor;
10356       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10357         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10358         if (log2 >= L.Width)
10359           L.Width = (L.NonNegative ? 0 : 1);
10360         else
10361           L.Width = std::min(L.Width - log2, MaxWidth);
10362         return L;
10363       }
10364 
10365       // Otherwise, just use the LHS's width.
10366       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10367       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10368     }
10369 
10370     // The result of a remainder can't be larger than the result of
10371     // either side.
10372     case BO_Rem: {
10373       // Don't 'pre-truncate' the operands.
10374       unsigned opWidth = C.getIntWidth(GetExprType(E));
10375       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10376       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10377 
10378       IntRange meet = IntRange::meet(L, R);
10379       meet.Width = std::min(meet.Width, MaxWidth);
10380       return meet;
10381     }
10382 
10383     // The default behavior is okay for these.
10384     case BO_Mul:
10385     case BO_Add:
10386     case BO_Xor:
10387     case BO_Or:
10388       break;
10389     }
10390 
10391     // The default case is to treat the operation as if it were closed
10392     // on the narrowest type that encompasses both operands.
10393     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10394     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10395     return IntRange::join(L, R);
10396   }
10397 
10398   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10399     switch (UO->getOpcode()) {
10400     // Boolean-valued operations are white-listed.
10401     case UO_LNot:
10402       return IntRange::forBoolType();
10403 
10404     // Operations with opaque sources are black-listed.
10405     case UO_Deref:
10406     case UO_AddrOf: // should be impossible
10407       return IntRange::forValueOfType(C, GetExprType(E));
10408 
10409     default:
10410       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10411     }
10412   }
10413 
10414   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10415     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10416 
10417   if (const auto *BitField = E->getSourceBitField())
10418     return IntRange(BitField->getBitWidthValue(C),
10419                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10420 
10421   return IntRange::forValueOfType(C, GetExprType(E));
10422 }
10423 
10424 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10425                              bool InConstantContext) {
10426   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10427 }
10428 
10429 /// Checks whether the given value, which currently has the given
10430 /// source semantics, has the same value when coerced through the
10431 /// target semantics.
10432 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10433                                  const llvm::fltSemantics &Src,
10434                                  const llvm::fltSemantics &Tgt) {
10435   llvm::APFloat truncated = value;
10436 
10437   bool ignored;
10438   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10439   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10440 
10441   return truncated.bitwiseIsEqual(value);
10442 }
10443 
10444 /// Checks whether the given value, which currently has the given
10445 /// source semantics, has the same value when coerced through the
10446 /// target semantics.
10447 ///
10448 /// The value might be a vector of floats (or a complex number).
10449 static bool IsSameFloatAfterCast(const APValue &value,
10450                                  const llvm::fltSemantics &Src,
10451                                  const llvm::fltSemantics &Tgt) {
10452   if (value.isFloat())
10453     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10454 
10455   if (value.isVector()) {
10456     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10457       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10458         return false;
10459     return true;
10460   }
10461 
10462   assert(value.isComplexFloat());
10463   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10464           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10465 }
10466 
10467 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10468                                        bool IsListInit = false);
10469 
10470 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10471   // Suppress cases where we are comparing against an enum constant.
10472   if (const DeclRefExpr *DR =
10473       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10474     if (isa<EnumConstantDecl>(DR->getDecl()))
10475       return true;
10476 
10477   // Suppress cases where the value is expanded from a macro, unless that macro
10478   // is how a language represents a boolean literal. This is the case in both C
10479   // and Objective-C.
10480   SourceLocation BeginLoc = E->getBeginLoc();
10481   if (BeginLoc.isMacroID()) {
10482     StringRef MacroName = Lexer::getImmediateMacroName(
10483         BeginLoc, S.getSourceManager(), S.getLangOpts());
10484     return MacroName != "YES" && MacroName != "NO" &&
10485            MacroName != "true" && MacroName != "false";
10486   }
10487 
10488   return false;
10489 }
10490 
10491 static bool isKnownToHaveUnsignedValue(Expr *E) {
10492   return E->getType()->isIntegerType() &&
10493          (!E->getType()->isSignedIntegerType() ||
10494           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10495 }
10496 
10497 namespace {
10498 /// The promoted range of values of a type. In general this has the
10499 /// following structure:
10500 ///
10501 ///     |-----------| . . . |-----------|
10502 ///     ^           ^       ^           ^
10503 ///    Min       HoleMin  HoleMax      Max
10504 ///
10505 /// ... where there is only a hole if a signed type is promoted to unsigned
10506 /// (in which case Min and Max are the smallest and largest representable
10507 /// values).
10508 struct PromotedRange {
10509   // Min, or HoleMax if there is a hole.
10510   llvm::APSInt PromotedMin;
10511   // Max, or HoleMin if there is a hole.
10512   llvm::APSInt PromotedMax;
10513 
10514   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10515     if (R.Width == 0)
10516       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10517     else if (R.Width >= BitWidth && !Unsigned) {
10518       // Promotion made the type *narrower*. This happens when promoting
10519       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10520       // Treat all values of 'signed int' as being in range for now.
10521       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10522       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10523     } else {
10524       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10525                         .extOrTrunc(BitWidth);
10526       PromotedMin.setIsUnsigned(Unsigned);
10527 
10528       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10529                         .extOrTrunc(BitWidth);
10530       PromotedMax.setIsUnsigned(Unsigned);
10531     }
10532   }
10533 
10534   // Determine whether this range is contiguous (has no hole).
10535   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10536 
10537   // Where a constant value is within the range.
10538   enum ComparisonResult {
10539     LT = 0x1,
10540     LE = 0x2,
10541     GT = 0x4,
10542     GE = 0x8,
10543     EQ = 0x10,
10544     NE = 0x20,
10545     InRangeFlag = 0x40,
10546 
10547     Less = LE | LT | NE,
10548     Min = LE | InRangeFlag,
10549     InRange = InRangeFlag,
10550     Max = GE | InRangeFlag,
10551     Greater = GE | GT | NE,
10552 
10553     OnlyValue = LE | GE | EQ | InRangeFlag,
10554     InHole = NE
10555   };
10556 
10557   ComparisonResult compare(const llvm::APSInt &Value) const {
10558     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10559            Value.isUnsigned() == PromotedMin.isUnsigned());
10560     if (!isContiguous()) {
10561       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10562       if (Value.isMinValue()) return Min;
10563       if (Value.isMaxValue()) return Max;
10564       if (Value >= PromotedMin) return InRange;
10565       if (Value <= PromotedMax) return InRange;
10566       return InHole;
10567     }
10568 
10569     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10570     case -1: return Less;
10571     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10572     case 1:
10573       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10574       case -1: return InRange;
10575       case 0: return Max;
10576       case 1: return Greater;
10577       }
10578     }
10579 
10580     llvm_unreachable("impossible compare result");
10581   }
10582 
10583   static llvm::Optional<StringRef>
10584   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10585     if (Op == BO_Cmp) {
10586       ComparisonResult LTFlag = LT, GTFlag = GT;
10587       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10588 
10589       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10590       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10591       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10592       return llvm::None;
10593     }
10594 
10595     ComparisonResult TrueFlag, FalseFlag;
10596     if (Op == BO_EQ) {
10597       TrueFlag = EQ;
10598       FalseFlag = NE;
10599     } else if (Op == BO_NE) {
10600       TrueFlag = NE;
10601       FalseFlag = EQ;
10602     } else {
10603       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10604         TrueFlag = LT;
10605         FalseFlag = GE;
10606       } else {
10607         TrueFlag = GT;
10608         FalseFlag = LE;
10609       }
10610       if (Op == BO_GE || Op == BO_LE)
10611         std::swap(TrueFlag, FalseFlag);
10612     }
10613     if (R & TrueFlag)
10614       return StringRef("true");
10615     if (R & FalseFlag)
10616       return StringRef("false");
10617     return llvm::None;
10618   }
10619 };
10620 }
10621 
10622 static bool HasEnumType(Expr *E) {
10623   // Strip off implicit integral promotions.
10624   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10625     if (ICE->getCastKind() != CK_IntegralCast &&
10626         ICE->getCastKind() != CK_NoOp)
10627       break;
10628     E = ICE->getSubExpr();
10629   }
10630 
10631   return E->getType()->isEnumeralType();
10632 }
10633 
10634 static int classifyConstantValue(Expr *Constant) {
10635   // The values of this enumeration are used in the diagnostics
10636   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10637   enum ConstantValueKind {
10638     Miscellaneous = 0,
10639     LiteralTrue,
10640     LiteralFalse
10641   };
10642   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10643     return BL->getValue() ? ConstantValueKind::LiteralTrue
10644                           : ConstantValueKind::LiteralFalse;
10645   return ConstantValueKind::Miscellaneous;
10646 }
10647 
10648 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10649                                         Expr *Constant, Expr *Other,
10650                                         const llvm::APSInt &Value,
10651                                         bool RhsConstant) {
10652   if (S.inTemplateInstantiation())
10653     return false;
10654 
10655   Expr *OriginalOther = Other;
10656 
10657   Constant = Constant->IgnoreParenImpCasts();
10658   Other = Other->IgnoreParenImpCasts();
10659 
10660   // Suppress warnings on tautological comparisons between values of the same
10661   // enumeration type. There are only two ways we could warn on this:
10662   //  - If the constant is outside the range of representable values of
10663   //    the enumeration. In such a case, we should warn about the cast
10664   //    to enumeration type, not about the comparison.
10665   //  - If the constant is the maximum / minimum in-range value. For an
10666   //    enumeratin type, such comparisons can be meaningful and useful.
10667   if (Constant->getType()->isEnumeralType() &&
10668       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10669     return false;
10670 
10671   // TODO: Investigate using GetExprRange() to get tighter bounds
10672   // on the bit ranges.
10673   QualType OtherT = Other->getType();
10674   if (const auto *AT = OtherT->getAs<AtomicType>())
10675     OtherT = AT->getValueType();
10676   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10677 
10678   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10679   // (Namely, macOS).
10680   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10681                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10682                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10683 
10684   // Whether we're treating Other as being a bool because of the form of
10685   // expression despite it having another type (typically 'int' in C).
10686   bool OtherIsBooleanDespiteType =
10687       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10688   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10689     OtherRange = IntRange::forBoolType();
10690 
10691   // Determine the promoted range of the other type and see if a comparison of
10692   // the constant against that range is tautological.
10693   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10694                                    Value.isUnsigned());
10695   auto Cmp = OtherPromotedRange.compare(Value);
10696   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10697   if (!Result)
10698     return false;
10699 
10700   // Suppress the diagnostic for an in-range comparison if the constant comes
10701   // from a macro or enumerator. We don't want to diagnose
10702   //
10703   //   some_long_value <= INT_MAX
10704   //
10705   // when sizeof(int) == sizeof(long).
10706   bool InRange = Cmp & PromotedRange::InRangeFlag;
10707   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10708     return false;
10709 
10710   // If this is a comparison to an enum constant, include that
10711   // constant in the diagnostic.
10712   const EnumConstantDecl *ED = nullptr;
10713   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10714     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10715 
10716   // Should be enough for uint128 (39 decimal digits)
10717   SmallString<64> PrettySourceValue;
10718   llvm::raw_svector_ostream OS(PrettySourceValue);
10719   if (ED) {
10720     OS << '\'' << *ED << "' (" << Value << ")";
10721   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10722                Constant->IgnoreParenImpCasts())) {
10723     OS << (BL->getValue() ? "YES" : "NO");
10724   } else {
10725     OS << Value;
10726   }
10727 
10728   if (IsObjCSignedCharBool) {
10729     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10730                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10731                               << OS.str() << *Result);
10732     return true;
10733   }
10734 
10735   // FIXME: We use a somewhat different formatting for the in-range cases and
10736   // cases involving boolean values for historical reasons. We should pick a
10737   // consistent way of presenting these diagnostics.
10738   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10739 
10740     S.DiagRuntimeBehavior(
10741         E->getOperatorLoc(), E,
10742         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10743                          : diag::warn_tautological_bool_compare)
10744             << OS.str() << classifyConstantValue(Constant) << OtherT
10745             << OtherIsBooleanDespiteType << *Result
10746             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10747   } else {
10748     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10749                         ? (HasEnumType(OriginalOther)
10750                                ? diag::warn_unsigned_enum_always_true_comparison
10751                                : diag::warn_unsigned_always_true_comparison)
10752                         : diag::warn_tautological_constant_compare;
10753 
10754     S.Diag(E->getOperatorLoc(), Diag)
10755         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10756         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10757   }
10758 
10759   return true;
10760 }
10761 
10762 /// Analyze the operands of the given comparison.  Implements the
10763 /// fallback case from AnalyzeComparison.
10764 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10765   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10766   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10767 }
10768 
10769 /// Implements -Wsign-compare.
10770 ///
10771 /// \param E the binary operator to check for warnings
10772 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10773   // The type the comparison is being performed in.
10774   QualType T = E->getLHS()->getType();
10775 
10776   // Only analyze comparison operators where both sides have been converted to
10777   // the same type.
10778   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10779     return AnalyzeImpConvsInComparison(S, E);
10780 
10781   // Don't analyze value-dependent comparisons directly.
10782   if (E->isValueDependent())
10783     return AnalyzeImpConvsInComparison(S, E);
10784 
10785   Expr *LHS = E->getLHS();
10786   Expr *RHS = E->getRHS();
10787 
10788   if (T->isIntegralType(S.Context)) {
10789     llvm::APSInt RHSValue;
10790     llvm::APSInt LHSValue;
10791 
10792     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10793     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10794 
10795     // We don't care about expressions whose result is a constant.
10796     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10797       return AnalyzeImpConvsInComparison(S, E);
10798 
10799     // We only care about expressions where just one side is literal
10800     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10801       // Is the constant on the RHS or LHS?
10802       const bool RhsConstant = IsRHSIntegralLiteral;
10803       Expr *Const = RhsConstant ? RHS : LHS;
10804       Expr *Other = RhsConstant ? LHS : RHS;
10805       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10806 
10807       // Check whether an integer constant comparison results in a value
10808       // of 'true' or 'false'.
10809       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10810         return AnalyzeImpConvsInComparison(S, E);
10811     }
10812   }
10813 
10814   if (!T->hasUnsignedIntegerRepresentation()) {
10815     // We don't do anything special if this isn't an unsigned integral
10816     // comparison:  we're only interested in integral comparisons, and
10817     // signed comparisons only happen in cases we don't care to warn about.
10818     return AnalyzeImpConvsInComparison(S, E);
10819   }
10820 
10821   LHS = LHS->IgnoreParenImpCasts();
10822   RHS = RHS->IgnoreParenImpCasts();
10823 
10824   if (!S.getLangOpts().CPlusPlus) {
10825     // Avoid warning about comparison of integers with different signs when
10826     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10827     // the type of `E`.
10828     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10829       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10830     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10831       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10832   }
10833 
10834   // Check to see if one of the (unmodified) operands is of different
10835   // signedness.
10836   Expr *signedOperand, *unsignedOperand;
10837   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10838     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10839            "unsigned comparison between two signed integer expressions?");
10840     signedOperand = LHS;
10841     unsignedOperand = RHS;
10842   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10843     signedOperand = RHS;
10844     unsignedOperand = LHS;
10845   } else {
10846     return AnalyzeImpConvsInComparison(S, E);
10847   }
10848 
10849   // Otherwise, calculate the effective range of the signed operand.
10850   IntRange signedRange =
10851       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10852 
10853   // Go ahead and analyze implicit conversions in the operands.  Note
10854   // that we skip the implicit conversions on both sides.
10855   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10856   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10857 
10858   // If the signed range is non-negative, -Wsign-compare won't fire.
10859   if (signedRange.NonNegative)
10860     return;
10861 
10862   // For (in)equality comparisons, if the unsigned operand is a
10863   // constant which cannot collide with a overflowed signed operand,
10864   // then reinterpreting the signed operand as unsigned will not
10865   // change the result of the comparison.
10866   if (E->isEqualityOp()) {
10867     unsigned comparisonWidth = S.Context.getIntWidth(T);
10868     IntRange unsignedRange =
10869         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10870 
10871     // We should never be unable to prove that the unsigned operand is
10872     // non-negative.
10873     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10874 
10875     if (unsignedRange.Width < comparisonWidth)
10876       return;
10877   }
10878 
10879   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10880                         S.PDiag(diag::warn_mixed_sign_comparison)
10881                             << LHS->getType() << RHS->getType()
10882                             << LHS->getSourceRange() << RHS->getSourceRange());
10883 }
10884 
10885 /// Analyzes an attempt to assign the given value to a bitfield.
10886 ///
10887 /// Returns true if there was something fishy about the attempt.
10888 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10889                                       SourceLocation InitLoc) {
10890   assert(Bitfield->isBitField());
10891   if (Bitfield->isInvalidDecl())
10892     return false;
10893 
10894   // White-list bool bitfields.
10895   QualType BitfieldType = Bitfield->getType();
10896   if (BitfieldType->isBooleanType())
10897      return false;
10898 
10899   if (BitfieldType->isEnumeralType()) {
10900     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10901     // If the underlying enum type was not explicitly specified as an unsigned
10902     // type and the enum contain only positive values, MSVC++ will cause an
10903     // inconsistency by storing this as a signed type.
10904     if (S.getLangOpts().CPlusPlus11 &&
10905         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10906         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10907         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10908       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10909         << BitfieldEnumDecl->getNameAsString();
10910     }
10911   }
10912 
10913   if (Bitfield->getType()->isBooleanType())
10914     return false;
10915 
10916   // Ignore value- or type-dependent expressions.
10917   if (Bitfield->getBitWidth()->isValueDependent() ||
10918       Bitfield->getBitWidth()->isTypeDependent() ||
10919       Init->isValueDependent() ||
10920       Init->isTypeDependent())
10921     return false;
10922 
10923   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10924   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10925 
10926   Expr::EvalResult Result;
10927   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10928                                    Expr::SE_AllowSideEffects)) {
10929     // The RHS is not constant.  If the RHS has an enum type, make sure the
10930     // bitfield is wide enough to hold all the values of the enum without
10931     // truncation.
10932     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10933       EnumDecl *ED = EnumTy->getDecl();
10934       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10935 
10936       // Enum types are implicitly signed on Windows, so check if there are any
10937       // negative enumerators to see if the enum was intended to be signed or
10938       // not.
10939       bool SignedEnum = ED->getNumNegativeBits() > 0;
10940 
10941       // Check for surprising sign changes when assigning enum values to a
10942       // bitfield of different signedness.  If the bitfield is signed and we
10943       // have exactly the right number of bits to store this unsigned enum,
10944       // suggest changing the enum to an unsigned type. This typically happens
10945       // on Windows where unfixed enums always use an underlying type of 'int'.
10946       unsigned DiagID = 0;
10947       if (SignedEnum && !SignedBitfield) {
10948         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10949       } else if (SignedBitfield && !SignedEnum &&
10950                  ED->getNumPositiveBits() == FieldWidth) {
10951         DiagID = diag::warn_signed_bitfield_enum_conversion;
10952       }
10953 
10954       if (DiagID) {
10955         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10956         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10957         SourceRange TypeRange =
10958             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10959         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10960             << SignedEnum << TypeRange;
10961       }
10962 
10963       // Compute the required bitwidth. If the enum has negative values, we need
10964       // one more bit than the normal number of positive bits to represent the
10965       // sign bit.
10966       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10967                                                   ED->getNumNegativeBits())
10968                                        : ED->getNumPositiveBits();
10969 
10970       // Check the bitwidth.
10971       if (BitsNeeded > FieldWidth) {
10972         Expr *WidthExpr = Bitfield->getBitWidth();
10973         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10974             << Bitfield << ED;
10975         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10976             << BitsNeeded << ED << WidthExpr->getSourceRange();
10977       }
10978     }
10979 
10980     return false;
10981   }
10982 
10983   llvm::APSInt Value = Result.Val.getInt();
10984 
10985   unsigned OriginalWidth = Value.getBitWidth();
10986 
10987   if (!Value.isSigned() || Value.isNegative())
10988     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10989       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10990         OriginalWidth = Value.getMinSignedBits();
10991 
10992   if (OriginalWidth <= FieldWidth)
10993     return false;
10994 
10995   // Compute the value which the bitfield will contain.
10996   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10997   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10998 
10999   // Check whether the stored value is equal to the original value.
11000   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11001   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11002     return false;
11003 
11004   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11005   // therefore don't strictly fit into a signed bitfield of width 1.
11006   if (FieldWidth == 1 && Value == 1)
11007     return false;
11008 
11009   std::string PrettyValue = Value.toString(10);
11010   std::string PrettyTrunc = TruncatedValue.toString(10);
11011 
11012   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11013     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11014     << Init->getSourceRange();
11015 
11016   return true;
11017 }
11018 
11019 /// Analyze the given simple or compound assignment for warning-worthy
11020 /// operations.
11021 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11022   // Just recurse on the LHS.
11023   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11024 
11025   // We want to recurse on the RHS as normal unless we're assigning to
11026   // a bitfield.
11027   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11028     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11029                                   E->getOperatorLoc())) {
11030       // Recurse, ignoring any implicit conversions on the RHS.
11031       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11032                                         E->getOperatorLoc());
11033     }
11034   }
11035 
11036   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11037 
11038   // Diagnose implicitly sequentially-consistent atomic assignment.
11039   if (E->getLHS()->getType()->isAtomicType())
11040     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11041 }
11042 
11043 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11044 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11045                             SourceLocation CContext, unsigned diag,
11046                             bool pruneControlFlow = false) {
11047   if (pruneControlFlow) {
11048     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11049                           S.PDiag(diag)
11050                               << SourceType << T << E->getSourceRange()
11051                               << SourceRange(CContext));
11052     return;
11053   }
11054   S.Diag(E->getExprLoc(), diag)
11055     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11056 }
11057 
11058 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11059 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11060                             SourceLocation CContext,
11061                             unsigned diag, bool pruneControlFlow = false) {
11062   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11063 }
11064 
11065 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11066   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11067       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11068 }
11069 
11070 static void adornObjCBoolConversionDiagWithTernaryFixit(
11071     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11072   Expr *Ignored = SourceExpr->IgnoreImplicit();
11073   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11074     Ignored = OVE->getSourceExpr();
11075   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11076                      isa<BinaryOperator>(Ignored) ||
11077                      isa<CXXOperatorCallExpr>(Ignored);
11078   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11079   if (NeedsParens)
11080     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11081             << FixItHint::CreateInsertion(EndLoc, ")");
11082   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11083 }
11084 
11085 /// Diagnose an implicit cast from a floating point value to an integer value.
11086 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11087                                     SourceLocation CContext) {
11088   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11089   const bool PruneWarnings = S.inTemplateInstantiation();
11090 
11091   Expr *InnerE = E->IgnoreParenImpCasts();
11092   // We also want to warn on, e.g., "int i = -1.234"
11093   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11094     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11095       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11096 
11097   const bool IsLiteral =
11098       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11099 
11100   llvm::APFloat Value(0.0);
11101   bool IsConstant =
11102     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11103   if (!IsConstant) {
11104     if (isObjCSignedCharBool(S, T)) {
11105       return adornObjCBoolConversionDiagWithTernaryFixit(
11106           S, E,
11107           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11108               << E->getType());
11109     }
11110 
11111     return DiagnoseImpCast(S, E, T, CContext,
11112                            diag::warn_impcast_float_integer, PruneWarnings);
11113   }
11114 
11115   bool isExact = false;
11116 
11117   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11118                             T->hasUnsignedIntegerRepresentation());
11119   llvm::APFloat::opStatus Result = Value.convertToInteger(
11120       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11121 
11122   // FIXME: Force the precision of the source value down so we don't print
11123   // digits which are usually useless (we don't really care here if we
11124   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11125   // would automatically print the shortest representation, but it's a bit
11126   // tricky to implement.
11127   SmallString<16> PrettySourceValue;
11128   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11129   precision = (precision * 59 + 195) / 196;
11130   Value.toString(PrettySourceValue, precision);
11131 
11132   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11133     return adornObjCBoolConversionDiagWithTernaryFixit(
11134         S, E,
11135         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11136             << PrettySourceValue);
11137   }
11138 
11139   if (Result == llvm::APFloat::opOK && isExact) {
11140     if (IsLiteral) return;
11141     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11142                            PruneWarnings);
11143   }
11144 
11145   // Conversion of a floating-point value to a non-bool integer where the
11146   // integral part cannot be represented by the integer type is undefined.
11147   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11148     return DiagnoseImpCast(
11149         S, E, T, CContext,
11150         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11151                   : diag::warn_impcast_float_to_integer_out_of_range,
11152         PruneWarnings);
11153 
11154   unsigned DiagID = 0;
11155   if (IsLiteral) {
11156     // Warn on floating point literal to integer.
11157     DiagID = diag::warn_impcast_literal_float_to_integer;
11158   } else if (IntegerValue == 0) {
11159     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11160       return DiagnoseImpCast(S, E, T, CContext,
11161                              diag::warn_impcast_float_integer, PruneWarnings);
11162     }
11163     // Warn on non-zero to zero conversion.
11164     DiagID = diag::warn_impcast_float_to_integer_zero;
11165   } else {
11166     if (IntegerValue.isUnsigned()) {
11167       if (!IntegerValue.isMaxValue()) {
11168         return DiagnoseImpCast(S, E, T, CContext,
11169                                diag::warn_impcast_float_integer, PruneWarnings);
11170       }
11171     } else {  // IntegerValue.isSigned()
11172       if (!IntegerValue.isMaxSignedValue() &&
11173           !IntegerValue.isMinSignedValue()) {
11174         return DiagnoseImpCast(S, E, T, CContext,
11175                                diag::warn_impcast_float_integer, PruneWarnings);
11176       }
11177     }
11178     // Warn on evaluatable floating point expression to integer conversion.
11179     DiagID = diag::warn_impcast_float_to_integer;
11180   }
11181 
11182   SmallString<16> PrettyTargetValue;
11183   if (IsBool)
11184     PrettyTargetValue = Value.isZero() ? "false" : "true";
11185   else
11186     IntegerValue.toString(PrettyTargetValue);
11187 
11188   if (PruneWarnings) {
11189     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11190                           S.PDiag(DiagID)
11191                               << E->getType() << T.getUnqualifiedType()
11192                               << PrettySourceValue << PrettyTargetValue
11193                               << E->getSourceRange() << SourceRange(CContext));
11194   } else {
11195     S.Diag(E->getExprLoc(), DiagID)
11196         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11197         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11198   }
11199 }
11200 
11201 /// Analyze the given compound assignment for the possible losing of
11202 /// floating-point precision.
11203 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11204   assert(isa<CompoundAssignOperator>(E) &&
11205          "Must be compound assignment operation");
11206   // Recurse on the LHS and RHS in here
11207   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11208   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11209 
11210   if (E->getLHS()->getType()->isAtomicType())
11211     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11212 
11213   // Now check the outermost expression
11214   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11215   const auto *RBT = cast<CompoundAssignOperator>(E)
11216                         ->getComputationResultType()
11217                         ->getAs<BuiltinType>();
11218 
11219   // The below checks assume source is floating point.
11220   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11221 
11222   // If source is floating point but target is an integer.
11223   if (ResultBT->isInteger())
11224     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11225                            E->getExprLoc(), diag::warn_impcast_float_integer);
11226 
11227   if (!ResultBT->isFloatingPoint())
11228     return;
11229 
11230   // If both source and target are floating points, warn about losing precision.
11231   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11232       QualType(ResultBT, 0), QualType(RBT, 0));
11233   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11234     // warn about dropping FP rank.
11235     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11236                     diag::warn_impcast_float_result_precision);
11237 }
11238 
11239 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11240                                       IntRange Range) {
11241   if (!Range.Width) return "0";
11242 
11243   llvm::APSInt ValueInRange = Value;
11244   ValueInRange.setIsSigned(!Range.NonNegative);
11245   ValueInRange = ValueInRange.trunc(Range.Width);
11246   return ValueInRange.toString(10);
11247 }
11248 
11249 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11250   if (!isa<ImplicitCastExpr>(Ex))
11251     return false;
11252 
11253   Expr *InnerE = Ex->IgnoreParenImpCasts();
11254   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11255   const Type *Source =
11256     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11257   if (Target->isDependentType())
11258     return false;
11259 
11260   const BuiltinType *FloatCandidateBT =
11261     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11262   const Type *BoolCandidateType = ToBool ? Target : Source;
11263 
11264   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11265           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11266 }
11267 
11268 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11269                                              SourceLocation CC) {
11270   unsigned NumArgs = TheCall->getNumArgs();
11271   for (unsigned i = 0; i < NumArgs; ++i) {
11272     Expr *CurrA = TheCall->getArg(i);
11273     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11274       continue;
11275 
11276     bool IsSwapped = ((i > 0) &&
11277         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11278     IsSwapped |= ((i < (NumArgs - 1)) &&
11279         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11280     if (IsSwapped) {
11281       // Warn on this floating-point to bool conversion.
11282       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11283                       CurrA->getType(), CC,
11284                       diag::warn_impcast_floating_point_to_bool);
11285     }
11286   }
11287 }
11288 
11289 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11290                                    SourceLocation CC) {
11291   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11292                         E->getExprLoc()))
11293     return;
11294 
11295   // Don't warn on functions which have return type nullptr_t.
11296   if (isa<CallExpr>(E))
11297     return;
11298 
11299   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11300   const Expr::NullPointerConstantKind NullKind =
11301       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11302   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11303     return;
11304 
11305   // Return if target type is a safe conversion.
11306   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11307       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11308     return;
11309 
11310   SourceLocation Loc = E->getSourceRange().getBegin();
11311 
11312   // Venture through the macro stacks to get to the source of macro arguments.
11313   // The new location is a better location than the complete location that was
11314   // passed in.
11315   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11316   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11317 
11318   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11319   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11320     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11321         Loc, S.SourceMgr, S.getLangOpts());
11322     if (MacroName == "NULL")
11323       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11324   }
11325 
11326   // Only warn if the null and context location are in the same macro expansion.
11327   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11328     return;
11329 
11330   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11331       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11332       << FixItHint::CreateReplacement(Loc,
11333                                       S.getFixItZeroLiteralForType(T, Loc));
11334 }
11335 
11336 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11337                                   ObjCArrayLiteral *ArrayLiteral);
11338 
11339 static void
11340 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11341                            ObjCDictionaryLiteral *DictionaryLiteral);
11342 
11343 /// Check a single element within a collection literal against the
11344 /// target element type.
11345 static void checkObjCCollectionLiteralElement(Sema &S,
11346                                               QualType TargetElementType,
11347                                               Expr *Element,
11348                                               unsigned ElementKind) {
11349   // Skip a bitcast to 'id' or qualified 'id'.
11350   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11351     if (ICE->getCastKind() == CK_BitCast &&
11352         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11353       Element = ICE->getSubExpr();
11354   }
11355 
11356   QualType ElementType = Element->getType();
11357   ExprResult ElementResult(Element);
11358   if (ElementType->getAs<ObjCObjectPointerType>() &&
11359       S.CheckSingleAssignmentConstraints(TargetElementType,
11360                                          ElementResult,
11361                                          false, false)
11362         != Sema::Compatible) {
11363     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11364         << ElementType << ElementKind << TargetElementType
11365         << Element->getSourceRange();
11366   }
11367 
11368   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11369     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11370   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11371     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11372 }
11373 
11374 /// Check an Objective-C array literal being converted to the given
11375 /// target type.
11376 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11377                                   ObjCArrayLiteral *ArrayLiteral) {
11378   if (!S.NSArrayDecl)
11379     return;
11380 
11381   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11382   if (!TargetObjCPtr)
11383     return;
11384 
11385   if (TargetObjCPtr->isUnspecialized() ||
11386       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11387         != S.NSArrayDecl->getCanonicalDecl())
11388     return;
11389 
11390   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11391   if (TypeArgs.size() != 1)
11392     return;
11393 
11394   QualType TargetElementType = TypeArgs[0];
11395   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11396     checkObjCCollectionLiteralElement(S, TargetElementType,
11397                                       ArrayLiteral->getElement(I),
11398                                       0);
11399   }
11400 }
11401 
11402 /// Check an Objective-C dictionary literal being converted to the given
11403 /// target type.
11404 static void
11405 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11406                            ObjCDictionaryLiteral *DictionaryLiteral) {
11407   if (!S.NSDictionaryDecl)
11408     return;
11409 
11410   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11411   if (!TargetObjCPtr)
11412     return;
11413 
11414   if (TargetObjCPtr->isUnspecialized() ||
11415       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11416         != S.NSDictionaryDecl->getCanonicalDecl())
11417     return;
11418 
11419   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11420   if (TypeArgs.size() != 2)
11421     return;
11422 
11423   QualType TargetKeyType = TypeArgs[0];
11424   QualType TargetObjectType = TypeArgs[1];
11425   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11426     auto Element = DictionaryLiteral->getKeyValueElement(I);
11427     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11428     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11429   }
11430 }
11431 
11432 // Helper function to filter out cases for constant width constant conversion.
11433 // Don't warn on char array initialization or for non-decimal values.
11434 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11435                                           SourceLocation CC) {
11436   // If initializing from a constant, and the constant starts with '0',
11437   // then it is a binary, octal, or hexadecimal.  Allow these constants
11438   // to fill all the bits, even if there is a sign change.
11439   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11440     const char FirstLiteralCharacter =
11441         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11442     if (FirstLiteralCharacter == '0')
11443       return false;
11444   }
11445 
11446   // If the CC location points to a '{', and the type is char, then assume
11447   // assume it is an array initialization.
11448   if (CC.isValid() && T->isCharType()) {
11449     const char FirstContextCharacter =
11450         S.getSourceManager().getCharacterData(CC)[0];
11451     if (FirstContextCharacter == '{')
11452       return false;
11453   }
11454 
11455   return true;
11456 }
11457 
11458 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11459   const auto *IL = dyn_cast<IntegerLiteral>(E);
11460   if (!IL) {
11461     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11462       if (UO->getOpcode() == UO_Minus)
11463         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11464     }
11465   }
11466 
11467   return IL;
11468 }
11469 
11470 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11471   E = E->IgnoreParenImpCasts();
11472   SourceLocation ExprLoc = E->getExprLoc();
11473 
11474   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11475     BinaryOperator::Opcode Opc = BO->getOpcode();
11476     Expr::EvalResult Result;
11477     // Do not diagnose unsigned shifts.
11478     if (Opc == BO_Shl) {
11479       const auto *LHS = getIntegerLiteral(BO->getLHS());
11480       const auto *RHS = getIntegerLiteral(BO->getRHS());
11481       if (LHS && LHS->getValue() == 0)
11482         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11483       else if (!E->isValueDependent() && LHS && RHS &&
11484                RHS->getValue().isNonNegative() &&
11485                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11486         S.Diag(ExprLoc, diag::warn_left_shift_always)
11487             << (Result.Val.getInt() != 0);
11488       else if (E->getType()->isSignedIntegerType())
11489         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11490     }
11491   }
11492 
11493   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11494     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11495     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11496     if (!LHS || !RHS)
11497       return;
11498     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11499         (RHS->getValue() == 0 || RHS->getValue() == 1))
11500       // Do not diagnose common idioms.
11501       return;
11502     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11503       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11504   }
11505 }
11506 
11507 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11508                                     SourceLocation CC,
11509                                     bool *ICContext = nullptr,
11510                                     bool IsListInit = false) {
11511   if (E->isTypeDependent() || E->isValueDependent()) return;
11512 
11513   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11514   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11515   if (Source == Target) return;
11516   if (Target->isDependentType()) return;
11517 
11518   // If the conversion context location is invalid don't complain. We also
11519   // don't want to emit a warning if the issue occurs from the expansion of
11520   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11521   // delay this check as long as possible. Once we detect we are in that
11522   // scenario, we just return.
11523   if (CC.isInvalid())
11524     return;
11525 
11526   if (Source->isAtomicType())
11527     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11528 
11529   // Diagnose implicit casts to bool.
11530   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11531     if (isa<StringLiteral>(E))
11532       // Warn on string literal to bool.  Checks for string literals in logical
11533       // and expressions, for instance, assert(0 && "error here"), are
11534       // prevented by a check in AnalyzeImplicitConversions().
11535       return DiagnoseImpCast(S, E, T, CC,
11536                              diag::warn_impcast_string_literal_to_bool);
11537     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11538         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11539       // This covers the literal expressions that evaluate to Objective-C
11540       // objects.
11541       return DiagnoseImpCast(S, E, T, CC,
11542                              diag::warn_impcast_objective_c_literal_to_bool);
11543     }
11544     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11545       // Warn on pointer to bool conversion that is always true.
11546       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11547                                      SourceRange(CC));
11548     }
11549   }
11550 
11551   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11552   // is a typedef for signed char (macOS), then that constant value has to be 1
11553   // or 0.
11554   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11555     Expr::EvalResult Result;
11556     if (E->EvaluateAsInt(Result, S.getASTContext(),
11557                          Expr::SE_AllowSideEffects)) {
11558       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11559         adornObjCBoolConversionDiagWithTernaryFixit(
11560             S, E,
11561             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11562                 << Result.Val.getInt().toString(10));
11563       }
11564       return;
11565     }
11566   }
11567 
11568   // Check implicit casts from Objective-C collection literals to specialized
11569   // collection types, e.g., NSArray<NSString *> *.
11570   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11571     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11572   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11573     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11574 
11575   // Strip vector types.
11576   if (isa<VectorType>(Source)) {
11577     if (!isa<VectorType>(Target)) {
11578       if (S.SourceMgr.isInSystemMacro(CC))
11579         return;
11580       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11581     }
11582 
11583     // If the vector cast is cast between two vectors of the same size, it is
11584     // a bitcast, not a conversion.
11585     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11586       return;
11587 
11588     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11589     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11590   }
11591   if (auto VecTy = dyn_cast<VectorType>(Target))
11592     Target = VecTy->getElementType().getTypePtr();
11593 
11594   // Strip complex types.
11595   if (isa<ComplexType>(Source)) {
11596     if (!isa<ComplexType>(Target)) {
11597       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11598         return;
11599 
11600       return DiagnoseImpCast(S, E, T, CC,
11601                              S.getLangOpts().CPlusPlus
11602                                  ? diag::err_impcast_complex_scalar
11603                                  : diag::warn_impcast_complex_scalar);
11604     }
11605 
11606     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11607     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11608   }
11609 
11610   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11611   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11612 
11613   // If the source is floating point...
11614   if (SourceBT && SourceBT->isFloatingPoint()) {
11615     // ...and the target is floating point...
11616     if (TargetBT && TargetBT->isFloatingPoint()) {
11617       // ...then warn if we're dropping FP rank.
11618 
11619       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11620           QualType(SourceBT, 0), QualType(TargetBT, 0));
11621       if (Order > 0) {
11622         // Don't warn about float constants that are precisely
11623         // representable in the target type.
11624         Expr::EvalResult result;
11625         if (E->EvaluateAsRValue(result, S.Context)) {
11626           // Value might be a float, a float vector, or a float complex.
11627           if (IsSameFloatAfterCast(result.Val,
11628                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11629                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11630             return;
11631         }
11632 
11633         if (S.SourceMgr.isInSystemMacro(CC))
11634           return;
11635 
11636         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11637       }
11638       // ... or possibly if we're increasing rank, too
11639       else if (Order < 0) {
11640         if (S.SourceMgr.isInSystemMacro(CC))
11641           return;
11642 
11643         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11644       }
11645       return;
11646     }
11647 
11648     // If the target is integral, always warn.
11649     if (TargetBT && TargetBT->isInteger()) {
11650       if (S.SourceMgr.isInSystemMacro(CC))
11651         return;
11652 
11653       DiagnoseFloatingImpCast(S, E, T, CC);
11654     }
11655 
11656     // Detect the case where a call result is converted from floating-point to
11657     // to bool, and the final argument to the call is converted from bool, to
11658     // discover this typo:
11659     //
11660     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11661     //
11662     // FIXME: This is an incredibly special case; is there some more general
11663     // way to detect this class of misplaced-parentheses bug?
11664     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11665       // Check last argument of function call to see if it is an
11666       // implicit cast from a type matching the type the result
11667       // is being cast to.
11668       CallExpr *CEx = cast<CallExpr>(E);
11669       if (unsigned NumArgs = CEx->getNumArgs()) {
11670         Expr *LastA = CEx->getArg(NumArgs - 1);
11671         Expr *InnerE = LastA->IgnoreParenImpCasts();
11672         if (isa<ImplicitCastExpr>(LastA) &&
11673             InnerE->getType()->isBooleanType()) {
11674           // Warn on this floating-point to bool conversion
11675           DiagnoseImpCast(S, E, T, CC,
11676                           diag::warn_impcast_floating_point_to_bool);
11677         }
11678       }
11679     }
11680     return;
11681   }
11682 
11683   // Valid casts involving fixed point types should be accounted for here.
11684   if (Source->isFixedPointType()) {
11685     if (Target->isUnsaturatedFixedPointType()) {
11686       Expr::EvalResult Result;
11687       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11688                                   S.isConstantEvaluated())) {
11689         APFixedPoint Value = Result.Val.getFixedPoint();
11690         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11691         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11692         if (Value > MaxVal || Value < MinVal) {
11693           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11694                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11695                                     << Value.toString() << T
11696                                     << E->getSourceRange()
11697                                     << clang::SourceRange(CC));
11698           return;
11699         }
11700       }
11701     } else if (Target->isIntegerType()) {
11702       Expr::EvalResult Result;
11703       if (!S.isConstantEvaluated() &&
11704           E->EvaluateAsFixedPoint(Result, S.Context,
11705                                   Expr::SE_AllowSideEffects)) {
11706         APFixedPoint FXResult = Result.Val.getFixedPoint();
11707 
11708         bool Overflowed;
11709         llvm::APSInt IntResult = FXResult.convertToInt(
11710             S.Context.getIntWidth(T),
11711             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11712 
11713         if (Overflowed) {
11714           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11715                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11716                                     << FXResult.toString() << T
11717                                     << E->getSourceRange()
11718                                     << clang::SourceRange(CC));
11719           return;
11720         }
11721       }
11722     }
11723   } else if (Target->isUnsaturatedFixedPointType()) {
11724     if (Source->isIntegerType()) {
11725       Expr::EvalResult Result;
11726       if (!S.isConstantEvaluated() &&
11727           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11728         llvm::APSInt Value = Result.Val.getInt();
11729 
11730         bool Overflowed;
11731         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11732             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11733 
11734         if (Overflowed) {
11735           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11736                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11737                                     << Value.toString(/*Radix=*/10) << T
11738                                     << E->getSourceRange()
11739                                     << clang::SourceRange(CC));
11740           return;
11741         }
11742       }
11743     }
11744   }
11745 
11746   // If we are casting an integer type to a floating point type without
11747   // initialization-list syntax, we might lose accuracy if the floating
11748   // point type has a narrower significand than the integer type.
11749   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11750       TargetBT->isFloatingType() && !IsListInit) {
11751     // Determine the number of precision bits in the source integer type.
11752     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11753     unsigned int SourcePrecision = SourceRange.Width;
11754 
11755     // Determine the number of precision bits in the
11756     // target floating point type.
11757     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11758         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11759 
11760     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11761         SourcePrecision > TargetPrecision) {
11762 
11763       llvm::APSInt SourceInt;
11764       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11765         // If the source integer is a constant, convert it to the target
11766         // floating point type. Issue a warning if the value changes
11767         // during the whole conversion.
11768         llvm::APFloat TargetFloatValue(
11769             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11770         llvm::APFloat::opStatus ConversionStatus =
11771             TargetFloatValue.convertFromAPInt(
11772                 SourceInt, SourceBT->isSignedInteger(),
11773                 llvm::APFloat::rmNearestTiesToEven);
11774 
11775         if (ConversionStatus != llvm::APFloat::opOK) {
11776           std::string PrettySourceValue = SourceInt.toString(10);
11777           SmallString<32> PrettyTargetValue;
11778           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11779 
11780           S.DiagRuntimeBehavior(
11781               E->getExprLoc(), E,
11782               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11783                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11784                   << E->getSourceRange() << clang::SourceRange(CC));
11785         }
11786       } else {
11787         // Otherwise, the implicit conversion may lose precision.
11788         DiagnoseImpCast(S, E, T, CC,
11789                         diag::warn_impcast_integer_float_precision);
11790       }
11791     }
11792   }
11793 
11794   DiagnoseNullConversion(S, E, T, CC);
11795 
11796   S.DiscardMisalignedMemberAddress(Target, E);
11797 
11798   if (Target->isBooleanType())
11799     DiagnoseIntInBoolContext(S, E);
11800 
11801   if (!Source->isIntegerType() || !Target->isIntegerType())
11802     return;
11803 
11804   // TODO: remove this early return once the false positives for constant->bool
11805   // in templates, macros, etc, are reduced or removed.
11806   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11807     return;
11808 
11809   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11810       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11811     return adornObjCBoolConversionDiagWithTernaryFixit(
11812         S, E,
11813         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11814             << E->getType());
11815   }
11816 
11817   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11818   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11819 
11820   if (SourceRange.Width > TargetRange.Width) {
11821     // If the source is a constant, use a default-on diagnostic.
11822     // TODO: this should happen for bitfield stores, too.
11823     Expr::EvalResult Result;
11824     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11825                          S.isConstantEvaluated())) {
11826       llvm::APSInt Value(32);
11827       Value = Result.Val.getInt();
11828 
11829       if (S.SourceMgr.isInSystemMacro(CC))
11830         return;
11831 
11832       std::string PrettySourceValue = Value.toString(10);
11833       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11834 
11835       S.DiagRuntimeBehavior(
11836           E->getExprLoc(), E,
11837           S.PDiag(diag::warn_impcast_integer_precision_constant)
11838               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11839               << E->getSourceRange() << clang::SourceRange(CC));
11840       return;
11841     }
11842 
11843     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11844     if (S.SourceMgr.isInSystemMacro(CC))
11845       return;
11846 
11847     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11848       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11849                              /* pruneControlFlow */ true);
11850     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11851   }
11852 
11853   if (TargetRange.Width > SourceRange.Width) {
11854     if (auto *UO = dyn_cast<UnaryOperator>(E))
11855       if (UO->getOpcode() == UO_Minus)
11856         if (Source->isUnsignedIntegerType()) {
11857           if (Target->isUnsignedIntegerType())
11858             return DiagnoseImpCast(S, E, T, CC,
11859                                    diag::warn_impcast_high_order_zero_bits);
11860           if (Target->isSignedIntegerType())
11861             return DiagnoseImpCast(S, E, T, CC,
11862                                    diag::warn_impcast_nonnegative_result);
11863         }
11864   }
11865 
11866   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11867       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11868     // Warn when doing a signed to signed conversion, warn if the positive
11869     // source value is exactly the width of the target type, which will
11870     // cause a negative value to be stored.
11871 
11872     Expr::EvalResult Result;
11873     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11874         !S.SourceMgr.isInSystemMacro(CC)) {
11875       llvm::APSInt Value = Result.Val.getInt();
11876       if (isSameWidthConstantConversion(S, E, T, CC)) {
11877         std::string PrettySourceValue = Value.toString(10);
11878         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11879 
11880         S.DiagRuntimeBehavior(
11881             E->getExprLoc(), E,
11882             S.PDiag(diag::warn_impcast_integer_precision_constant)
11883                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11884                 << E->getSourceRange() << clang::SourceRange(CC));
11885         return;
11886       }
11887     }
11888 
11889     // Fall through for non-constants to give a sign conversion warning.
11890   }
11891 
11892   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11893       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11894        SourceRange.Width == TargetRange.Width)) {
11895     if (S.SourceMgr.isInSystemMacro(CC))
11896       return;
11897 
11898     unsigned DiagID = diag::warn_impcast_integer_sign;
11899 
11900     // Traditionally, gcc has warned about this under -Wsign-compare.
11901     // We also want to warn about it in -Wconversion.
11902     // So if -Wconversion is off, use a completely identical diagnostic
11903     // in the sign-compare group.
11904     // The conditional-checking code will
11905     if (ICContext) {
11906       DiagID = diag::warn_impcast_integer_sign_conditional;
11907       *ICContext = true;
11908     }
11909 
11910     return DiagnoseImpCast(S, E, T, CC, DiagID);
11911   }
11912 
11913   // Diagnose conversions between different enumeration types.
11914   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11915   // type, to give us better diagnostics.
11916   QualType SourceType = E->getType();
11917   if (!S.getLangOpts().CPlusPlus) {
11918     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11919       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11920         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11921         SourceType = S.Context.getTypeDeclType(Enum);
11922         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11923       }
11924   }
11925 
11926   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11927     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11928       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11929           TargetEnum->getDecl()->hasNameForLinkage() &&
11930           SourceEnum != TargetEnum) {
11931         if (S.SourceMgr.isInSystemMacro(CC))
11932           return;
11933 
11934         return DiagnoseImpCast(S, E, SourceType, T, CC,
11935                                diag::warn_impcast_different_enum_types);
11936       }
11937 }
11938 
11939 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11940                                      SourceLocation CC, QualType T);
11941 
11942 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11943                                     SourceLocation CC, bool &ICContext) {
11944   E = E->IgnoreParenImpCasts();
11945 
11946   if (isa<ConditionalOperator>(E))
11947     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11948 
11949   AnalyzeImplicitConversions(S, E, CC);
11950   if (E->getType() != T)
11951     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11952 }
11953 
11954 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11955                                      SourceLocation CC, QualType T) {
11956   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11957 
11958   bool Suspicious = false;
11959   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11960   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11961 
11962   if (T->isBooleanType())
11963     DiagnoseIntInBoolContext(S, E);
11964 
11965   // If -Wconversion would have warned about either of the candidates
11966   // for a signedness conversion to the context type...
11967   if (!Suspicious) return;
11968 
11969   // ...but it's currently ignored...
11970   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11971     return;
11972 
11973   // ...then check whether it would have warned about either of the
11974   // candidates for a signedness conversion to the condition type.
11975   if (E->getType() == T) return;
11976 
11977   Suspicious = false;
11978   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11979                           E->getType(), CC, &Suspicious);
11980   if (!Suspicious)
11981     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11982                             E->getType(), CC, &Suspicious);
11983 }
11984 
11985 /// Check conversion of given expression to boolean.
11986 /// Input argument E is a logical expression.
11987 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11988   if (S.getLangOpts().Bool)
11989     return;
11990   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11991     return;
11992   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11993 }
11994 
11995 namespace {
11996 struct AnalyzeImplicitConversionsWorkItem {
11997   Expr *E;
11998   SourceLocation CC;
11999   bool IsListInit;
12000 };
12001 }
12002 
12003 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12004 /// that should be visited are added to WorkList.
12005 static void AnalyzeImplicitConversions(
12006     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12007     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12008   Expr *OrigE = Item.E;
12009   SourceLocation CC = Item.CC;
12010 
12011   QualType T = OrigE->getType();
12012   Expr *E = OrigE->IgnoreParenImpCasts();
12013 
12014   // Propagate whether we are in a C++ list initialization expression.
12015   // If so, we do not issue warnings for implicit int-float conversion
12016   // precision loss, because C++11 narrowing already handles it.
12017   bool IsListInit = Item.IsListInit ||
12018                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12019 
12020   if (E->isTypeDependent() || E->isValueDependent())
12021     return;
12022 
12023   Expr *SourceExpr = E;
12024   // Examine, but don't traverse into the source expression of an
12025   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12026   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12027   // evaluate it in the context of checking the specific conversion to T though.
12028   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12029     if (auto *Src = OVE->getSourceExpr())
12030       SourceExpr = Src;
12031 
12032   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12033     if (UO->getOpcode() == UO_Not &&
12034         UO->getSubExpr()->isKnownToHaveBooleanValue())
12035       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12036           << OrigE->getSourceRange() << T->isBooleanType()
12037           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12038 
12039   // For conditional operators, we analyze the arguments as if they
12040   // were being fed directly into the output.
12041   if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) {
12042     CheckConditionalOperator(S, CO, CC, T);
12043     return;
12044   }
12045 
12046   // Check implicit argument conversions for function calls.
12047   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12048     CheckImplicitArgumentConversions(S, Call, CC);
12049 
12050   // Go ahead and check any implicit conversions we might have skipped.
12051   // The non-canonical typecheck is just an optimization;
12052   // CheckImplicitConversion will filter out dead implicit conversions.
12053   if (SourceExpr->getType() != T)
12054     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12055 
12056   // Now continue drilling into this expression.
12057 
12058   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12059     // The bound subexpressions in a PseudoObjectExpr are not reachable
12060     // as transitive children.
12061     // FIXME: Use a more uniform representation for this.
12062     for (auto *SE : POE->semantics())
12063       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12064         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12065   }
12066 
12067   // Skip past explicit casts.
12068   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12069     E = CE->getSubExpr()->IgnoreParenImpCasts();
12070     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12071       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12072     WorkList.push_back({E, CC, IsListInit});
12073     return;
12074   }
12075 
12076   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12077     // Do a somewhat different check with comparison operators.
12078     if (BO->isComparisonOp())
12079       return AnalyzeComparison(S, BO);
12080 
12081     // And with simple assignments.
12082     if (BO->getOpcode() == BO_Assign)
12083       return AnalyzeAssignment(S, BO);
12084     // And with compound assignments.
12085     if (BO->isAssignmentOp())
12086       return AnalyzeCompoundAssignment(S, BO);
12087   }
12088 
12089   // These break the otherwise-useful invariant below.  Fortunately,
12090   // we don't really need to recurse into them, because any internal
12091   // expressions should have been analyzed already when they were
12092   // built into statements.
12093   if (isa<StmtExpr>(E)) return;
12094 
12095   // Don't descend into unevaluated contexts.
12096   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12097 
12098   // Now just recurse over the expression's children.
12099   CC = E->getExprLoc();
12100   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12101   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12102   for (Stmt *SubStmt : E->children()) {
12103     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12104     if (!ChildExpr)
12105       continue;
12106 
12107     if (IsLogicalAndOperator &&
12108         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12109       // Ignore checking string literals that are in logical and operators.
12110       // This is a common pattern for asserts.
12111       continue;
12112     WorkList.push_back({ChildExpr, CC, IsListInit});
12113   }
12114 
12115   if (BO && BO->isLogicalOp()) {
12116     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12117     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12118       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12119 
12120     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12121     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12122       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12123   }
12124 
12125   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12126     if (U->getOpcode() == UO_LNot) {
12127       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12128     } else if (U->getOpcode() != UO_AddrOf) {
12129       if (U->getSubExpr()->getType()->isAtomicType())
12130         S.Diag(U->getSubExpr()->getBeginLoc(),
12131                diag::warn_atomic_implicit_seq_cst);
12132     }
12133   }
12134 }
12135 
12136 /// AnalyzeImplicitConversions - Find and report any interesting
12137 /// implicit conversions in the given expression.  There are a couple
12138 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12139 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12140                                        bool IsListInit/*= false*/) {
12141   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12142   WorkList.push_back({OrigE, CC, IsListInit});
12143   while (!WorkList.empty())
12144     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12145 }
12146 
12147 /// Diagnose integer type and any valid implicit conversion to it.
12148 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12149   // Taking into account implicit conversions,
12150   // allow any integer.
12151   if (!E->getType()->isIntegerType()) {
12152     S.Diag(E->getBeginLoc(),
12153            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12154     return true;
12155   }
12156   // Potentially emit standard warnings for implicit conversions if enabled
12157   // using -Wconversion.
12158   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12159   return false;
12160 }
12161 
12162 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12163 // Returns true when emitting a warning about taking the address of a reference.
12164 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12165                               const PartialDiagnostic &PD) {
12166   E = E->IgnoreParenImpCasts();
12167 
12168   const FunctionDecl *FD = nullptr;
12169 
12170   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12171     if (!DRE->getDecl()->getType()->isReferenceType())
12172       return false;
12173   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12174     if (!M->getMemberDecl()->getType()->isReferenceType())
12175       return false;
12176   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12177     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12178       return false;
12179     FD = Call->getDirectCallee();
12180   } else {
12181     return false;
12182   }
12183 
12184   SemaRef.Diag(E->getExprLoc(), PD);
12185 
12186   // If possible, point to location of function.
12187   if (FD) {
12188     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12189   }
12190 
12191   return true;
12192 }
12193 
12194 // Returns true if the SourceLocation is expanded from any macro body.
12195 // Returns false if the SourceLocation is invalid, is from not in a macro
12196 // expansion, or is from expanded from a top-level macro argument.
12197 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12198   if (Loc.isInvalid())
12199     return false;
12200 
12201   while (Loc.isMacroID()) {
12202     if (SM.isMacroBodyExpansion(Loc))
12203       return true;
12204     Loc = SM.getImmediateMacroCallerLoc(Loc);
12205   }
12206 
12207   return false;
12208 }
12209 
12210 /// Diagnose pointers that are always non-null.
12211 /// \param E the expression containing the pointer
12212 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12213 /// compared to a null pointer
12214 /// \param IsEqual True when the comparison is equal to a null pointer
12215 /// \param Range Extra SourceRange to highlight in the diagnostic
12216 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12217                                         Expr::NullPointerConstantKind NullKind,
12218                                         bool IsEqual, SourceRange Range) {
12219   if (!E)
12220     return;
12221 
12222   // Don't warn inside macros.
12223   if (E->getExprLoc().isMacroID()) {
12224     const SourceManager &SM = getSourceManager();
12225     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12226         IsInAnyMacroBody(SM, Range.getBegin()))
12227       return;
12228   }
12229   E = E->IgnoreImpCasts();
12230 
12231   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12232 
12233   if (isa<CXXThisExpr>(E)) {
12234     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12235                                 : diag::warn_this_bool_conversion;
12236     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12237     return;
12238   }
12239 
12240   bool IsAddressOf = false;
12241 
12242   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12243     if (UO->getOpcode() != UO_AddrOf)
12244       return;
12245     IsAddressOf = true;
12246     E = UO->getSubExpr();
12247   }
12248 
12249   if (IsAddressOf) {
12250     unsigned DiagID = IsCompare
12251                           ? diag::warn_address_of_reference_null_compare
12252                           : diag::warn_address_of_reference_bool_conversion;
12253     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12254                                          << IsEqual;
12255     if (CheckForReference(*this, E, PD)) {
12256       return;
12257     }
12258   }
12259 
12260   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12261     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12262     std::string Str;
12263     llvm::raw_string_ostream S(Str);
12264     E->printPretty(S, nullptr, getPrintingPolicy());
12265     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12266                                 : diag::warn_cast_nonnull_to_bool;
12267     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12268       << E->getSourceRange() << Range << IsEqual;
12269     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12270   };
12271 
12272   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12273   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12274     if (auto *Callee = Call->getDirectCallee()) {
12275       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12276         ComplainAboutNonnullParamOrCall(A);
12277         return;
12278       }
12279     }
12280   }
12281 
12282   // Expect to find a single Decl.  Skip anything more complicated.
12283   ValueDecl *D = nullptr;
12284   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12285     D = R->getDecl();
12286   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12287     D = M->getMemberDecl();
12288   }
12289 
12290   // Weak Decls can be null.
12291   if (!D || D->isWeak())
12292     return;
12293 
12294   // Check for parameter decl with nonnull attribute
12295   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12296     if (getCurFunction() &&
12297         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12298       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12299         ComplainAboutNonnullParamOrCall(A);
12300         return;
12301       }
12302 
12303       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12304         // Skip function template not specialized yet.
12305         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12306           return;
12307         auto ParamIter = llvm::find(FD->parameters(), PV);
12308         assert(ParamIter != FD->param_end());
12309         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12310 
12311         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12312           if (!NonNull->args_size()) {
12313               ComplainAboutNonnullParamOrCall(NonNull);
12314               return;
12315           }
12316 
12317           for (const ParamIdx &ArgNo : NonNull->args()) {
12318             if (ArgNo.getASTIndex() == ParamNo) {
12319               ComplainAboutNonnullParamOrCall(NonNull);
12320               return;
12321             }
12322           }
12323         }
12324       }
12325     }
12326   }
12327 
12328   QualType T = D->getType();
12329   const bool IsArray = T->isArrayType();
12330   const bool IsFunction = T->isFunctionType();
12331 
12332   // Address of function is used to silence the function warning.
12333   if (IsAddressOf && IsFunction) {
12334     return;
12335   }
12336 
12337   // Found nothing.
12338   if (!IsAddressOf && !IsFunction && !IsArray)
12339     return;
12340 
12341   // Pretty print the expression for the diagnostic.
12342   std::string Str;
12343   llvm::raw_string_ostream S(Str);
12344   E->printPretty(S, nullptr, getPrintingPolicy());
12345 
12346   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12347                               : diag::warn_impcast_pointer_to_bool;
12348   enum {
12349     AddressOf,
12350     FunctionPointer,
12351     ArrayPointer
12352   } DiagType;
12353   if (IsAddressOf)
12354     DiagType = AddressOf;
12355   else if (IsFunction)
12356     DiagType = FunctionPointer;
12357   else if (IsArray)
12358     DiagType = ArrayPointer;
12359   else
12360     llvm_unreachable("Could not determine diagnostic.");
12361   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12362                                 << Range << IsEqual;
12363 
12364   if (!IsFunction)
12365     return;
12366 
12367   // Suggest '&' to silence the function warning.
12368   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12369       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12370 
12371   // Check to see if '()' fixit should be emitted.
12372   QualType ReturnType;
12373   UnresolvedSet<4> NonTemplateOverloads;
12374   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12375   if (ReturnType.isNull())
12376     return;
12377 
12378   if (IsCompare) {
12379     // There are two cases here.  If there is null constant, the only suggest
12380     // for a pointer return type.  If the null is 0, then suggest if the return
12381     // type is a pointer or an integer type.
12382     if (!ReturnType->isPointerType()) {
12383       if (NullKind == Expr::NPCK_ZeroExpression ||
12384           NullKind == Expr::NPCK_ZeroLiteral) {
12385         if (!ReturnType->isIntegerType())
12386           return;
12387       } else {
12388         return;
12389       }
12390     }
12391   } else { // !IsCompare
12392     // For function to bool, only suggest if the function pointer has bool
12393     // return type.
12394     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12395       return;
12396   }
12397   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12398       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12399 }
12400 
12401 /// Diagnoses "dangerous" implicit conversions within the given
12402 /// expression (which is a full expression).  Implements -Wconversion
12403 /// and -Wsign-compare.
12404 ///
12405 /// \param CC the "context" location of the implicit conversion, i.e.
12406 ///   the most location of the syntactic entity requiring the implicit
12407 ///   conversion
12408 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12409   // Don't diagnose in unevaluated contexts.
12410   if (isUnevaluatedContext())
12411     return;
12412 
12413   // Don't diagnose for value- or type-dependent expressions.
12414   if (E->isTypeDependent() || E->isValueDependent())
12415     return;
12416 
12417   // Check for array bounds violations in cases where the check isn't triggered
12418   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12419   // ArraySubscriptExpr is on the RHS of a variable initialization.
12420   CheckArrayAccess(E);
12421 
12422   // This is not the right CC for (e.g.) a variable initialization.
12423   AnalyzeImplicitConversions(*this, E, CC);
12424 }
12425 
12426 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12427 /// Input argument E is a logical expression.
12428 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12429   ::CheckBoolLikeConversion(*this, E, CC);
12430 }
12431 
12432 /// Diagnose when expression is an integer constant expression and its evaluation
12433 /// results in integer overflow
12434 void Sema::CheckForIntOverflow (Expr *E) {
12435   // Use a work list to deal with nested struct initializers.
12436   SmallVector<Expr *, 2> Exprs(1, E);
12437 
12438   do {
12439     Expr *OriginalE = Exprs.pop_back_val();
12440     Expr *E = OriginalE->IgnoreParenCasts();
12441 
12442     if (isa<BinaryOperator>(E)) {
12443       E->EvaluateForOverflow(Context);
12444       continue;
12445     }
12446 
12447     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12448       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12449     else if (isa<ObjCBoxedExpr>(OriginalE))
12450       E->EvaluateForOverflow(Context);
12451     else if (auto Call = dyn_cast<CallExpr>(E))
12452       Exprs.append(Call->arg_begin(), Call->arg_end());
12453     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12454       Exprs.append(Message->arg_begin(), Message->arg_end());
12455   } while (!Exprs.empty());
12456 }
12457 
12458 namespace {
12459 
12460 /// Visitor for expressions which looks for unsequenced operations on the
12461 /// same object.
12462 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12463   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12464 
12465   /// A tree of sequenced regions within an expression. Two regions are
12466   /// unsequenced if one is an ancestor or a descendent of the other. When we
12467   /// finish processing an expression with sequencing, such as a comma
12468   /// expression, we fold its tree nodes into its parent, since they are
12469   /// unsequenced with respect to nodes we will visit later.
12470   class SequenceTree {
12471     struct Value {
12472       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12473       unsigned Parent : 31;
12474       unsigned Merged : 1;
12475     };
12476     SmallVector<Value, 8> Values;
12477 
12478   public:
12479     /// A region within an expression which may be sequenced with respect
12480     /// to some other region.
12481     class Seq {
12482       friend class SequenceTree;
12483 
12484       unsigned Index;
12485 
12486       explicit Seq(unsigned N) : Index(N) {}
12487 
12488     public:
12489       Seq() : Index(0) {}
12490     };
12491 
12492     SequenceTree() { Values.push_back(Value(0)); }
12493     Seq root() const { return Seq(0); }
12494 
12495     /// Create a new sequence of operations, which is an unsequenced
12496     /// subset of \p Parent. This sequence of operations is sequenced with
12497     /// respect to other children of \p Parent.
12498     Seq allocate(Seq Parent) {
12499       Values.push_back(Value(Parent.Index));
12500       return Seq(Values.size() - 1);
12501     }
12502 
12503     /// Merge a sequence of operations into its parent.
12504     void merge(Seq S) {
12505       Values[S.Index].Merged = true;
12506     }
12507 
12508     /// Determine whether two operations are unsequenced. This operation
12509     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12510     /// should have been merged into its parent as appropriate.
12511     bool isUnsequenced(Seq Cur, Seq Old) {
12512       unsigned C = representative(Cur.Index);
12513       unsigned Target = representative(Old.Index);
12514       while (C >= Target) {
12515         if (C == Target)
12516           return true;
12517         C = Values[C].Parent;
12518       }
12519       return false;
12520     }
12521 
12522   private:
12523     /// Pick a representative for a sequence.
12524     unsigned representative(unsigned K) {
12525       if (Values[K].Merged)
12526         // Perform path compression as we go.
12527         return Values[K].Parent = representative(Values[K].Parent);
12528       return K;
12529     }
12530   };
12531 
12532   /// An object for which we can track unsequenced uses.
12533   using Object = const NamedDecl *;
12534 
12535   /// Different flavors of object usage which we track. We only track the
12536   /// least-sequenced usage of each kind.
12537   enum UsageKind {
12538     /// A read of an object. Multiple unsequenced reads are OK.
12539     UK_Use,
12540 
12541     /// A modification of an object which is sequenced before the value
12542     /// computation of the expression, such as ++n in C++.
12543     UK_ModAsValue,
12544 
12545     /// A modification of an object which is not sequenced before the value
12546     /// computation of the expression, such as n++.
12547     UK_ModAsSideEffect,
12548 
12549     UK_Count = UK_ModAsSideEffect + 1
12550   };
12551 
12552   /// Bundle together a sequencing region and the expression corresponding
12553   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12554   struct Usage {
12555     const Expr *UsageExpr;
12556     SequenceTree::Seq Seq;
12557 
12558     Usage() : UsageExpr(nullptr), Seq() {}
12559   };
12560 
12561   struct UsageInfo {
12562     Usage Uses[UK_Count];
12563 
12564     /// Have we issued a diagnostic for this object already?
12565     bool Diagnosed;
12566 
12567     UsageInfo() : Uses(), Diagnosed(false) {}
12568   };
12569   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12570 
12571   Sema &SemaRef;
12572 
12573   /// Sequenced regions within the expression.
12574   SequenceTree Tree;
12575 
12576   /// Declaration modifications and references which we have seen.
12577   UsageInfoMap UsageMap;
12578 
12579   /// The region we are currently within.
12580   SequenceTree::Seq Region;
12581 
12582   /// Filled in with declarations which were modified as a side-effect
12583   /// (that is, post-increment operations).
12584   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12585 
12586   /// Expressions to check later. We defer checking these to reduce
12587   /// stack usage.
12588   SmallVectorImpl<const Expr *> &WorkList;
12589 
12590   /// RAII object wrapping the visitation of a sequenced subexpression of an
12591   /// expression. At the end of this process, the side-effects of the evaluation
12592   /// become sequenced with respect to the value computation of the result, so
12593   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12594   /// UK_ModAsValue.
12595   struct SequencedSubexpression {
12596     SequencedSubexpression(SequenceChecker &Self)
12597       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12598       Self.ModAsSideEffect = &ModAsSideEffect;
12599     }
12600 
12601     ~SequencedSubexpression() {
12602       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12603         // Add a new usage with usage kind UK_ModAsValue, and then restore
12604         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12605         // the previous one was empty).
12606         UsageInfo &UI = Self.UsageMap[M.first];
12607         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12608         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12609         SideEffectUsage = M.second;
12610       }
12611       Self.ModAsSideEffect = OldModAsSideEffect;
12612     }
12613 
12614     SequenceChecker &Self;
12615     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12616     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12617   };
12618 
12619   /// RAII object wrapping the visitation of a subexpression which we might
12620   /// choose to evaluate as a constant. If any subexpression is evaluated and
12621   /// found to be non-constant, this allows us to suppress the evaluation of
12622   /// the outer expression.
12623   class EvaluationTracker {
12624   public:
12625     EvaluationTracker(SequenceChecker &Self)
12626         : Self(Self), Prev(Self.EvalTracker) {
12627       Self.EvalTracker = this;
12628     }
12629 
12630     ~EvaluationTracker() {
12631       Self.EvalTracker = Prev;
12632       if (Prev)
12633         Prev->EvalOK &= EvalOK;
12634     }
12635 
12636     bool evaluate(const Expr *E, bool &Result) {
12637       if (!EvalOK || E->isValueDependent())
12638         return false;
12639       EvalOK = E->EvaluateAsBooleanCondition(
12640           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12641       return EvalOK;
12642     }
12643 
12644   private:
12645     SequenceChecker &Self;
12646     EvaluationTracker *Prev;
12647     bool EvalOK = true;
12648   } *EvalTracker = nullptr;
12649 
12650   /// Find the object which is produced by the specified expression,
12651   /// if any.
12652   Object getObject(const Expr *E, bool Mod) const {
12653     E = E->IgnoreParenCasts();
12654     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12655       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12656         return getObject(UO->getSubExpr(), Mod);
12657     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12658       if (BO->getOpcode() == BO_Comma)
12659         return getObject(BO->getRHS(), Mod);
12660       if (Mod && BO->isAssignmentOp())
12661         return getObject(BO->getLHS(), Mod);
12662     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12663       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12664       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12665         return ME->getMemberDecl();
12666     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12667       // FIXME: If this is a reference, map through to its value.
12668       return DRE->getDecl();
12669     return nullptr;
12670   }
12671 
12672   /// Note that an object \p O was modified or used by an expression
12673   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12674   /// the object \p O as obtained via the \p UsageMap.
12675   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12676     // Get the old usage for the given object and usage kind.
12677     Usage &U = UI.Uses[UK];
12678     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12679       // If we have a modification as side effect and are in a sequenced
12680       // subexpression, save the old Usage so that we can restore it later
12681       // in SequencedSubexpression::~SequencedSubexpression.
12682       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12683         ModAsSideEffect->push_back(std::make_pair(O, U));
12684       // Then record the new usage with the current sequencing region.
12685       U.UsageExpr = UsageExpr;
12686       U.Seq = Region;
12687     }
12688   }
12689 
12690   /// Check whether a modification or use of an object \p O in an expression
12691   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12692   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12693   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12694   /// usage and false we are checking for a mod-use unsequenced usage.
12695   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12696                   UsageKind OtherKind, bool IsModMod) {
12697     if (UI.Diagnosed)
12698       return;
12699 
12700     const Usage &U = UI.Uses[OtherKind];
12701     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12702       return;
12703 
12704     const Expr *Mod = U.UsageExpr;
12705     const Expr *ModOrUse = UsageExpr;
12706     if (OtherKind == UK_Use)
12707       std::swap(Mod, ModOrUse);
12708 
12709     SemaRef.DiagRuntimeBehavior(
12710         Mod->getExprLoc(), {Mod, ModOrUse},
12711         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12712                                : diag::warn_unsequenced_mod_use)
12713             << O << SourceRange(ModOrUse->getExprLoc()));
12714     UI.Diagnosed = true;
12715   }
12716 
12717   // A note on note{Pre, Post}{Use, Mod}:
12718   //
12719   // (It helps to follow the algorithm with an expression such as
12720   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12721   //  operations before C++17 and both are well-defined in C++17).
12722   //
12723   // When visiting a node which uses/modify an object we first call notePreUse
12724   // or notePreMod before visiting its sub-expression(s). At this point the
12725   // children of the current node have not yet been visited and so the eventual
12726   // uses/modifications resulting from the children of the current node have not
12727   // been recorded yet.
12728   //
12729   // We then visit the children of the current node. After that notePostUse or
12730   // notePostMod is called. These will 1) detect an unsequenced modification
12731   // as side effect (as in "k++ + k") and 2) add a new usage with the
12732   // appropriate usage kind.
12733   //
12734   // We also have to be careful that some operation sequences modification as
12735   // side effect as well (for example: || or ,). To account for this we wrap
12736   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12737   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12738   // which record usages which are modifications as side effect, and then
12739   // downgrade them (or more accurately restore the previous usage which was a
12740   // modification as side effect) when exiting the scope of the sequenced
12741   // subexpression.
12742 
12743   void notePreUse(Object O, const Expr *UseExpr) {
12744     UsageInfo &UI = UsageMap[O];
12745     // Uses conflict with other modifications.
12746     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12747   }
12748 
12749   void notePostUse(Object O, const Expr *UseExpr) {
12750     UsageInfo &UI = UsageMap[O];
12751     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12752                /*IsModMod=*/false);
12753     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12754   }
12755 
12756   void notePreMod(Object O, const Expr *ModExpr) {
12757     UsageInfo &UI = UsageMap[O];
12758     // Modifications conflict with other modifications and with uses.
12759     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12760     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12761   }
12762 
12763   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12764     UsageInfo &UI = UsageMap[O];
12765     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12766                /*IsModMod=*/true);
12767     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12768   }
12769 
12770 public:
12771   SequenceChecker(Sema &S, const Expr *E,
12772                   SmallVectorImpl<const Expr *> &WorkList)
12773       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12774     Visit(E);
12775     // Silence a -Wunused-private-field since WorkList is now unused.
12776     // TODO: Evaluate if it can be used, and if not remove it.
12777     (void)this->WorkList;
12778   }
12779 
12780   void VisitStmt(const Stmt *S) {
12781     // Skip all statements which aren't expressions for now.
12782   }
12783 
12784   void VisitExpr(const Expr *E) {
12785     // By default, just recurse to evaluated subexpressions.
12786     Base::VisitStmt(E);
12787   }
12788 
12789   void VisitCastExpr(const CastExpr *E) {
12790     Object O = Object();
12791     if (E->getCastKind() == CK_LValueToRValue)
12792       O = getObject(E->getSubExpr(), false);
12793 
12794     if (O)
12795       notePreUse(O, E);
12796     VisitExpr(E);
12797     if (O)
12798       notePostUse(O, E);
12799   }
12800 
12801   void VisitSequencedExpressions(const Expr *SequencedBefore,
12802                                  const Expr *SequencedAfter) {
12803     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12804     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12805     SequenceTree::Seq OldRegion = Region;
12806 
12807     {
12808       SequencedSubexpression SeqBefore(*this);
12809       Region = BeforeRegion;
12810       Visit(SequencedBefore);
12811     }
12812 
12813     Region = AfterRegion;
12814     Visit(SequencedAfter);
12815 
12816     Region = OldRegion;
12817 
12818     Tree.merge(BeforeRegion);
12819     Tree.merge(AfterRegion);
12820   }
12821 
12822   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12823     // C++17 [expr.sub]p1:
12824     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12825     //   expression E1 is sequenced before the expression E2.
12826     if (SemaRef.getLangOpts().CPlusPlus17)
12827       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12828     else {
12829       Visit(ASE->getLHS());
12830       Visit(ASE->getRHS());
12831     }
12832   }
12833 
12834   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12835   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12836   void VisitBinPtrMem(const BinaryOperator *BO) {
12837     // C++17 [expr.mptr.oper]p4:
12838     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12839     //  the expression E1 is sequenced before the expression E2.
12840     if (SemaRef.getLangOpts().CPlusPlus17)
12841       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12842     else {
12843       Visit(BO->getLHS());
12844       Visit(BO->getRHS());
12845     }
12846   }
12847 
12848   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12849   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12850   void VisitBinShlShr(const BinaryOperator *BO) {
12851     // C++17 [expr.shift]p4:
12852     //  The expression E1 is sequenced before the expression E2.
12853     if (SemaRef.getLangOpts().CPlusPlus17)
12854       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12855     else {
12856       Visit(BO->getLHS());
12857       Visit(BO->getRHS());
12858     }
12859   }
12860 
12861   void VisitBinComma(const BinaryOperator *BO) {
12862     // C++11 [expr.comma]p1:
12863     //   Every value computation and side effect associated with the left
12864     //   expression is sequenced before every value computation and side
12865     //   effect associated with the right expression.
12866     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12867   }
12868 
12869   void VisitBinAssign(const BinaryOperator *BO) {
12870     SequenceTree::Seq RHSRegion;
12871     SequenceTree::Seq LHSRegion;
12872     if (SemaRef.getLangOpts().CPlusPlus17) {
12873       RHSRegion = Tree.allocate(Region);
12874       LHSRegion = Tree.allocate(Region);
12875     } else {
12876       RHSRegion = Region;
12877       LHSRegion = Region;
12878     }
12879     SequenceTree::Seq OldRegion = Region;
12880 
12881     // C++11 [expr.ass]p1:
12882     //  [...] the assignment is sequenced after the value computation
12883     //  of the right and left operands, [...]
12884     //
12885     // so check it before inspecting the operands and update the
12886     // map afterwards.
12887     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12888     if (O)
12889       notePreMod(O, BO);
12890 
12891     if (SemaRef.getLangOpts().CPlusPlus17) {
12892       // C++17 [expr.ass]p1:
12893       //  [...] The right operand is sequenced before the left operand. [...]
12894       {
12895         SequencedSubexpression SeqBefore(*this);
12896         Region = RHSRegion;
12897         Visit(BO->getRHS());
12898       }
12899 
12900       Region = LHSRegion;
12901       Visit(BO->getLHS());
12902 
12903       if (O && isa<CompoundAssignOperator>(BO))
12904         notePostUse(O, BO);
12905 
12906     } else {
12907       // C++11 does not specify any sequencing between the LHS and RHS.
12908       Region = LHSRegion;
12909       Visit(BO->getLHS());
12910 
12911       if (O && isa<CompoundAssignOperator>(BO))
12912         notePostUse(O, BO);
12913 
12914       Region = RHSRegion;
12915       Visit(BO->getRHS());
12916     }
12917 
12918     // C++11 [expr.ass]p1:
12919     //  the assignment is sequenced [...] before the value computation of the
12920     //  assignment expression.
12921     // C11 6.5.16/3 has no such rule.
12922     Region = OldRegion;
12923     if (O)
12924       notePostMod(O, BO,
12925                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12926                                                   : UK_ModAsSideEffect);
12927     if (SemaRef.getLangOpts().CPlusPlus17) {
12928       Tree.merge(RHSRegion);
12929       Tree.merge(LHSRegion);
12930     }
12931   }
12932 
12933   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12934     VisitBinAssign(CAO);
12935   }
12936 
12937   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12938   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12939   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12940     Object O = getObject(UO->getSubExpr(), true);
12941     if (!O)
12942       return VisitExpr(UO);
12943 
12944     notePreMod(O, UO);
12945     Visit(UO->getSubExpr());
12946     // C++11 [expr.pre.incr]p1:
12947     //   the expression ++x is equivalent to x+=1
12948     notePostMod(O, UO,
12949                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12950                                                 : UK_ModAsSideEffect);
12951   }
12952 
12953   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12954   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12955   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12956     Object O = getObject(UO->getSubExpr(), true);
12957     if (!O)
12958       return VisitExpr(UO);
12959 
12960     notePreMod(O, UO);
12961     Visit(UO->getSubExpr());
12962     notePostMod(O, UO, UK_ModAsSideEffect);
12963   }
12964 
12965   void VisitBinLOr(const BinaryOperator *BO) {
12966     // C++11 [expr.log.or]p2:
12967     //  If the second expression is evaluated, every value computation and
12968     //  side effect associated with the first expression is sequenced before
12969     //  every value computation and side effect associated with the
12970     //  second expression.
12971     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12972     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12973     SequenceTree::Seq OldRegion = Region;
12974 
12975     EvaluationTracker Eval(*this);
12976     {
12977       SequencedSubexpression Sequenced(*this);
12978       Region = LHSRegion;
12979       Visit(BO->getLHS());
12980     }
12981 
12982     // C++11 [expr.log.or]p1:
12983     //  [...] the second operand is not evaluated if the first operand
12984     //  evaluates to true.
12985     bool EvalResult = false;
12986     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12987     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
12988     if (ShouldVisitRHS) {
12989       Region = RHSRegion;
12990       Visit(BO->getRHS());
12991     }
12992 
12993     Region = OldRegion;
12994     Tree.merge(LHSRegion);
12995     Tree.merge(RHSRegion);
12996   }
12997 
12998   void VisitBinLAnd(const BinaryOperator *BO) {
12999     // C++11 [expr.log.and]p2:
13000     //  If the second expression is evaluated, every value computation and
13001     //  side effect associated with the first expression is sequenced before
13002     //  every value computation and side effect associated with the
13003     //  second expression.
13004     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13005     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13006     SequenceTree::Seq OldRegion = Region;
13007 
13008     EvaluationTracker Eval(*this);
13009     {
13010       SequencedSubexpression Sequenced(*this);
13011       Region = LHSRegion;
13012       Visit(BO->getLHS());
13013     }
13014 
13015     // C++11 [expr.log.and]p1:
13016     //  [...] the second operand is not evaluated if the first operand is false.
13017     bool EvalResult = false;
13018     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13019     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13020     if (ShouldVisitRHS) {
13021       Region = RHSRegion;
13022       Visit(BO->getRHS());
13023     }
13024 
13025     Region = OldRegion;
13026     Tree.merge(LHSRegion);
13027     Tree.merge(RHSRegion);
13028   }
13029 
13030   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13031     // C++11 [expr.cond]p1:
13032     //  [...] Every value computation and side effect associated with the first
13033     //  expression is sequenced before every value computation and side effect
13034     //  associated with the second or third expression.
13035     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13036 
13037     // No sequencing is specified between the true and false expression.
13038     // However since exactly one of both is going to be evaluated we can
13039     // consider them to be sequenced. This is needed to avoid warning on
13040     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13041     // both the true and false expressions because we can't evaluate x.
13042     // This will still allow us to detect an expression like (pre C++17)
13043     // "(x ? y += 1 : y += 2) = y".
13044     //
13045     // We don't wrap the visitation of the true and false expression with
13046     // SequencedSubexpression because we don't want to downgrade modifications
13047     // as side effect in the true and false expressions after the visition
13048     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13049     // not warn between the two "y++", but we should warn between the "y++"
13050     // and the "y".
13051     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13052     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13053     SequenceTree::Seq OldRegion = Region;
13054 
13055     EvaluationTracker Eval(*this);
13056     {
13057       SequencedSubexpression Sequenced(*this);
13058       Region = ConditionRegion;
13059       Visit(CO->getCond());
13060     }
13061 
13062     // C++11 [expr.cond]p1:
13063     // [...] The first expression is contextually converted to bool (Clause 4).
13064     // It is evaluated and if it is true, the result of the conditional
13065     // expression is the value of the second expression, otherwise that of the
13066     // third expression. Only one of the second and third expressions is
13067     // evaluated. [...]
13068     bool EvalResult = false;
13069     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13070     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13071     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13072     if (ShouldVisitTrueExpr) {
13073       Region = TrueRegion;
13074       Visit(CO->getTrueExpr());
13075     }
13076     if (ShouldVisitFalseExpr) {
13077       Region = FalseRegion;
13078       Visit(CO->getFalseExpr());
13079     }
13080 
13081     Region = OldRegion;
13082     Tree.merge(ConditionRegion);
13083     Tree.merge(TrueRegion);
13084     Tree.merge(FalseRegion);
13085   }
13086 
13087   void VisitCallExpr(const CallExpr *CE) {
13088     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13089 
13090     if (CE->isUnevaluatedBuiltinCall(Context))
13091       return;
13092 
13093     // C++11 [intro.execution]p15:
13094     //   When calling a function [...], every value computation and side effect
13095     //   associated with any argument expression, or with the postfix expression
13096     //   designating the called function, is sequenced before execution of every
13097     //   expression or statement in the body of the function [and thus before
13098     //   the value computation of its result].
13099     SequencedSubexpression Sequenced(*this);
13100     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13101       // C++17 [expr.call]p5
13102       //   The postfix-expression is sequenced before each expression in the
13103       //   expression-list and any default argument. [...]
13104       SequenceTree::Seq CalleeRegion;
13105       SequenceTree::Seq OtherRegion;
13106       if (SemaRef.getLangOpts().CPlusPlus17) {
13107         CalleeRegion = Tree.allocate(Region);
13108         OtherRegion = Tree.allocate(Region);
13109       } else {
13110         CalleeRegion = Region;
13111         OtherRegion = Region;
13112       }
13113       SequenceTree::Seq OldRegion = Region;
13114 
13115       // Visit the callee expression first.
13116       Region = CalleeRegion;
13117       if (SemaRef.getLangOpts().CPlusPlus17) {
13118         SequencedSubexpression Sequenced(*this);
13119         Visit(CE->getCallee());
13120       } else {
13121         Visit(CE->getCallee());
13122       }
13123 
13124       // Then visit the argument expressions.
13125       Region = OtherRegion;
13126       for (const Expr *Argument : CE->arguments())
13127         Visit(Argument);
13128 
13129       Region = OldRegion;
13130       if (SemaRef.getLangOpts().CPlusPlus17) {
13131         Tree.merge(CalleeRegion);
13132         Tree.merge(OtherRegion);
13133       }
13134     });
13135   }
13136 
13137   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13138     // C++17 [over.match.oper]p2:
13139     //   [...] the operator notation is first transformed to the equivalent
13140     //   function-call notation as summarized in Table 12 (where @ denotes one
13141     //   of the operators covered in the specified subclause). However, the
13142     //   operands are sequenced in the order prescribed for the built-in
13143     //   operator (Clause 8).
13144     //
13145     // From the above only overloaded binary operators and overloaded call
13146     // operators have sequencing rules in C++17 that we need to handle
13147     // separately.
13148     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13149         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13150       return VisitCallExpr(CXXOCE);
13151 
13152     enum {
13153       NoSequencing,
13154       LHSBeforeRHS,
13155       RHSBeforeLHS,
13156       LHSBeforeRest
13157     } SequencingKind;
13158     switch (CXXOCE->getOperator()) {
13159     case OO_Equal:
13160     case OO_PlusEqual:
13161     case OO_MinusEqual:
13162     case OO_StarEqual:
13163     case OO_SlashEqual:
13164     case OO_PercentEqual:
13165     case OO_CaretEqual:
13166     case OO_AmpEqual:
13167     case OO_PipeEqual:
13168     case OO_LessLessEqual:
13169     case OO_GreaterGreaterEqual:
13170       SequencingKind = RHSBeforeLHS;
13171       break;
13172 
13173     case OO_LessLess:
13174     case OO_GreaterGreater:
13175     case OO_AmpAmp:
13176     case OO_PipePipe:
13177     case OO_Comma:
13178     case OO_ArrowStar:
13179     case OO_Subscript:
13180       SequencingKind = LHSBeforeRHS;
13181       break;
13182 
13183     case OO_Call:
13184       SequencingKind = LHSBeforeRest;
13185       break;
13186 
13187     default:
13188       SequencingKind = NoSequencing;
13189       break;
13190     }
13191 
13192     if (SequencingKind == NoSequencing)
13193       return VisitCallExpr(CXXOCE);
13194 
13195     // This is a call, so all subexpressions are sequenced before the result.
13196     SequencedSubexpression Sequenced(*this);
13197 
13198     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13199       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13200              "Should only get there with C++17 and above!");
13201       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13202              "Should only get there with an overloaded binary operator"
13203              " or an overloaded call operator!");
13204 
13205       if (SequencingKind == LHSBeforeRest) {
13206         assert(CXXOCE->getOperator() == OO_Call &&
13207                "We should only have an overloaded call operator here!");
13208 
13209         // This is very similar to VisitCallExpr, except that we only have the
13210         // C++17 case. The postfix-expression is the first argument of the
13211         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13212         // are in the following arguments.
13213         //
13214         // Note that we intentionally do not visit the callee expression since
13215         // it is just a decayed reference to a function.
13216         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13217         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13218         SequenceTree::Seq OldRegion = Region;
13219 
13220         assert(CXXOCE->getNumArgs() >= 1 &&
13221                "An overloaded call operator must have at least one argument"
13222                " for the postfix-expression!");
13223         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13224         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13225                                           CXXOCE->getNumArgs() - 1);
13226 
13227         // Visit the postfix-expression first.
13228         {
13229           Region = PostfixExprRegion;
13230           SequencedSubexpression Sequenced(*this);
13231           Visit(PostfixExpr);
13232         }
13233 
13234         // Then visit the argument expressions.
13235         Region = ArgsRegion;
13236         for (const Expr *Arg : Args)
13237           Visit(Arg);
13238 
13239         Region = OldRegion;
13240         Tree.merge(PostfixExprRegion);
13241         Tree.merge(ArgsRegion);
13242       } else {
13243         assert(CXXOCE->getNumArgs() == 2 &&
13244                "Should only have two arguments here!");
13245         assert((SequencingKind == LHSBeforeRHS ||
13246                 SequencingKind == RHSBeforeLHS) &&
13247                "Unexpected sequencing kind!");
13248 
13249         // We do not visit the callee expression since it is just a decayed
13250         // reference to a function.
13251         const Expr *E1 = CXXOCE->getArg(0);
13252         const Expr *E2 = CXXOCE->getArg(1);
13253         if (SequencingKind == RHSBeforeLHS)
13254           std::swap(E1, E2);
13255 
13256         return VisitSequencedExpressions(E1, E2);
13257       }
13258     });
13259   }
13260 
13261   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13262     // This is a call, so all subexpressions are sequenced before the result.
13263     SequencedSubexpression Sequenced(*this);
13264 
13265     if (!CCE->isListInitialization())
13266       return VisitExpr(CCE);
13267 
13268     // In C++11, list initializations are sequenced.
13269     SmallVector<SequenceTree::Seq, 32> Elts;
13270     SequenceTree::Seq Parent = Region;
13271     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13272                                               E = CCE->arg_end();
13273          I != E; ++I) {
13274       Region = Tree.allocate(Parent);
13275       Elts.push_back(Region);
13276       Visit(*I);
13277     }
13278 
13279     // Forget that the initializers are sequenced.
13280     Region = Parent;
13281     for (unsigned I = 0; I < Elts.size(); ++I)
13282       Tree.merge(Elts[I]);
13283   }
13284 
13285   void VisitInitListExpr(const InitListExpr *ILE) {
13286     if (!SemaRef.getLangOpts().CPlusPlus11)
13287       return VisitExpr(ILE);
13288 
13289     // In C++11, list initializations are sequenced.
13290     SmallVector<SequenceTree::Seq, 32> Elts;
13291     SequenceTree::Seq Parent = Region;
13292     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13293       const Expr *E = ILE->getInit(I);
13294       if (!E)
13295         continue;
13296       Region = Tree.allocate(Parent);
13297       Elts.push_back(Region);
13298       Visit(E);
13299     }
13300 
13301     // Forget that the initializers are sequenced.
13302     Region = Parent;
13303     for (unsigned I = 0; I < Elts.size(); ++I)
13304       Tree.merge(Elts[I]);
13305   }
13306 };
13307 
13308 } // namespace
13309 
13310 void Sema::CheckUnsequencedOperations(const Expr *E) {
13311   SmallVector<const Expr *, 8> WorkList;
13312   WorkList.push_back(E);
13313   while (!WorkList.empty()) {
13314     const Expr *Item = WorkList.pop_back_val();
13315     SequenceChecker(*this, Item, WorkList);
13316   }
13317 }
13318 
13319 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13320                               bool IsConstexpr) {
13321   llvm::SaveAndRestore<bool> ConstantContext(
13322       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13323   CheckImplicitConversions(E, CheckLoc);
13324   if (!E->isInstantiationDependent())
13325     CheckUnsequencedOperations(E);
13326   if (!IsConstexpr && !E->isValueDependent())
13327     CheckForIntOverflow(E);
13328   DiagnoseMisalignedMembers();
13329 }
13330 
13331 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13332                                        FieldDecl *BitField,
13333                                        Expr *Init) {
13334   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13335 }
13336 
13337 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13338                                          SourceLocation Loc) {
13339   if (!PType->isVariablyModifiedType())
13340     return;
13341   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13342     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13343     return;
13344   }
13345   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13346     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13347     return;
13348   }
13349   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13350     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13351     return;
13352   }
13353 
13354   const ArrayType *AT = S.Context.getAsArrayType(PType);
13355   if (!AT)
13356     return;
13357 
13358   if (AT->getSizeModifier() != ArrayType::Star) {
13359     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13360     return;
13361   }
13362 
13363   S.Diag(Loc, diag::err_array_star_in_function_definition);
13364 }
13365 
13366 /// CheckParmsForFunctionDef - Check that the parameters of the given
13367 /// function are appropriate for the definition of a function. This
13368 /// takes care of any checks that cannot be performed on the
13369 /// declaration itself, e.g., that the types of each of the function
13370 /// parameters are complete.
13371 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13372                                     bool CheckParameterNames) {
13373   bool HasInvalidParm = false;
13374   for (ParmVarDecl *Param : Parameters) {
13375     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13376     // function declarator that is part of a function definition of
13377     // that function shall not have incomplete type.
13378     //
13379     // This is also C++ [dcl.fct]p6.
13380     if (!Param->isInvalidDecl() &&
13381         RequireCompleteType(Param->getLocation(), Param->getType(),
13382                             diag::err_typecheck_decl_incomplete_type)) {
13383       Param->setInvalidDecl();
13384       HasInvalidParm = true;
13385     }
13386 
13387     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13388     // declaration of each parameter shall include an identifier.
13389     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13390         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13391       // Diagnose this as an extension in C17 and earlier.
13392       if (!getLangOpts().C2x)
13393         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13394     }
13395 
13396     // C99 6.7.5.3p12:
13397     //   If the function declarator is not part of a definition of that
13398     //   function, parameters may have incomplete type and may use the [*]
13399     //   notation in their sequences of declarator specifiers to specify
13400     //   variable length array types.
13401     QualType PType = Param->getOriginalType();
13402     // FIXME: This diagnostic should point the '[*]' if source-location
13403     // information is added for it.
13404     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13405 
13406     // If the parameter is a c++ class type and it has to be destructed in the
13407     // callee function, declare the destructor so that it can be called by the
13408     // callee function. Do not perform any direct access check on the dtor here.
13409     if (!Param->isInvalidDecl()) {
13410       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13411         if (!ClassDecl->isInvalidDecl() &&
13412             !ClassDecl->hasIrrelevantDestructor() &&
13413             !ClassDecl->isDependentContext() &&
13414             ClassDecl->isParamDestroyedInCallee()) {
13415           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13416           MarkFunctionReferenced(Param->getLocation(), Destructor);
13417           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13418         }
13419       }
13420     }
13421 
13422     // Parameters with the pass_object_size attribute only need to be marked
13423     // constant at function definitions. Because we lack information about
13424     // whether we're on a declaration or definition when we're instantiating the
13425     // attribute, we need to check for constness here.
13426     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13427       if (!Param->getType().isConstQualified())
13428         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13429             << Attr->getSpelling() << 1;
13430 
13431     // Check for parameter names shadowing fields from the class.
13432     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13433       // The owning context for the parameter should be the function, but we
13434       // want to see if this function's declaration context is a record.
13435       DeclContext *DC = Param->getDeclContext();
13436       if (DC && DC->isFunctionOrMethod()) {
13437         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13438           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13439                                      RD, /*DeclIsField*/ false);
13440       }
13441     }
13442   }
13443 
13444   return HasInvalidParm;
13445 }
13446 
13447 Optional<std::pair<CharUnits, CharUnits>>
13448 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13449 
13450 /// Compute the alignment and offset of the base class object given the
13451 /// derived-to-base cast expression and the alignment and offset of the derived
13452 /// class object.
13453 static std::pair<CharUnits, CharUnits>
13454 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13455                                    CharUnits BaseAlignment, CharUnits Offset,
13456                                    ASTContext &Ctx) {
13457   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13458        ++PathI) {
13459     const CXXBaseSpecifier *Base = *PathI;
13460     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13461     if (Base->isVirtual()) {
13462       // The complete object may have a lower alignment than the non-virtual
13463       // alignment of the base, in which case the base may be misaligned. Choose
13464       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13465       // conservative lower bound of the complete object alignment.
13466       CharUnits NonVirtualAlignment =
13467           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13468       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13469       Offset = CharUnits::Zero();
13470     } else {
13471       const ASTRecordLayout &RL =
13472           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13473       Offset += RL.getBaseClassOffset(BaseDecl);
13474     }
13475     DerivedType = Base->getType();
13476   }
13477 
13478   return std::make_pair(BaseAlignment, Offset);
13479 }
13480 
13481 /// Compute the alignment and offset of a binary additive operator.
13482 static Optional<std::pair<CharUnits, CharUnits>>
13483 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13484                                      bool IsSub, ASTContext &Ctx) {
13485   QualType PointeeType = PtrE->getType()->getPointeeType();
13486 
13487   if (!PointeeType->isConstantSizeType())
13488     return llvm::None;
13489 
13490   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13491 
13492   if (!P)
13493     return llvm::None;
13494 
13495   llvm::APSInt IdxRes;
13496   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13497   if (IntE->isIntegerConstantExpr(IdxRes, Ctx)) {
13498     CharUnits Offset = EltSize * IdxRes.getExtValue();
13499     if (IsSub)
13500       Offset = -Offset;
13501     return std::make_pair(P->first, P->second + Offset);
13502   }
13503 
13504   // If the integer expression isn't a constant expression, compute the lower
13505   // bound of the alignment using the alignment and offset of the pointer
13506   // expression and the element size.
13507   return std::make_pair(
13508       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13509       CharUnits::Zero());
13510 }
13511 
13512 /// This helper function takes an lvalue expression and returns the alignment of
13513 /// a VarDecl and a constant offset from the VarDecl.
13514 Optional<std::pair<CharUnits, CharUnits>>
13515 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
13516   E = E->IgnoreParens();
13517   switch (E->getStmtClass()) {
13518   default:
13519     break;
13520   case Stmt::CStyleCastExprClass:
13521   case Stmt::CXXStaticCastExprClass:
13522   case Stmt::ImplicitCastExprClass: {
13523     auto *CE = cast<CastExpr>(E);
13524     const Expr *From = CE->getSubExpr();
13525     switch (CE->getCastKind()) {
13526     default:
13527       break;
13528     case CK_NoOp:
13529       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13530     case CK_UncheckedDerivedToBase:
13531     case CK_DerivedToBase: {
13532       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13533       if (!P)
13534         break;
13535       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13536                                                 P->second, Ctx);
13537     }
13538     }
13539     break;
13540   }
13541   case Stmt::ArraySubscriptExprClass: {
13542     auto *ASE = cast<ArraySubscriptExpr>(E);
13543     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
13544                                                 false, Ctx);
13545   }
13546   case Stmt::DeclRefExprClass: {
13547     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13548       // FIXME: If VD is captured by copy or is an escaping __block variable,
13549       // use the alignment of VD's type.
13550       if (!VD->getType()->isReferenceType())
13551         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
13552       if (VD->hasInit())
13553         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13554     }
13555     break;
13556   }
13557   case Stmt::MemberExprClass: {
13558     auto *ME = cast<MemberExpr>(E);
13559     if (ME->isArrow())
13560       break;
13561     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13562     if (!FD || FD->getType()->isReferenceType())
13563       break;
13564     auto P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13565     if (!P)
13566       break;
13567     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13568     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13569     return std::make_pair(P->first,
13570                           P->second + CharUnits::fromQuantity(Offset));
13571   }
13572   case Stmt::UnaryOperatorClass: {
13573     auto *UO = cast<UnaryOperator>(E);
13574     switch (UO->getOpcode()) {
13575     default:
13576       break;
13577     case UO_Deref:
13578       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
13579     }
13580     break;
13581   }
13582   case Stmt::BinaryOperatorClass: {
13583     auto *BO = cast<BinaryOperator>(E);
13584     auto Opcode = BO->getOpcode();
13585     switch (Opcode) {
13586     default:
13587       break;
13588     case BO_Comma:
13589       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
13590     }
13591     break;
13592   }
13593   }
13594   return llvm::None;
13595 }
13596 
13597 /// This helper function takes a pointer expression and returns the alignment of
13598 /// a VarDecl and a constant offset from the VarDecl.
13599 Optional<std::pair<CharUnits, CharUnits>>
13600 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
13601   E = E->IgnoreParens();
13602   switch (E->getStmtClass()) {
13603   default:
13604     break;
13605   case Stmt::CStyleCastExprClass:
13606   case Stmt::CXXStaticCastExprClass:
13607   case Stmt::ImplicitCastExprClass: {
13608     auto *CE = cast<CastExpr>(E);
13609     const Expr *From = CE->getSubExpr();
13610     switch (CE->getCastKind()) {
13611     default:
13612       break;
13613     case CK_NoOp:
13614       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13615     case CK_ArrayToPointerDecay:
13616       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13617     case CK_UncheckedDerivedToBase:
13618     case CK_DerivedToBase: {
13619       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13620       if (!P)
13621         break;
13622       return getDerivedToBaseAlignmentAndOffset(
13623           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13624     }
13625     }
13626     break;
13627   }
13628   case Stmt::UnaryOperatorClass: {
13629     auto *UO = cast<UnaryOperator>(E);
13630     if (UO->getOpcode() == UO_AddrOf)
13631       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
13632     break;
13633   }
13634   case Stmt::BinaryOperatorClass: {
13635     auto *BO = cast<BinaryOperator>(E);
13636     auto Opcode = BO->getOpcode();
13637     switch (Opcode) {
13638     default:
13639       break;
13640     case BO_Add:
13641     case BO_Sub: {
13642       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13643       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13644         std::swap(LHS, RHS);
13645       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13646                                                   Ctx);
13647     }
13648     case BO_Comma:
13649       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13650     }
13651     break;
13652   }
13653   }
13654   return llvm::None;
13655 }
13656 
13657 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
13658   // See if we can compute the alignment of a VarDecl and an offset from it.
13659   Optional<std::pair<CharUnits, CharUnits>> P =
13660       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
13661 
13662   if (P)
13663     return P->first.alignmentAtOffset(P->second);
13664 
13665   // If that failed, return the type's alignment.
13666   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
13667 }
13668 
13669 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13670 /// pointer cast increases the alignment requirements.
13671 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13672   // This is actually a lot of work to potentially be doing on every
13673   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13674   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13675     return;
13676 
13677   // Ignore dependent types.
13678   if (T->isDependentType() || Op->getType()->isDependentType())
13679     return;
13680 
13681   // Require that the destination be a pointer type.
13682   const PointerType *DestPtr = T->getAs<PointerType>();
13683   if (!DestPtr) return;
13684 
13685   // If the destination has alignment 1, we're done.
13686   QualType DestPointee = DestPtr->getPointeeType();
13687   if (DestPointee->isIncompleteType()) return;
13688   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13689   if (DestAlign.isOne()) return;
13690 
13691   // Require that the source be a pointer type.
13692   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13693   if (!SrcPtr) return;
13694   QualType SrcPointee = SrcPtr->getPointeeType();
13695 
13696   // Explicitly allow casts from cv void*.  We already implicitly
13697   // allowed casts to cv void*, since they have alignment 1.
13698   // Also allow casts involving incomplete types, which implicitly
13699   // includes 'void'.
13700   if (SrcPointee->isIncompleteType()) return;
13701 
13702   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
13703 
13704   if (SrcAlign >= DestAlign) return;
13705 
13706   Diag(TRange.getBegin(), diag::warn_cast_align)
13707     << Op->getType() << T
13708     << static_cast<unsigned>(SrcAlign.getQuantity())
13709     << static_cast<unsigned>(DestAlign.getQuantity())
13710     << TRange << Op->getSourceRange();
13711 }
13712 
13713 /// Check whether this array fits the idiom of a size-one tail padded
13714 /// array member of a struct.
13715 ///
13716 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13717 /// commonly used to emulate flexible arrays in C89 code.
13718 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13719                                     const NamedDecl *ND) {
13720   if (Size != 1 || !ND) return false;
13721 
13722   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13723   if (!FD) return false;
13724 
13725   // Don't consider sizes resulting from macro expansions or template argument
13726   // substitution to form C89 tail-padded arrays.
13727 
13728   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13729   while (TInfo) {
13730     TypeLoc TL = TInfo->getTypeLoc();
13731     // Look through typedefs.
13732     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13733       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13734       TInfo = TDL->getTypeSourceInfo();
13735       continue;
13736     }
13737     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13738       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13739       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13740         return false;
13741     }
13742     break;
13743   }
13744 
13745   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13746   if (!RD) return false;
13747   if (RD->isUnion()) return false;
13748   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13749     if (!CRD->isStandardLayout()) return false;
13750   }
13751 
13752   // See if this is the last field decl in the record.
13753   const Decl *D = FD;
13754   while ((D = D->getNextDeclInContext()))
13755     if (isa<FieldDecl>(D))
13756       return false;
13757   return true;
13758 }
13759 
13760 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13761                             const ArraySubscriptExpr *ASE,
13762                             bool AllowOnePastEnd, bool IndexNegated) {
13763   // Already diagnosed by the constant evaluator.
13764   if (isConstantEvaluated())
13765     return;
13766 
13767   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13768   if (IndexExpr->isValueDependent())
13769     return;
13770 
13771   const Type *EffectiveType =
13772       BaseExpr->getType()->getPointeeOrArrayElementType();
13773   BaseExpr = BaseExpr->IgnoreParenCasts();
13774   const ConstantArrayType *ArrayTy =
13775       Context.getAsConstantArrayType(BaseExpr->getType());
13776 
13777   if (!ArrayTy)
13778     return;
13779 
13780   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13781   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13782     return;
13783 
13784   Expr::EvalResult Result;
13785   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13786     return;
13787 
13788   llvm::APSInt index = Result.Val.getInt();
13789   if (IndexNegated)
13790     index = -index;
13791 
13792   const NamedDecl *ND = nullptr;
13793   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13794     ND = DRE->getDecl();
13795   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13796     ND = ME->getMemberDecl();
13797 
13798   if (index.isUnsigned() || !index.isNegative()) {
13799     // It is possible that the type of the base expression after
13800     // IgnoreParenCasts is incomplete, even though the type of the base
13801     // expression before IgnoreParenCasts is complete (see PR39746 for an
13802     // example). In this case we have no information about whether the array
13803     // access exceeds the array bounds. However we can still diagnose an array
13804     // access which precedes the array bounds.
13805     if (BaseType->isIncompleteType())
13806       return;
13807 
13808     llvm::APInt size = ArrayTy->getSize();
13809     if (!size.isStrictlyPositive())
13810       return;
13811 
13812     if (BaseType != EffectiveType) {
13813       // Make sure we're comparing apples to apples when comparing index to size
13814       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13815       uint64_t array_typesize = Context.getTypeSize(BaseType);
13816       // Handle ptrarith_typesize being zero, such as when casting to void*
13817       if (!ptrarith_typesize) ptrarith_typesize = 1;
13818       if (ptrarith_typesize != array_typesize) {
13819         // There's a cast to a different size type involved
13820         uint64_t ratio = array_typesize / ptrarith_typesize;
13821         // TODO: Be smarter about handling cases where array_typesize is not a
13822         // multiple of ptrarith_typesize
13823         if (ptrarith_typesize * ratio == array_typesize)
13824           size *= llvm::APInt(size.getBitWidth(), ratio);
13825       }
13826     }
13827 
13828     if (size.getBitWidth() > index.getBitWidth())
13829       index = index.zext(size.getBitWidth());
13830     else if (size.getBitWidth() < index.getBitWidth())
13831       size = size.zext(index.getBitWidth());
13832 
13833     // For array subscripting the index must be less than size, but for pointer
13834     // arithmetic also allow the index (offset) to be equal to size since
13835     // computing the next address after the end of the array is legal and
13836     // commonly done e.g. in C++ iterators and range-based for loops.
13837     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13838       return;
13839 
13840     // Also don't warn for arrays of size 1 which are members of some
13841     // structure. These are often used to approximate flexible arrays in C89
13842     // code.
13843     if (IsTailPaddedMemberArray(*this, size, ND))
13844       return;
13845 
13846     // Suppress the warning if the subscript expression (as identified by the
13847     // ']' location) and the index expression are both from macro expansions
13848     // within a system header.
13849     if (ASE) {
13850       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13851           ASE->getRBracketLoc());
13852       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13853         SourceLocation IndexLoc =
13854             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13855         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13856           return;
13857       }
13858     }
13859 
13860     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13861     if (ASE)
13862       DiagID = diag::warn_array_index_exceeds_bounds;
13863 
13864     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13865                         PDiag(DiagID) << index.toString(10, true)
13866                                       << size.toString(10, true)
13867                                       << (unsigned)size.getLimitedValue(~0U)
13868                                       << IndexExpr->getSourceRange());
13869   } else {
13870     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13871     if (!ASE) {
13872       DiagID = diag::warn_ptr_arith_precedes_bounds;
13873       if (index.isNegative()) index = -index;
13874     }
13875 
13876     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13877                         PDiag(DiagID) << index.toString(10, true)
13878                                       << IndexExpr->getSourceRange());
13879   }
13880 
13881   if (!ND) {
13882     // Try harder to find a NamedDecl to point at in the note.
13883     while (const ArraySubscriptExpr *ASE =
13884            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13885       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13886     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13887       ND = DRE->getDecl();
13888     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13889       ND = ME->getMemberDecl();
13890   }
13891 
13892   if (ND)
13893     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13894                         PDiag(diag::note_array_declared_here)
13895                             << ND->getDeclName());
13896 }
13897 
13898 void Sema::CheckArrayAccess(const Expr *expr) {
13899   int AllowOnePastEnd = 0;
13900   while (expr) {
13901     expr = expr->IgnoreParenImpCasts();
13902     switch (expr->getStmtClass()) {
13903       case Stmt::ArraySubscriptExprClass: {
13904         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13905         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13906                          AllowOnePastEnd > 0);
13907         expr = ASE->getBase();
13908         break;
13909       }
13910       case Stmt::MemberExprClass: {
13911         expr = cast<MemberExpr>(expr)->getBase();
13912         break;
13913       }
13914       case Stmt::OMPArraySectionExprClass: {
13915         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13916         if (ASE->getLowerBound())
13917           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13918                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13919         return;
13920       }
13921       case Stmt::UnaryOperatorClass: {
13922         // Only unwrap the * and & unary operators
13923         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13924         expr = UO->getSubExpr();
13925         switch (UO->getOpcode()) {
13926           case UO_AddrOf:
13927             AllowOnePastEnd++;
13928             break;
13929           case UO_Deref:
13930             AllowOnePastEnd--;
13931             break;
13932           default:
13933             return;
13934         }
13935         break;
13936       }
13937       case Stmt::ConditionalOperatorClass: {
13938         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13939         if (const Expr *lhs = cond->getLHS())
13940           CheckArrayAccess(lhs);
13941         if (const Expr *rhs = cond->getRHS())
13942           CheckArrayAccess(rhs);
13943         return;
13944       }
13945       case Stmt::CXXOperatorCallExprClass: {
13946         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13947         for (const auto *Arg : OCE->arguments())
13948           CheckArrayAccess(Arg);
13949         return;
13950       }
13951       default:
13952         return;
13953     }
13954   }
13955 }
13956 
13957 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13958 
13959 namespace {
13960 
13961 struct RetainCycleOwner {
13962   VarDecl *Variable = nullptr;
13963   SourceRange Range;
13964   SourceLocation Loc;
13965   bool Indirect = false;
13966 
13967   RetainCycleOwner() = default;
13968 
13969   void setLocsFrom(Expr *e) {
13970     Loc = e->getExprLoc();
13971     Range = e->getSourceRange();
13972   }
13973 };
13974 
13975 } // namespace
13976 
13977 /// Consider whether capturing the given variable can possibly lead to
13978 /// a retain cycle.
13979 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13980   // In ARC, it's captured strongly iff the variable has __strong
13981   // lifetime.  In MRR, it's captured strongly if the variable is
13982   // __block and has an appropriate type.
13983   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13984     return false;
13985 
13986   owner.Variable = var;
13987   if (ref)
13988     owner.setLocsFrom(ref);
13989   return true;
13990 }
13991 
13992 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13993   while (true) {
13994     e = e->IgnoreParens();
13995     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13996       switch (cast->getCastKind()) {
13997       case CK_BitCast:
13998       case CK_LValueBitCast:
13999       case CK_LValueToRValue:
14000       case CK_ARCReclaimReturnedObject:
14001         e = cast->getSubExpr();
14002         continue;
14003 
14004       default:
14005         return false;
14006       }
14007     }
14008 
14009     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14010       ObjCIvarDecl *ivar = ref->getDecl();
14011       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14012         return false;
14013 
14014       // Try to find a retain cycle in the base.
14015       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14016         return false;
14017 
14018       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14019       owner.Indirect = true;
14020       return true;
14021     }
14022 
14023     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14024       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14025       if (!var) return false;
14026       return considerVariable(var, ref, owner);
14027     }
14028 
14029     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14030       if (member->isArrow()) return false;
14031 
14032       // Don't count this as an indirect ownership.
14033       e = member->getBase();
14034       continue;
14035     }
14036 
14037     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14038       // Only pay attention to pseudo-objects on property references.
14039       ObjCPropertyRefExpr *pre
14040         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14041                                               ->IgnoreParens());
14042       if (!pre) return false;
14043       if (pre->isImplicitProperty()) return false;
14044       ObjCPropertyDecl *property = pre->getExplicitProperty();
14045       if (!property->isRetaining() &&
14046           !(property->getPropertyIvarDecl() &&
14047             property->getPropertyIvarDecl()->getType()
14048               .getObjCLifetime() == Qualifiers::OCL_Strong))
14049           return false;
14050 
14051       owner.Indirect = true;
14052       if (pre->isSuperReceiver()) {
14053         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14054         if (!owner.Variable)
14055           return false;
14056         owner.Loc = pre->getLocation();
14057         owner.Range = pre->getSourceRange();
14058         return true;
14059       }
14060       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14061                               ->getSourceExpr());
14062       continue;
14063     }
14064 
14065     // Array ivars?
14066 
14067     return false;
14068   }
14069 }
14070 
14071 namespace {
14072 
14073   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14074     ASTContext &Context;
14075     VarDecl *Variable;
14076     Expr *Capturer = nullptr;
14077     bool VarWillBeReased = false;
14078 
14079     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14080         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14081           Context(Context), Variable(variable) {}
14082 
14083     void VisitDeclRefExpr(DeclRefExpr *ref) {
14084       if (ref->getDecl() == Variable && !Capturer)
14085         Capturer = ref;
14086     }
14087 
14088     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14089       if (Capturer) return;
14090       Visit(ref->getBase());
14091       if (Capturer && ref->isFreeIvar())
14092         Capturer = ref;
14093     }
14094 
14095     void VisitBlockExpr(BlockExpr *block) {
14096       // Look inside nested blocks
14097       if (block->getBlockDecl()->capturesVariable(Variable))
14098         Visit(block->getBlockDecl()->getBody());
14099     }
14100 
14101     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14102       if (Capturer) return;
14103       if (OVE->getSourceExpr())
14104         Visit(OVE->getSourceExpr());
14105     }
14106 
14107     void VisitBinaryOperator(BinaryOperator *BinOp) {
14108       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14109         return;
14110       Expr *LHS = BinOp->getLHS();
14111       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14112         if (DRE->getDecl() != Variable)
14113           return;
14114         if (Expr *RHS = BinOp->getRHS()) {
14115           RHS = RHS->IgnoreParenCasts();
14116           llvm::APSInt Value;
14117           VarWillBeReased =
14118             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
14119         }
14120       }
14121     }
14122   };
14123 
14124 } // namespace
14125 
14126 /// Check whether the given argument is a block which captures a
14127 /// variable.
14128 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14129   assert(owner.Variable && owner.Loc.isValid());
14130 
14131   e = e->IgnoreParenCasts();
14132 
14133   // Look through [^{...} copy] and Block_copy(^{...}).
14134   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14135     Selector Cmd = ME->getSelector();
14136     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14137       e = ME->getInstanceReceiver();
14138       if (!e)
14139         return nullptr;
14140       e = e->IgnoreParenCasts();
14141     }
14142   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14143     if (CE->getNumArgs() == 1) {
14144       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14145       if (Fn) {
14146         const IdentifierInfo *FnI = Fn->getIdentifier();
14147         if (FnI && FnI->isStr("_Block_copy")) {
14148           e = CE->getArg(0)->IgnoreParenCasts();
14149         }
14150       }
14151     }
14152   }
14153 
14154   BlockExpr *block = dyn_cast<BlockExpr>(e);
14155   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14156     return nullptr;
14157 
14158   FindCaptureVisitor visitor(S.Context, owner.Variable);
14159   visitor.Visit(block->getBlockDecl()->getBody());
14160   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14161 }
14162 
14163 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14164                                 RetainCycleOwner &owner) {
14165   assert(capturer);
14166   assert(owner.Variable && owner.Loc.isValid());
14167 
14168   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14169     << owner.Variable << capturer->getSourceRange();
14170   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14171     << owner.Indirect << owner.Range;
14172 }
14173 
14174 /// Check for a keyword selector that starts with the word 'add' or
14175 /// 'set'.
14176 static bool isSetterLikeSelector(Selector sel) {
14177   if (sel.isUnarySelector()) return false;
14178 
14179   StringRef str = sel.getNameForSlot(0);
14180   while (!str.empty() && str.front() == '_') str = str.substr(1);
14181   if (str.startswith("set"))
14182     str = str.substr(3);
14183   else if (str.startswith("add")) {
14184     // Specially allow 'addOperationWithBlock:'.
14185     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14186       return false;
14187     str = str.substr(3);
14188   }
14189   else
14190     return false;
14191 
14192   if (str.empty()) return true;
14193   return !isLowercase(str.front());
14194 }
14195 
14196 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14197                                                     ObjCMessageExpr *Message) {
14198   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14199                                                 Message->getReceiverInterface(),
14200                                                 NSAPI::ClassId_NSMutableArray);
14201   if (!IsMutableArray) {
14202     return None;
14203   }
14204 
14205   Selector Sel = Message->getSelector();
14206 
14207   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14208     S.NSAPIObj->getNSArrayMethodKind(Sel);
14209   if (!MKOpt) {
14210     return None;
14211   }
14212 
14213   NSAPI::NSArrayMethodKind MK = *MKOpt;
14214 
14215   switch (MK) {
14216     case NSAPI::NSMutableArr_addObject:
14217     case NSAPI::NSMutableArr_insertObjectAtIndex:
14218     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14219       return 0;
14220     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14221       return 1;
14222 
14223     default:
14224       return None;
14225   }
14226 
14227   return None;
14228 }
14229 
14230 static
14231 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14232                                                   ObjCMessageExpr *Message) {
14233   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14234                                             Message->getReceiverInterface(),
14235                                             NSAPI::ClassId_NSMutableDictionary);
14236   if (!IsMutableDictionary) {
14237     return None;
14238   }
14239 
14240   Selector Sel = Message->getSelector();
14241 
14242   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14243     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14244   if (!MKOpt) {
14245     return None;
14246   }
14247 
14248   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14249 
14250   switch (MK) {
14251     case NSAPI::NSMutableDict_setObjectForKey:
14252     case NSAPI::NSMutableDict_setValueForKey:
14253     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14254       return 0;
14255 
14256     default:
14257       return None;
14258   }
14259 
14260   return None;
14261 }
14262 
14263 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14264   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14265                                                 Message->getReceiverInterface(),
14266                                                 NSAPI::ClassId_NSMutableSet);
14267 
14268   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14269                                             Message->getReceiverInterface(),
14270                                             NSAPI::ClassId_NSMutableOrderedSet);
14271   if (!IsMutableSet && !IsMutableOrderedSet) {
14272     return None;
14273   }
14274 
14275   Selector Sel = Message->getSelector();
14276 
14277   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14278   if (!MKOpt) {
14279     return None;
14280   }
14281 
14282   NSAPI::NSSetMethodKind MK = *MKOpt;
14283 
14284   switch (MK) {
14285     case NSAPI::NSMutableSet_addObject:
14286     case NSAPI::NSOrderedSet_setObjectAtIndex:
14287     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14288     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14289       return 0;
14290     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14291       return 1;
14292   }
14293 
14294   return None;
14295 }
14296 
14297 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14298   if (!Message->isInstanceMessage()) {
14299     return;
14300   }
14301 
14302   Optional<int> ArgOpt;
14303 
14304   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14305       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14306       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14307     return;
14308   }
14309 
14310   int ArgIndex = *ArgOpt;
14311 
14312   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14313   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14314     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14315   }
14316 
14317   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14318     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14319       if (ArgRE->isObjCSelfExpr()) {
14320         Diag(Message->getSourceRange().getBegin(),
14321              diag::warn_objc_circular_container)
14322           << ArgRE->getDecl() << StringRef("'super'");
14323       }
14324     }
14325   } else {
14326     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14327 
14328     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14329       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14330     }
14331 
14332     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14333       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14334         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14335           ValueDecl *Decl = ReceiverRE->getDecl();
14336           Diag(Message->getSourceRange().getBegin(),
14337                diag::warn_objc_circular_container)
14338             << Decl << Decl;
14339           if (!ArgRE->isObjCSelfExpr()) {
14340             Diag(Decl->getLocation(),
14341                  diag::note_objc_circular_container_declared_here)
14342               << Decl;
14343           }
14344         }
14345       }
14346     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14347       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14348         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14349           ObjCIvarDecl *Decl = IvarRE->getDecl();
14350           Diag(Message->getSourceRange().getBegin(),
14351                diag::warn_objc_circular_container)
14352             << Decl << Decl;
14353           Diag(Decl->getLocation(),
14354                diag::note_objc_circular_container_declared_here)
14355             << Decl;
14356         }
14357       }
14358     }
14359   }
14360 }
14361 
14362 /// Check a message send to see if it's likely to cause a retain cycle.
14363 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14364   // Only check instance methods whose selector looks like a setter.
14365   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14366     return;
14367 
14368   // Try to find a variable that the receiver is strongly owned by.
14369   RetainCycleOwner owner;
14370   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14371     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14372       return;
14373   } else {
14374     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14375     owner.Variable = getCurMethodDecl()->getSelfDecl();
14376     owner.Loc = msg->getSuperLoc();
14377     owner.Range = msg->getSuperLoc();
14378   }
14379 
14380   // Check whether the receiver is captured by any of the arguments.
14381   const ObjCMethodDecl *MD = msg->getMethodDecl();
14382   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14383     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14384       // noescape blocks should not be retained by the method.
14385       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14386         continue;
14387       return diagnoseRetainCycle(*this, capturer, owner);
14388     }
14389   }
14390 }
14391 
14392 /// Check a property assign to see if it's likely to cause a retain cycle.
14393 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14394   RetainCycleOwner owner;
14395   if (!findRetainCycleOwner(*this, receiver, owner))
14396     return;
14397 
14398   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14399     diagnoseRetainCycle(*this, capturer, owner);
14400 }
14401 
14402 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14403   RetainCycleOwner Owner;
14404   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14405     return;
14406 
14407   // Because we don't have an expression for the variable, we have to set the
14408   // location explicitly here.
14409   Owner.Loc = Var->getLocation();
14410   Owner.Range = Var->getSourceRange();
14411 
14412   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14413     diagnoseRetainCycle(*this, Capturer, Owner);
14414 }
14415 
14416 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14417                                      Expr *RHS, bool isProperty) {
14418   // Check if RHS is an Objective-C object literal, which also can get
14419   // immediately zapped in a weak reference.  Note that we explicitly
14420   // allow ObjCStringLiterals, since those are designed to never really die.
14421   RHS = RHS->IgnoreParenImpCasts();
14422 
14423   // This enum needs to match with the 'select' in
14424   // warn_objc_arc_literal_assign (off-by-1).
14425   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14426   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14427     return false;
14428 
14429   S.Diag(Loc, diag::warn_arc_literal_assign)
14430     << (unsigned) Kind
14431     << (isProperty ? 0 : 1)
14432     << RHS->getSourceRange();
14433 
14434   return true;
14435 }
14436 
14437 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14438                                     Qualifiers::ObjCLifetime LT,
14439                                     Expr *RHS, bool isProperty) {
14440   // Strip off any implicit cast added to get to the one ARC-specific.
14441   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14442     if (cast->getCastKind() == CK_ARCConsumeObject) {
14443       S.Diag(Loc, diag::warn_arc_retained_assign)
14444         << (LT == Qualifiers::OCL_ExplicitNone)
14445         << (isProperty ? 0 : 1)
14446         << RHS->getSourceRange();
14447       return true;
14448     }
14449     RHS = cast->getSubExpr();
14450   }
14451 
14452   if (LT == Qualifiers::OCL_Weak &&
14453       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14454     return true;
14455 
14456   return false;
14457 }
14458 
14459 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14460                               QualType LHS, Expr *RHS) {
14461   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14462 
14463   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14464     return false;
14465 
14466   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14467     return true;
14468 
14469   return false;
14470 }
14471 
14472 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14473                               Expr *LHS, Expr *RHS) {
14474   QualType LHSType;
14475   // PropertyRef on LHS type need be directly obtained from
14476   // its declaration as it has a PseudoType.
14477   ObjCPropertyRefExpr *PRE
14478     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14479   if (PRE && !PRE->isImplicitProperty()) {
14480     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14481     if (PD)
14482       LHSType = PD->getType();
14483   }
14484 
14485   if (LHSType.isNull())
14486     LHSType = LHS->getType();
14487 
14488   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14489 
14490   if (LT == Qualifiers::OCL_Weak) {
14491     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14492       getCurFunction()->markSafeWeakUse(LHS);
14493   }
14494 
14495   if (checkUnsafeAssigns(Loc, LHSType, RHS))
14496     return;
14497 
14498   // FIXME. Check for other life times.
14499   if (LT != Qualifiers::OCL_None)
14500     return;
14501 
14502   if (PRE) {
14503     if (PRE->isImplicitProperty())
14504       return;
14505     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14506     if (!PD)
14507       return;
14508 
14509     unsigned Attributes = PD->getPropertyAttributes();
14510     if (Attributes & ObjCPropertyAttribute::kind_assign) {
14511       // when 'assign' attribute was not explicitly specified
14512       // by user, ignore it and rely on property type itself
14513       // for lifetime info.
14514       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14515       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14516           LHSType->isObjCRetainableType())
14517         return;
14518 
14519       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14520         if (cast->getCastKind() == CK_ARCConsumeObject) {
14521           Diag(Loc, diag::warn_arc_retained_property_assign)
14522           << RHS->getSourceRange();
14523           return;
14524         }
14525         RHS = cast->getSubExpr();
14526       }
14527     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
14528       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14529         return;
14530     }
14531   }
14532 }
14533 
14534 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14535 
14536 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14537                                         SourceLocation StmtLoc,
14538                                         const NullStmt *Body) {
14539   // Do not warn if the body is a macro that expands to nothing, e.g:
14540   //
14541   // #define CALL(x)
14542   // if (condition)
14543   //   CALL(0);
14544   if (Body->hasLeadingEmptyMacro())
14545     return false;
14546 
14547   // Get line numbers of statement and body.
14548   bool StmtLineInvalid;
14549   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14550                                                       &StmtLineInvalid);
14551   if (StmtLineInvalid)
14552     return false;
14553 
14554   bool BodyLineInvalid;
14555   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14556                                                       &BodyLineInvalid);
14557   if (BodyLineInvalid)
14558     return false;
14559 
14560   // Warn if null statement and body are on the same line.
14561   if (StmtLine != BodyLine)
14562     return false;
14563 
14564   return true;
14565 }
14566 
14567 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14568                                  const Stmt *Body,
14569                                  unsigned DiagID) {
14570   // Since this is a syntactic check, don't emit diagnostic for template
14571   // instantiations, this just adds noise.
14572   if (CurrentInstantiationScope)
14573     return;
14574 
14575   // The body should be a null statement.
14576   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14577   if (!NBody)
14578     return;
14579 
14580   // Do the usual checks.
14581   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14582     return;
14583 
14584   Diag(NBody->getSemiLoc(), DiagID);
14585   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14586 }
14587 
14588 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14589                                  const Stmt *PossibleBody) {
14590   assert(!CurrentInstantiationScope); // Ensured by caller
14591 
14592   SourceLocation StmtLoc;
14593   const Stmt *Body;
14594   unsigned DiagID;
14595   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14596     StmtLoc = FS->getRParenLoc();
14597     Body = FS->getBody();
14598     DiagID = diag::warn_empty_for_body;
14599   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14600     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14601     Body = WS->getBody();
14602     DiagID = diag::warn_empty_while_body;
14603   } else
14604     return; // Neither `for' nor `while'.
14605 
14606   // The body should be a null statement.
14607   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14608   if (!NBody)
14609     return;
14610 
14611   // Skip expensive checks if diagnostic is disabled.
14612   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14613     return;
14614 
14615   // Do the usual checks.
14616   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14617     return;
14618 
14619   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14620   // noise level low, emit diagnostics only if for/while is followed by a
14621   // CompoundStmt, e.g.:
14622   //    for (int i = 0; i < n; i++);
14623   //    {
14624   //      a(i);
14625   //    }
14626   // or if for/while is followed by a statement with more indentation
14627   // than for/while itself:
14628   //    for (int i = 0; i < n; i++);
14629   //      a(i);
14630   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14631   if (!ProbableTypo) {
14632     bool BodyColInvalid;
14633     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14634         PossibleBody->getBeginLoc(), &BodyColInvalid);
14635     if (BodyColInvalid)
14636       return;
14637 
14638     bool StmtColInvalid;
14639     unsigned StmtCol =
14640         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14641     if (StmtColInvalid)
14642       return;
14643 
14644     if (BodyCol > StmtCol)
14645       ProbableTypo = true;
14646   }
14647 
14648   if (ProbableTypo) {
14649     Diag(NBody->getSemiLoc(), DiagID);
14650     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14651   }
14652 }
14653 
14654 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14655 
14656 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14657 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14658                              SourceLocation OpLoc) {
14659   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14660     return;
14661 
14662   if (inTemplateInstantiation())
14663     return;
14664 
14665   // Strip parens and casts away.
14666   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14667   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14668 
14669   // Check for a call expression
14670   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14671   if (!CE || CE->getNumArgs() != 1)
14672     return;
14673 
14674   // Check for a call to std::move
14675   if (!CE->isCallToStdMove())
14676     return;
14677 
14678   // Get argument from std::move
14679   RHSExpr = CE->getArg(0);
14680 
14681   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14682   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14683 
14684   // Two DeclRefExpr's, check that the decls are the same.
14685   if (LHSDeclRef && RHSDeclRef) {
14686     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14687       return;
14688     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14689         RHSDeclRef->getDecl()->getCanonicalDecl())
14690       return;
14691 
14692     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14693                                         << LHSExpr->getSourceRange()
14694                                         << RHSExpr->getSourceRange();
14695     return;
14696   }
14697 
14698   // Member variables require a different approach to check for self moves.
14699   // MemberExpr's are the same if every nested MemberExpr refers to the same
14700   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14701   // the base Expr's are CXXThisExpr's.
14702   const Expr *LHSBase = LHSExpr;
14703   const Expr *RHSBase = RHSExpr;
14704   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14705   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14706   if (!LHSME || !RHSME)
14707     return;
14708 
14709   while (LHSME && RHSME) {
14710     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14711         RHSME->getMemberDecl()->getCanonicalDecl())
14712       return;
14713 
14714     LHSBase = LHSME->getBase();
14715     RHSBase = RHSME->getBase();
14716     LHSME = dyn_cast<MemberExpr>(LHSBase);
14717     RHSME = dyn_cast<MemberExpr>(RHSBase);
14718   }
14719 
14720   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14721   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14722   if (LHSDeclRef && RHSDeclRef) {
14723     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14724       return;
14725     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14726         RHSDeclRef->getDecl()->getCanonicalDecl())
14727       return;
14728 
14729     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14730                                         << LHSExpr->getSourceRange()
14731                                         << RHSExpr->getSourceRange();
14732     return;
14733   }
14734 
14735   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14736     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14737                                         << LHSExpr->getSourceRange()
14738                                         << RHSExpr->getSourceRange();
14739 }
14740 
14741 //===--- Layout compatibility ----------------------------------------------//
14742 
14743 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14744 
14745 /// Check if two enumeration types are layout-compatible.
14746 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14747   // C++11 [dcl.enum] p8:
14748   // Two enumeration types are layout-compatible if they have the same
14749   // underlying type.
14750   return ED1->isComplete() && ED2->isComplete() &&
14751          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14752 }
14753 
14754 /// Check if two fields are layout-compatible.
14755 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14756                                FieldDecl *Field2) {
14757   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14758     return false;
14759 
14760   if (Field1->isBitField() != Field2->isBitField())
14761     return false;
14762 
14763   if (Field1->isBitField()) {
14764     // Make sure that the bit-fields are the same length.
14765     unsigned Bits1 = Field1->getBitWidthValue(C);
14766     unsigned Bits2 = Field2->getBitWidthValue(C);
14767 
14768     if (Bits1 != Bits2)
14769       return false;
14770   }
14771 
14772   return true;
14773 }
14774 
14775 /// Check if two standard-layout structs are layout-compatible.
14776 /// (C++11 [class.mem] p17)
14777 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14778                                      RecordDecl *RD2) {
14779   // If both records are C++ classes, check that base classes match.
14780   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14781     // If one of records is a CXXRecordDecl we are in C++ mode,
14782     // thus the other one is a CXXRecordDecl, too.
14783     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14784     // Check number of base classes.
14785     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14786       return false;
14787 
14788     // Check the base classes.
14789     for (CXXRecordDecl::base_class_const_iterator
14790                Base1 = D1CXX->bases_begin(),
14791            BaseEnd1 = D1CXX->bases_end(),
14792               Base2 = D2CXX->bases_begin();
14793          Base1 != BaseEnd1;
14794          ++Base1, ++Base2) {
14795       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14796         return false;
14797     }
14798   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14799     // If only RD2 is a C++ class, it should have zero base classes.
14800     if (D2CXX->getNumBases() > 0)
14801       return false;
14802   }
14803 
14804   // Check the fields.
14805   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14806                              Field2End = RD2->field_end(),
14807                              Field1 = RD1->field_begin(),
14808                              Field1End = RD1->field_end();
14809   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14810     if (!isLayoutCompatible(C, *Field1, *Field2))
14811       return false;
14812   }
14813   if (Field1 != Field1End || Field2 != Field2End)
14814     return false;
14815 
14816   return true;
14817 }
14818 
14819 /// Check if two standard-layout unions are layout-compatible.
14820 /// (C++11 [class.mem] p18)
14821 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14822                                     RecordDecl *RD2) {
14823   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14824   for (auto *Field2 : RD2->fields())
14825     UnmatchedFields.insert(Field2);
14826 
14827   for (auto *Field1 : RD1->fields()) {
14828     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14829         I = UnmatchedFields.begin(),
14830         E = UnmatchedFields.end();
14831 
14832     for ( ; I != E; ++I) {
14833       if (isLayoutCompatible(C, Field1, *I)) {
14834         bool Result = UnmatchedFields.erase(*I);
14835         (void) Result;
14836         assert(Result);
14837         break;
14838       }
14839     }
14840     if (I == E)
14841       return false;
14842   }
14843 
14844   return UnmatchedFields.empty();
14845 }
14846 
14847 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14848                                RecordDecl *RD2) {
14849   if (RD1->isUnion() != RD2->isUnion())
14850     return false;
14851 
14852   if (RD1->isUnion())
14853     return isLayoutCompatibleUnion(C, RD1, RD2);
14854   else
14855     return isLayoutCompatibleStruct(C, RD1, RD2);
14856 }
14857 
14858 /// Check if two types are layout-compatible in C++11 sense.
14859 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14860   if (T1.isNull() || T2.isNull())
14861     return false;
14862 
14863   // C++11 [basic.types] p11:
14864   // If two types T1 and T2 are the same type, then T1 and T2 are
14865   // layout-compatible types.
14866   if (C.hasSameType(T1, T2))
14867     return true;
14868 
14869   T1 = T1.getCanonicalType().getUnqualifiedType();
14870   T2 = T2.getCanonicalType().getUnqualifiedType();
14871 
14872   const Type::TypeClass TC1 = T1->getTypeClass();
14873   const Type::TypeClass TC2 = T2->getTypeClass();
14874 
14875   if (TC1 != TC2)
14876     return false;
14877 
14878   if (TC1 == Type::Enum) {
14879     return isLayoutCompatible(C,
14880                               cast<EnumType>(T1)->getDecl(),
14881                               cast<EnumType>(T2)->getDecl());
14882   } else if (TC1 == Type::Record) {
14883     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14884       return false;
14885 
14886     return isLayoutCompatible(C,
14887                               cast<RecordType>(T1)->getDecl(),
14888                               cast<RecordType>(T2)->getDecl());
14889   }
14890 
14891   return false;
14892 }
14893 
14894 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14895 
14896 /// Given a type tag expression find the type tag itself.
14897 ///
14898 /// \param TypeExpr Type tag expression, as it appears in user's code.
14899 ///
14900 /// \param VD Declaration of an identifier that appears in a type tag.
14901 ///
14902 /// \param MagicValue Type tag magic value.
14903 ///
14904 /// \param isConstantEvaluated wether the evalaution should be performed in
14905 
14906 /// constant context.
14907 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14908                             const ValueDecl **VD, uint64_t *MagicValue,
14909                             bool isConstantEvaluated) {
14910   while(true) {
14911     if (!TypeExpr)
14912       return false;
14913 
14914     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14915 
14916     switch (TypeExpr->getStmtClass()) {
14917     case Stmt::UnaryOperatorClass: {
14918       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14919       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14920         TypeExpr = UO->getSubExpr();
14921         continue;
14922       }
14923       return false;
14924     }
14925 
14926     case Stmt::DeclRefExprClass: {
14927       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14928       *VD = DRE->getDecl();
14929       return true;
14930     }
14931 
14932     case Stmt::IntegerLiteralClass: {
14933       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14934       llvm::APInt MagicValueAPInt = IL->getValue();
14935       if (MagicValueAPInt.getActiveBits() <= 64) {
14936         *MagicValue = MagicValueAPInt.getZExtValue();
14937         return true;
14938       } else
14939         return false;
14940     }
14941 
14942     case Stmt::BinaryConditionalOperatorClass:
14943     case Stmt::ConditionalOperatorClass: {
14944       const AbstractConditionalOperator *ACO =
14945           cast<AbstractConditionalOperator>(TypeExpr);
14946       bool Result;
14947       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14948                                                      isConstantEvaluated)) {
14949         if (Result)
14950           TypeExpr = ACO->getTrueExpr();
14951         else
14952           TypeExpr = ACO->getFalseExpr();
14953         continue;
14954       }
14955       return false;
14956     }
14957 
14958     case Stmt::BinaryOperatorClass: {
14959       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14960       if (BO->getOpcode() == BO_Comma) {
14961         TypeExpr = BO->getRHS();
14962         continue;
14963       }
14964       return false;
14965     }
14966 
14967     default:
14968       return false;
14969     }
14970   }
14971 }
14972 
14973 /// Retrieve the C type corresponding to type tag TypeExpr.
14974 ///
14975 /// \param TypeExpr Expression that specifies a type tag.
14976 ///
14977 /// \param MagicValues Registered magic values.
14978 ///
14979 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14980 ///        kind.
14981 ///
14982 /// \param TypeInfo Information about the corresponding C type.
14983 ///
14984 /// \param isConstantEvaluated wether the evalaution should be performed in
14985 /// constant context.
14986 ///
14987 /// \returns true if the corresponding C type was found.
14988 static bool GetMatchingCType(
14989     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14990     const ASTContext &Ctx,
14991     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14992         *MagicValues,
14993     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14994     bool isConstantEvaluated) {
14995   FoundWrongKind = false;
14996 
14997   // Variable declaration that has type_tag_for_datatype attribute.
14998   const ValueDecl *VD = nullptr;
14999 
15000   uint64_t MagicValue;
15001 
15002   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15003     return false;
15004 
15005   if (VD) {
15006     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15007       if (I->getArgumentKind() != ArgumentKind) {
15008         FoundWrongKind = true;
15009         return false;
15010       }
15011       TypeInfo.Type = I->getMatchingCType();
15012       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15013       TypeInfo.MustBeNull = I->getMustBeNull();
15014       return true;
15015     }
15016     return false;
15017   }
15018 
15019   if (!MagicValues)
15020     return false;
15021 
15022   llvm::DenseMap<Sema::TypeTagMagicValue,
15023                  Sema::TypeTagData>::const_iterator I =
15024       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15025   if (I == MagicValues->end())
15026     return false;
15027 
15028   TypeInfo = I->second;
15029   return true;
15030 }
15031 
15032 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15033                                       uint64_t MagicValue, QualType Type,
15034                                       bool LayoutCompatible,
15035                                       bool MustBeNull) {
15036   if (!TypeTagForDatatypeMagicValues)
15037     TypeTagForDatatypeMagicValues.reset(
15038         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15039 
15040   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15041   (*TypeTagForDatatypeMagicValues)[Magic] =
15042       TypeTagData(Type, LayoutCompatible, MustBeNull);
15043 }
15044 
15045 static bool IsSameCharType(QualType T1, QualType T2) {
15046   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15047   if (!BT1)
15048     return false;
15049 
15050   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15051   if (!BT2)
15052     return false;
15053 
15054   BuiltinType::Kind T1Kind = BT1->getKind();
15055   BuiltinType::Kind T2Kind = BT2->getKind();
15056 
15057   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15058          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15059          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15060          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15061 }
15062 
15063 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15064                                     const ArrayRef<const Expr *> ExprArgs,
15065                                     SourceLocation CallSiteLoc) {
15066   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15067   bool IsPointerAttr = Attr->getIsPointer();
15068 
15069   // Retrieve the argument representing the 'type_tag'.
15070   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15071   if (TypeTagIdxAST >= ExprArgs.size()) {
15072     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15073         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15074     return;
15075   }
15076   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15077   bool FoundWrongKind;
15078   TypeTagData TypeInfo;
15079   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15080                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15081                         TypeInfo, isConstantEvaluated())) {
15082     if (FoundWrongKind)
15083       Diag(TypeTagExpr->getExprLoc(),
15084            diag::warn_type_tag_for_datatype_wrong_kind)
15085         << TypeTagExpr->getSourceRange();
15086     return;
15087   }
15088 
15089   // Retrieve the argument representing the 'arg_idx'.
15090   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15091   if (ArgumentIdxAST >= ExprArgs.size()) {
15092     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15093         << 1 << Attr->getArgumentIdx().getSourceIndex();
15094     return;
15095   }
15096   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15097   if (IsPointerAttr) {
15098     // Skip implicit cast of pointer to `void *' (as a function argument).
15099     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15100       if (ICE->getType()->isVoidPointerType() &&
15101           ICE->getCastKind() == CK_BitCast)
15102         ArgumentExpr = ICE->getSubExpr();
15103   }
15104   QualType ArgumentType = ArgumentExpr->getType();
15105 
15106   // Passing a `void*' pointer shouldn't trigger a warning.
15107   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15108     return;
15109 
15110   if (TypeInfo.MustBeNull) {
15111     // Type tag with matching void type requires a null pointer.
15112     if (!ArgumentExpr->isNullPointerConstant(Context,
15113                                              Expr::NPC_ValueDependentIsNotNull)) {
15114       Diag(ArgumentExpr->getExprLoc(),
15115            diag::warn_type_safety_null_pointer_required)
15116           << ArgumentKind->getName()
15117           << ArgumentExpr->getSourceRange()
15118           << TypeTagExpr->getSourceRange();
15119     }
15120     return;
15121   }
15122 
15123   QualType RequiredType = TypeInfo.Type;
15124   if (IsPointerAttr)
15125     RequiredType = Context.getPointerType(RequiredType);
15126 
15127   bool mismatch = false;
15128   if (!TypeInfo.LayoutCompatible) {
15129     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15130 
15131     // C++11 [basic.fundamental] p1:
15132     // Plain char, signed char, and unsigned char are three distinct types.
15133     //
15134     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15135     // char' depending on the current char signedness mode.
15136     if (mismatch)
15137       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15138                                            RequiredType->getPointeeType())) ||
15139           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15140         mismatch = false;
15141   } else
15142     if (IsPointerAttr)
15143       mismatch = !isLayoutCompatible(Context,
15144                                      ArgumentType->getPointeeType(),
15145                                      RequiredType->getPointeeType());
15146     else
15147       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15148 
15149   if (mismatch)
15150     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15151         << ArgumentType << ArgumentKind
15152         << TypeInfo.LayoutCompatible << RequiredType
15153         << ArgumentExpr->getSourceRange()
15154         << TypeTagExpr->getSourceRange();
15155 }
15156 
15157 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15158                                          CharUnits Alignment) {
15159   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15160 }
15161 
15162 void Sema::DiagnoseMisalignedMembers() {
15163   for (MisalignedMember &m : MisalignedMembers) {
15164     const NamedDecl *ND = m.RD;
15165     if (ND->getName().empty()) {
15166       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15167         ND = TD;
15168     }
15169     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15170         << m.MD << ND << m.E->getSourceRange();
15171   }
15172   MisalignedMembers.clear();
15173 }
15174 
15175 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15176   E = E->IgnoreParens();
15177   if (!T->isPointerType() && !T->isIntegerType())
15178     return;
15179   if (isa<UnaryOperator>(E) &&
15180       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15181     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15182     if (isa<MemberExpr>(Op)) {
15183       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15184       if (MA != MisalignedMembers.end() &&
15185           (T->isIntegerType() ||
15186            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15187                                    Context.getTypeAlignInChars(
15188                                        T->getPointeeType()) <= MA->Alignment))))
15189         MisalignedMembers.erase(MA);
15190     }
15191   }
15192 }
15193 
15194 void Sema::RefersToMemberWithReducedAlignment(
15195     Expr *E,
15196     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15197         Action) {
15198   const auto *ME = dyn_cast<MemberExpr>(E);
15199   if (!ME)
15200     return;
15201 
15202   // No need to check expressions with an __unaligned-qualified type.
15203   if (E->getType().getQualifiers().hasUnaligned())
15204     return;
15205 
15206   // For a chain of MemberExpr like "a.b.c.d" this list
15207   // will keep FieldDecl's like [d, c, b].
15208   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15209   const MemberExpr *TopME = nullptr;
15210   bool AnyIsPacked = false;
15211   do {
15212     QualType BaseType = ME->getBase()->getType();
15213     if (BaseType->isDependentType())
15214       return;
15215     if (ME->isArrow())
15216       BaseType = BaseType->getPointeeType();
15217     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15218     if (RD->isInvalidDecl())
15219       return;
15220 
15221     ValueDecl *MD = ME->getMemberDecl();
15222     auto *FD = dyn_cast<FieldDecl>(MD);
15223     // We do not care about non-data members.
15224     if (!FD || FD->isInvalidDecl())
15225       return;
15226 
15227     AnyIsPacked =
15228         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15229     ReverseMemberChain.push_back(FD);
15230 
15231     TopME = ME;
15232     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15233   } while (ME);
15234   assert(TopME && "We did not compute a topmost MemberExpr!");
15235 
15236   // Not the scope of this diagnostic.
15237   if (!AnyIsPacked)
15238     return;
15239 
15240   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15241   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15242   // TODO: The innermost base of the member expression may be too complicated.
15243   // For now, just disregard these cases. This is left for future
15244   // improvement.
15245   if (!DRE && !isa<CXXThisExpr>(TopBase))
15246       return;
15247 
15248   // Alignment expected by the whole expression.
15249   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15250 
15251   // No need to do anything else with this case.
15252   if (ExpectedAlignment.isOne())
15253     return;
15254 
15255   // Synthesize offset of the whole access.
15256   CharUnits Offset;
15257   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15258        I++) {
15259     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15260   }
15261 
15262   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15263   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15264       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15265 
15266   // The base expression of the innermost MemberExpr may give
15267   // stronger guarantees than the class containing the member.
15268   if (DRE && !TopME->isArrow()) {
15269     const ValueDecl *VD = DRE->getDecl();
15270     if (!VD->getType()->isReferenceType())
15271       CompleteObjectAlignment =
15272           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15273   }
15274 
15275   // Check if the synthesized offset fulfills the alignment.
15276   if (Offset % ExpectedAlignment != 0 ||
15277       // It may fulfill the offset it but the effective alignment may still be
15278       // lower than the expected expression alignment.
15279       CompleteObjectAlignment < ExpectedAlignment) {
15280     // If this happens, we want to determine a sensible culprit of this.
15281     // Intuitively, watching the chain of member expressions from right to
15282     // left, we start with the required alignment (as required by the field
15283     // type) but some packed attribute in that chain has reduced the alignment.
15284     // It may happen that another packed structure increases it again. But if
15285     // we are here such increase has not been enough. So pointing the first
15286     // FieldDecl that either is packed or else its RecordDecl is,
15287     // seems reasonable.
15288     FieldDecl *FD = nullptr;
15289     CharUnits Alignment;
15290     for (FieldDecl *FDI : ReverseMemberChain) {
15291       if (FDI->hasAttr<PackedAttr>() ||
15292           FDI->getParent()->hasAttr<PackedAttr>()) {
15293         FD = FDI;
15294         Alignment = std::min(
15295             Context.getTypeAlignInChars(FD->getType()),
15296             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15297         break;
15298       }
15299     }
15300     assert(FD && "We did not find a packed FieldDecl!");
15301     Action(E, FD->getParent(), FD, Alignment);
15302   }
15303 }
15304 
15305 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15306   using namespace std::placeholders;
15307 
15308   RefersToMemberWithReducedAlignment(
15309       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15310                      _2, _3, _4));
15311 }
15312 
15313 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15314                                             ExprResult CallResult) {
15315   if (checkArgCount(*this, TheCall, 1))
15316     return ExprError();
15317 
15318   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15319   if (MatrixArg.isInvalid())
15320     return MatrixArg;
15321   Expr *Matrix = MatrixArg.get();
15322 
15323   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15324   if (!MType) {
15325     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15326     return ExprError();
15327   }
15328 
15329   // Create returned matrix type by swapping rows and columns of the argument
15330   // matrix type.
15331   QualType ResultType = Context.getConstantMatrixType(
15332       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15333 
15334   // Change the return type to the type of the returned matrix.
15335   TheCall->setType(ResultType);
15336 
15337   // Update call argument to use the possibly converted matrix argument.
15338   TheCall->setArg(0, Matrix);
15339   return CallResult;
15340 }
15341 
15342 // Get and verify the matrix dimensions.
15343 static llvm::Optional<unsigned>
15344 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15345   llvm::APSInt Value(64);
15346   SourceLocation ErrorPos;
15347   if (!Expr->isIntegerConstantExpr(Value, S.Context, &ErrorPos)) {
15348     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15349         << Name;
15350     return {};
15351   }
15352   uint64_t Dim = Value.getZExtValue();
15353   if (!ConstantMatrixType::isDimensionValid(Dim)) {
15354     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15355         << Name << ConstantMatrixType::getMaxElementsPerDimension();
15356     return {};
15357   }
15358   return Dim;
15359 }
15360 
15361 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15362                                                   ExprResult CallResult) {
15363   if (!getLangOpts().MatrixTypes) {
15364     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15365     return ExprError();
15366   }
15367 
15368   if (checkArgCount(*this, TheCall, 4))
15369     return ExprError();
15370 
15371   unsigned PtrArgIdx = 0;
15372   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15373   Expr *RowsExpr = TheCall->getArg(1);
15374   Expr *ColumnsExpr = TheCall->getArg(2);
15375   Expr *StrideExpr = TheCall->getArg(3);
15376 
15377   bool ArgError = false;
15378 
15379   // Check pointer argument.
15380   {
15381     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15382     if (PtrConv.isInvalid())
15383       return PtrConv;
15384     PtrExpr = PtrConv.get();
15385     TheCall->setArg(0, PtrExpr);
15386     if (PtrExpr->isTypeDependent()) {
15387       TheCall->setType(Context.DependentTy);
15388       return TheCall;
15389     }
15390   }
15391 
15392   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15393   QualType ElementTy;
15394   if (!PtrTy) {
15395     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15396         << PtrArgIdx + 1;
15397     ArgError = true;
15398   } else {
15399     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15400 
15401     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15402       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15403           << PtrArgIdx + 1;
15404       ArgError = true;
15405     }
15406   }
15407 
15408   // Apply default Lvalue conversions and convert the expression to size_t.
15409   auto ApplyArgumentConversions = [this](Expr *E) {
15410     ExprResult Conv = DefaultLvalueConversion(E);
15411     if (Conv.isInvalid())
15412       return Conv;
15413 
15414     return tryConvertExprToType(Conv.get(), Context.getSizeType());
15415   };
15416 
15417   // Apply conversion to row and column expressions.
15418   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15419   if (!RowsConv.isInvalid()) {
15420     RowsExpr = RowsConv.get();
15421     TheCall->setArg(1, RowsExpr);
15422   } else
15423     RowsExpr = nullptr;
15424 
15425   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
15426   if (!ColumnsConv.isInvalid()) {
15427     ColumnsExpr = ColumnsConv.get();
15428     TheCall->setArg(2, ColumnsExpr);
15429   } else
15430     ColumnsExpr = nullptr;
15431 
15432   // If any any part of the result matrix type is still pending, just use
15433   // Context.DependentTy, until all parts are resolved.
15434   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
15435       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
15436     TheCall->setType(Context.DependentTy);
15437     return CallResult;
15438   }
15439 
15440   // Check row and column dimenions.
15441   llvm::Optional<unsigned> MaybeRows;
15442   if (RowsExpr)
15443     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
15444 
15445   llvm::Optional<unsigned> MaybeColumns;
15446   if (ColumnsExpr)
15447     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
15448 
15449   // Check stride argument.
15450   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
15451   if (StrideConv.isInvalid())
15452     return ExprError();
15453   StrideExpr = StrideConv.get();
15454   TheCall->setArg(3, StrideExpr);
15455 
15456   llvm::APSInt Value(64);
15457   if (MaybeRows && StrideExpr->isIntegerConstantExpr(Value, Context)) {
15458     uint64_t Stride = Value.getZExtValue();
15459     if (Stride < *MaybeRows) {
15460       Diag(StrideExpr->getBeginLoc(),
15461            diag::err_builtin_matrix_stride_too_small);
15462       ArgError = true;
15463     }
15464   }
15465 
15466   if (ArgError || !MaybeRows || !MaybeColumns)
15467     return ExprError();
15468 
15469   TheCall->setType(
15470       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
15471   return CallResult;
15472 }
15473 
15474 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
15475                                                    ExprResult CallResult) {
15476   if (checkArgCount(*this, TheCall, 3))
15477     return ExprError();
15478 
15479   unsigned PtrArgIdx = 1;
15480   Expr *MatrixExpr = TheCall->getArg(0);
15481   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15482   Expr *StrideExpr = TheCall->getArg(2);
15483 
15484   bool ArgError = false;
15485 
15486   {
15487     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
15488     if (MatrixConv.isInvalid())
15489       return MatrixConv;
15490     MatrixExpr = MatrixConv.get();
15491     TheCall->setArg(0, MatrixExpr);
15492   }
15493   if (MatrixExpr->isTypeDependent()) {
15494     TheCall->setType(Context.DependentTy);
15495     return TheCall;
15496   }
15497 
15498   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
15499   if (!MatrixTy) {
15500     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
15501     ArgError = true;
15502   }
15503 
15504   {
15505     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15506     if (PtrConv.isInvalid())
15507       return PtrConv;
15508     PtrExpr = PtrConv.get();
15509     TheCall->setArg(1, PtrExpr);
15510     if (PtrExpr->isTypeDependent()) {
15511       TheCall->setType(Context.DependentTy);
15512       return TheCall;
15513     }
15514   }
15515 
15516   // Check pointer argument.
15517   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15518   if (!PtrTy) {
15519     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15520         << PtrArgIdx + 1;
15521     ArgError = true;
15522   } else {
15523     QualType ElementTy = PtrTy->getPointeeType();
15524     if (ElementTy.isConstQualified()) {
15525       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
15526       ArgError = true;
15527     }
15528     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
15529     if (MatrixTy &&
15530         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
15531       Diag(PtrExpr->getBeginLoc(),
15532            diag::err_builtin_matrix_pointer_arg_mismatch)
15533           << ElementTy << MatrixTy->getElementType();
15534       ArgError = true;
15535     }
15536   }
15537 
15538   // Apply default Lvalue conversions and convert the stride expression to
15539   // size_t.
15540   {
15541     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
15542     if (StrideConv.isInvalid())
15543       return StrideConv;
15544 
15545     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
15546     if (StrideConv.isInvalid())
15547       return StrideConv;
15548     StrideExpr = StrideConv.get();
15549     TheCall->setArg(2, StrideExpr);
15550   }
15551 
15552   // Check stride argument.
15553   llvm::APSInt Value(64);
15554   if (MatrixTy && StrideExpr->isIntegerConstantExpr(Value, Context)) {
15555     uint64_t Stride = Value.getZExtValue();
15556     if (Stride < MatrixTy->getNumRows()) {
15557       Diag(StrideExpr->getBeginLoc(),
15558            diag::err_builtin_matrix_stride_too_small);
15559       ArgError = true;
15560     }
15561   }
15562 
15563   if (ArgError)
15564     return ExprError();
15565 
15566   return CallResult;
15567 }
15568