1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSwitch.h"
79 #include "llvm/ADT/Triple.h"
80 #include "llvm/Support/AtomicOrdering.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ConvertUTF.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/Locale.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/SaveAndRestore.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstddef>
93 #include <cstdint>
94 #include <functional>
95 #include <limits>
96 #include <string>
97 #include <tuple>
98 #include <utility>
99 
100 using namespace clang;
101 using namespace sema;
102 
103 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
104                                                     unsigned ByteNo) const {
105   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
106                                Context.getTargetInfo());
107 }
108 
109 /// Checks that a call expression's argument count is the desired number.
110 /// This is useful when doing custom type-checking.  Returns true on error.
111 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
112   unsigned argCount = call->getNumArgs();
113   if (argCount == desiredArgCount) return false;
114 
115   if (argCount < desiredArgCount)
116     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
117            << 0 /*function call*/ << desiredArgCount << argCount
118            << call->getSourceRange();
119 
120   // Highlight all the excess arguments.
121   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
122                     call->getArg(argCount - 1)->getEndLoc());
123 
124   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
125     << 0 /*function call*/ << desiredArgCount << argCount
126     << call->getArg(1)->getSourceRange();
127 }
128 
129 /// Check that the first argument to __builtin_annotation is an integer
130 /// and the second argument is a non-wide string literal.
131 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
132   if (checkArgCount(S, TheCall, 2))
133     return true;
134 
135   // First argument should be an integer.
136   Expr *ValArg = TheCall->getArg(0);
137   QualType Ty = ValArg->getType();
138   if (!Ty->isIntegerType()) {
139     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
140         << ValArg->getSourceRange();
141     return true;
142   }
143 
144   // Second argument should be a constant string.
145   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
146   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
147   if (!Literal || !Literal->isAscii()) {
148     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
149         << StrArg->getSourceRange();
150     return true;
151   }
152 
153   TheCall->setType(Ty);
154   return false;
155 }
156 
157 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
158   // We need at least one argument.
159   if (TheCall->getNumArgs() < 1) {
160     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
161         << 0 << 1 << TheCall->getNumArgs()
162         << TheCall->getCallee()->getSourceRange();
163     return true;
164   }
165 
166   // All arguments should be wide string literals.
167   for (Expr *Arg : TheCall->arguments()) {
168     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
169     if (!Literal || !Literal->isWide()) {
170       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
171           << Arg->getSourceRange();
172       return true;
173     }
174   }
175 
176   return false;
177 }
178 
179 /// Check that the argument to __builtin_addressof is a glvalue, and set the
180 /// result type to the corresponding pointer type.
181 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
182   if (checkArgCount(S, TheCall, 1))
183     return true;
184 
185   ExprResult Arg(TheCall->getArg(0));
186   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
187   if (ResultType.isNull())
188     return true;
189 
190   TheCall->setArg(0, Arg.get());
191   TheCall->setType(ResultType);
192   return false;
193 }
194 
195 /// Check the number of arguments and set the result type to
196 /// the argument type.
197 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
198   if (checkArgCount(S, TheCall, 1))
199     return true;
200 
201   TheCall->setType(TheCall->getArg(0)->getType());
202   return false;
203 }
204 
205 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
206 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
207 /// type (but not a function pointer) and that the alignment is a power-of-two.
208 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
209   if (checkArgCount(S, TheCall, 2))
210     return true;
211 
212   clang::Expr *Source = TheCall->getArg(0);
213   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
214 
215   auto IsValidIntegerType = [](QualType Ty) {
216     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
217   };
218   QualType SrcTy = Source->getType();
219   // We should also be able to use it with arrays (but not functions!).
220   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
221     SrcTy = S.Context.getDecayedType(SrcTy);
222   }
223   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
224       SrcTy->isFunctionPointerType()) {
225     // FIXME: this is not quite the right error message since we don't allow
226     // floating point types, or member pointers.
227     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
228         << SrcTy;
229     return true;
230   }
231 
232   clang::Expr *AlignOp = TheCall->getArg(1);
233   if (!IsValidIntegerType(AlignOp->getType())) {
234     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
235         << AlignOp->getType();
236     return true;
237   }
238   Expr::EvalResult AlignResult;
239   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
240   // We can't check validity of alignment if it is type dependent.
241   if (!AlignOp->isInstantiationDependent() &&
242       AlignOp->EvaluateAsInt(AlignResult, S.Context,
243                              Expr::SE_AllowSideEffects)) {
244     llvm::APSInt AlignValue = AlignResult.Val.getInt();
245     llvm::APSInt MaxValue(
246         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
247     if (AlignValue < 1) {
248       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
249       return true;
250     }
251     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
252       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
253           << MaxValue.toString(10);
254       return true;
255     }
256     if (!AlignValue.isPowerOf2()) {
257       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
258       return true;
259     }
260     if (AlignValue == 1) {
261       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
262           << IsBooleanAlignBuiltin;
263     }
264   }
265 
266   ExprResult SrcArg = S.PerformCopyInitialization(
267       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
268       SourceLocation(), Source);
269   if (SrcArg.isInvalid())
270     return true;
271   TheCall->setArg(0, SrcArg.get());
272   ExprResult AlignArg =
273       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
274                                       S.Context, AlignOp->getType(), false),
275                                   SourceLocation(), AlignOp);
276   if (AlignArg.isInvalid())
277     return true;
278   TheCall->setArg(1, AlignArg.get());
279   // For align_up/align_down, the return type is the same as the (potentially
280   // decayed) argument type including qualifiers. For is_aligned(), the result
281   // is always bool.
282   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
283   return false;
284 }
285 
286 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
287                                 unsigned BuiltinID) {
288   if (checkArgCount(S, TheCall, 3))
289     return true;
290 
291   // First two arguments should be integers.
292   for (unsigned I = 0; I < 2; ++I) {
293     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
294     if (Arg.isInvalid()) return true;
295     TheCall->setArg(I, Arg.get());
296 
297     QualType Ty = Arg.get()->getType();
298     if (!Ty->isIntegerType()) {
299       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
300           << Ty << Arg.get()->getSourceRange();
301       return true;
302     }
303   }
304 
305   // Third argument should be a pointer to a non-const integer.
306   // IRGen correctly handles volatile, restrict, and address spaces, and
307   // the other qualifiers aren't possible.
308   {
309     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
310     if (Arg.isInvalid()) return true;
311     TheCall->setArg(2, Arg.get());
312 
313     QualType Ty = Arg.get()->getType();
314     const auto *PtrTy = Ty->getAs<PointerType>();
315     if (!PtrTy ||
316         !PtrTy->getPointeeType()->isIntegerType() ||
317         PtrTy->getPointeeType().isConstQualified()) {
318       S.Diag(Arg.get()->getBeginLoc(),
319              diag::err_overflow_builtin_must_be_ptr_int)
320         << Ty << Arg.get()->getSourceRange();
321       return true;
322     }
323   }
324 
325   // Disallow signed ExtIntType args larger than 128 bits to mul function until
326   // we improve backend support.
327   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
328     for (unsigned I = 0; I < 3; ++I) {
329       const auto Arg = TheCall->getArg(I);
330       // Third argument will be a pointer.
331       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
332       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
333           S.getASTContext().getIntWidth(Ty) > 128)
334         return S.Diag(Arg->getBeginLoc(),
335                       diag::err_overflow_builtin_ext_int_max_size)
336                << 128;
337     }
338   }
339 
340   return false;
341 }
342 
343 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
344   if (checkArgCount(S, BuiltinCall, 2))
345     return true;
346 
347   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
348   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
349   Expr *Call = BuiltinCall->getArg(0);
350   Expr *Chain = BuiltinCall->getArg(1);
351 
352   if (Call->getStmtClass() != Stmt::CallExprClass) {
353     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
354         << Call->getSourceRange();
355     return true;
356   }
357 
358   auto CE = cast<CallExpr>(Call);
359   if (CE->getCallee()->getType()->isBlockPointerType()) {
360     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
361         << Call->getSourceRange();
362     return true;
363   }
364 
365   const Decl *TargetDecl = CE->getCalleeDecl();
366   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
367     if (FD->getBuiltinID()) {
368       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
369           << Call->getSourceRange();
370       return true;
371     }
372 
373   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
374     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
375         << Call->getSourceRange();
376     return true;
377   }
378 
379   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
380   if (ChainResult.isInvalid())
381     return true;
382   if (!ChainResult.get()->getType()->isPointerType()) {
383     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
384         << Chain->getSourceRange();
385     return true;
386   }
387 
388   QualType ReturnTy = CE->getCallReturnType(S.Context);
389   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
390   QualType BuiltinTy = S.Context.getFunctionType(
391       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
392   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
393 
394   Builtin =
395       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
396 
397   BuiltinCall->setType(CE->getType());
398   BuiltinCall->setValueKind(CE->getValueKind());
399   BuiltinCall->setObjectKind(CE->getObjectKind());
400   BuiltinCall->setCallee(Builtin);
401   BuiltinCall->setArg(1, ChainResult.get());
402 
403   return false;
404 }
405 
406 namespace {
407 
408 class EstimateSizeFormatHandler
409     : public analyze_format_string::FormatStringHandler {
410   size_t Size;
411 
412 public:
413   EstimateSizeFormatHandler(StringRef Format)
414       : Size(std::min(Format.find(0), Format.size()) +
415              1 /* null byte always written by sprintf */) {}
416 
417   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
418                              const char *, unsigned SpecifierLen) override {
419 
420     const size_t FieldWidth = computeFieldWidth(FS);
421     const size_t Precision = computePrecision(FS);
422 
423     // The actual format.
424     switch (FS.getConversionSpecifier().getKind()) {
425     // Just a char.
426     case analyze_format_string::ConversionSpecifier::cArg:
427     case analyze_format_string::ConversionSpecifier::CArg:
428       Size += std::max(FieldWidth, (size_t)1);
429       break;
430     // Just an integer.
431     case analyze_format_string::ConversionSpecifier::dArg:
432     case analyze_format_string::ConversionSpecifier::DArg:
433     case analyze_format_string::ConversionSpecifier::iArg:
434     case analyze_format_string::ConversionSpecifier::oArg:
435     case analyze_format_string::ConversionSpecifier::OArg:
436     case analyze_format_string::ConversionSpecifier::uArg:
437     case analyze_format_string::ConversionSpecifier::UArg:
438     case analyze_format_string::ConversionSpecifier::xArg:
439     case analyze_format_string::ConversionSpecifier::XArg:
440       Size += std::max(FieldWidth, Precision);
441       break;
442 
443     // %g style conversion switches between %f or %e style dynamically.
444     // %f always takes less space, so default to it.
445     case analyze_format_string::ConversionSpecifier::gArg:
446     case analyze_format_string::ConversionSpecifier::GArg:
447 
448     // Floating point number in the form '[+]ddd.ddd'.
449     case analyze_format_string::ConversionSpecifier::fArg:
450     case analyze_format_string::ConversionSpecifier::FArg:
451       Size += std::max(FieldWidth, 1 /* integer part */ +
452                                        (Precision ? 1 + Precision
453                                                   : 0) /* period + decimal */);
454       break;
455 
456     // Floating point number in the form '[-]d.ddde[+-]dd'.
457     case analyze_format_string::ConversionSpecifier::eArg:
458     case analyze_format_string::ConversionSpecifier::EArg:
459       Size +=
460           std::max(FieldWidth,
461                    1 /* integer part */ +
462                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
463                        1 /* e or E letter */ + 2 /* exponent */);
464       break;
465 
466     // Floating point number in the form '[-]0xh.hhhhp±dd'.
467     case analyze_format_string::ConversionSpecifier::aArg:
468     case analyze_format_string::ConversionSpecifier::AArg:
469       Size +=
470           std::max(FieldWidth,
471                    2 /* 0x */ + 1 /* integer part */ +
472                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
473                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
474       break;
475 
476     // Just a string.
477     case analyze_format_string::ConversionSpecifier::sArg:
478     case analyze_format_string::ConversionSpecifier::SArg:
479       Size += FieldWidth;
480       break;
481 
482     // Just a pointer in the form '0xddd'.
483     case analyze_format_string::ConversionSpecifier::pArg:
484       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
485       break;
486 
487     // A plain percent.
488     case analyze_format_string::ConversionSpecifier::PercentArg:
489       Size += 1;
490       break;
491 
492     default:
493       break;
494     }
495 
496     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
497 
498     if (FS.hasAlternativeForm()) {
499       switch (FS.getConversionSpecifier().getKind()) {
500       default:
501         break;
502       // Force a leading '0'.
503       case analyze_format_string::ConversionSpecifier::oArg:
504         Size += 1;
505         break;
506       // Force a leading '0x'.
507       case analyze_format_string::ConversionSpecifier::xArg:
508       case analyze_format_string::ConversionSpecifier::XArg:
509         Size += 2;
510         break;
511       // Force a period '.' before decimal, even if precision is 0.
512       case analyze_format_string::ConversionSpecifier::aArg:
513       case analyze_format_string::ConversionSpecifier::AArg:
514       case analyze_format_string::ConversionSpecifier::eArg:
515       case analyze_format_string::ConversionSpecifier::EArg:
516       case analyze_format_string::ConversionSpecifier::fArg:
517       case analyze_format_string::ConversionSpecifier::FArg:
518       case analyze_format_string::ConversionSpecifier::gArg:
519       case analyze_format_string::ConversionSpecifier::GArg:
520         Size += (Precision ? 0 : 1);
521         break;
522       }
523     }
524     assert(SpecifierLen <= Size && "no underflow");
525     Size -= SpecifierLen;
526     return true;
527   }
528 
529   size_t getSizeLowerBound() const { return Size; }
530 
531 private:
532   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
533     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
534     size_t FieldWidth = 0;
535     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
536       FieldWidth = FW.getConstantAmount();
537     return FieldWidth;
538   }
539 
540   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
541     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
542     size_t Precision = 0;
543 
544     // See man 3 printf for default precision value based on the specifier.
545     switch (FW.getHowSpecified()) {
546     case analyze_format_string::OptionalAmount::NotSpecified:
547       switch (FS.getConversionSpecifier().getKind()) {
548       default:
549         break;
550       case analyze_format_string::ConversionSpecifier::dArg: // %d
551       case analyze_format_string::ConversionSpecifier::DArg: // %D
552       case analyze_format_string::ConversionSpecifier::iArg: // %i
553         Precision = 1;
554         break;
555       case analyze_format_string::ConversionSpecifier::oArg: // %d
556       case analyze_format_string::ConversionSpecifier::OArg: // %D
557       case analyze_format_string::ConversionSpecifier::uArg: // %d
558       case analyze_format_string::ConversionSpecifier::UArg: // %D
559       case analyze_format_string::ConversionSpecifier::xArg: // %d
560       case analyze_format_string::ConversionSpecifier::XArg: // %D
561         Precision = 1;
562         break;
563       case analyze_format_string::ConversionSpecifier::fArg: // %f
564       case analyze_format_string::ConversionSpecifier::FArg: // %F
565       case analyze_format_string::ConversionSpecifier::eArg: // %e
566       case analyze_format_string::ConversionSpecifier::EArg: // %E
567       case analyze_format_string::ConversionSpecifier::gArg: // %g
568       case analyze_format_string::ConversionSpecifier::GArg: // %G
569         Precision = 6;
570         break;
571       case analyze_format_string::ConversionSpecifier::pArg: // %d
572         Precision = 1;
573         break;
574       }
575       break;
576     case analyze_format_string::OptionalAmount::Constant:
577       Precision = FW.getConstantAmount();
578       break;
579     default:
580       break;
581     }
582     return Precision;
583   }
584 };
585 
586 } // namespace
587 
588 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
589 /// __builtin_*_chk function, then use the object size argument specified in the
590 /// source. Otherwise, infer the object size using __builtin_object_size.
591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
592                                                CallExpr *TheCall) {
593   // FIXME: There are some more useful checks we could be doing here:
594   //  - Evaluate strlen of strcpy arguments, use as object size.
595 
596   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
597       isConstantEvaluated())
598     return;
599 
600   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
601   if (!BuiltinID)
602     return;
603 
604   const TargetInfo &TI = getASTContext().getTargetInfo();
605   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
606 
607   unsigned DiagID = 0;
608   bool IsChkVariant = false;
609   Optional<llvm::APSInt> UsedSize;
610   unsigned SizeIndex, ObjectIndex;
611   switch (BuiltinID) {
612   default:
613     return;
614   case Builtin::BIsprintf:
615   case Builtin::BI__builtin___sprintf_chk: {
616     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
617     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
618 
619     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
620 
621       if (!Format->isAscii() && !Format->isUTF8())
622         return;
623 
624       StringRef FormatStrRef = Format->getString();
625       EstimateSizeFormatHandler H(FormatStrRef);
626       const char *FormatBytes = FormatStrRef.data();
627       const ConstantArrayType *T =
628           Context.getAsConstantArrayType(Format->getType());
629       assert(T && "String literal not of constant array type!");
630       size_t TypeSize = T->getSize().getZExtValue();
631 
632       // In case there's a null byte somewhere.
633       size_t StrLen =
634           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
635       if (!analyze_format_string::ParsePrintfString(
636               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
637               Context.getTargetInfo(), false)) {
638         DiagID = diag::warn_fortify_source_format_overflow;
639         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
640                        .extOrTrunc(SizeTypeWidth);
641         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
642           IsChkVariant = true;
643           ObjectIndex = 2;
644         } else {
645           IsChkVariant = false;
646           ObjectIndex = 0;
647         }
648         break;
649       }
650     }
651     return;
652   }
653   case Builtin::BI__builtin___memcpy_chk:
654   case Builtin::BI__builtin___memmove_chk:
655   case Builtin::BI__builtin___memset_chk:
656   case Builtin::BI__builtin___strlcat_chk:
657   case Builtin::BI__builtin___strlcpy_chk:
658   case Builtin::BI__builtin___strncat_chk:
659   case Builtin::BI__builtin___strncpy_chk:
660   case Builtin::BI__builtin___stpncpy_chk:
661   case Builtin::BI__builtin___memccpy_chk:
662   case Builtin::BI__builtin___mempcpy_chk: {
663     DiagID = diag::warn_builtin_chk_overflow;
664     IsChkVariant = true;
665     SizeIndex = TheCall->getNumArgs() - 2;
666     ObjectIndex = TheCall->getNumArgs() - 1;
667     break;
668   }
669 
670   case Builtin::BI__builtin___snprintf_chk:
671   case Builtin::BI__builtin___vsnprintf_chk: {
672     DiagID = diag::warn_builtin_chk_overflow;
673     IsChkVariant = true;
674     SizeIndex = 1;
675     ObjectIndex = 3;
676     break;
677   }
678 
679   case Builtin::BIstrncat:
680   case Builtin::BI__builtin_strncat:
681   case Builtin::BIstrncpy:
682   case Builtin::BI__builtin_strncpy:
683   case Builtin::BIstpncpy:
684   case Builtin::BI__builtin_stpncpy: {
685     // Whether these functions overflow depends on the runtime strlen of the
686     // string, not just the buffer size, so emitting the "always overflow"
687     // diagnostic isn't quite right. We should still diagnose passing a buffer
688     // size larger than the destination buffer though; this is a runtime abort
689     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
690     DiagID = diag::warn_fortify_source_size_mismatch;
691     SizeIndex = TheCall->getNumArgs() - 1;
692     ObjectIndex = 0;
693     break;
694   }
695 
696   case Builtin::BImemcpy:
697   case Builtin::BI__builtin_memcpy:
698   case Builtin::BImemmove:
699   case Builtin::BI__builtin_memmove:
700   case Builtin::BImemset:
701   case Builtin::BI__builtin_memset:
702   case Builtin::BImempcpy:
703   case Builtin::BI__builtin_mempcpy: {
704     DiagID = diag::warn_fortify_source_overflow;
705     SizeIndex = TheCall->getNumArgs() - 1;
706     ObjectIndex = 0;
707     break;
708   }
709   case Builtin::BIsnprintf:
710   case Builtin::BI__builtin_snprintf:
711   case Builtin::BIvsnprintf:
712   case Builtin::BI__builtin_vsnprintf: {
713     DiagID = diag::warn_fortify_source_size_mismatch;
714     SizeIndex = 1;
715     ObjectIndex = 0;
716     break;
717   }
718   }
719 
720   llvm::APSInt ObjectSize;
721   // For __builtin___*_chk, the object size is explicitly provided by the caller
722   // (usually using __builtin_object_size). Use that value to check this call.
723   if (IsChkVariant) {
724     Expr::EvalResult Result;
725     Expr *SizeArg = TheCall->getArg(ObjectIndex);
726     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
727       return;
728     ObjectSize = Result.Val.getInt();
729 
730   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
731   } else {
732     // If the parameter has a pass_object_size attribute, then we should use its
733     // (potentially) more strict checking mode. Otherwise, conservatively assume
734     // type 0.
735     int BOSType = 0;
736     if (const auto *POS =
737             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
738       BOSType = POS->getType();
739 
740     Expr *ObjArg = TheCall->getArg(ObjectIndex);
741     uint64_t Result;
742     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
743       return;
744     // Get the object size in the target's size_t width.
745     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
746   }
747 
748   // Evaluate the number of bytes of the object that this call will use.
749   if (!UsedSize) {
750     Expr::EvalResult Result;
751     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
752     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
753       return;
754     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
755   }
756 
757   if (UsedSize.getValue().ule(ObjectSize))
758     return;
759 
760   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
761   // Skim off the details of whichever builtin was called to produce a better
762   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
763   if (IsChkVariant) {
764     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
765     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
766   } else if (FunctionName.startswith("__builtin_")) {
767     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
768   }
769 
770   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
771                       PDiag(DiagID)
772                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
773                           << UsedSize.getValue().toString(/*Radix=*/10));
774 }
775 
776 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
777                                      Scope::ScopeFlags NeededScopeFlags,
778                                      unsigned DiagID) {
779   // Scopes aren't available during instantiation. Fortunately, builtin
780   // functions cannot be template args so they cannot be formed through template
781   // instantiation. Therefore checking once during the parse is sufficient.
782   if (SemaRef.inTemplateInstantiation())
783     return false;
784 
785   Scope *S = SemaRef.getCurScope();
786   while (S && !S->isSEHExceptScope())
787     S = S->getParent();
788   if (!S || !(S->getFlags() & NeededScopeFlags)) {
789     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
790     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
791         << DRE->getDecl()->getIdentifier();
792     return true;
793   }
794 
795   return false;
796 }
797 
798 static inline bool isBlockPointer(Expr *Arg) {
799   return Arg->getType()->isBlockPointerType();
800 }
801 
802 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
803 /// void*, which is a requirement of device side enqueue.
804 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
805   const BlockPointerType *BPT =
806       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
807   ArrayRef<QualType> Params =
808       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
809   unsigned ArgCounter = 0;
810   bool IllegalParams = false;
811   // Iterate through the block parameters until either one is found that is not
812   // a local void*, or the block is valid.
813   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
814        I != E; ++I, ++ArgCounter) {
815     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
816         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
817             LangAS::opencl_local) {
818       // Get the location of the error. If a block literal has been passed
819       // (BlockExpr) then we can point straight to the offending argument,
820       // else we just point to the variable reference.
821       SourceLocation ErrorLoc;
822       if (isa<BlockExpr>(BlockArg)) {
823         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
824         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
825       } else if (isa<DeclRefExpr>(BlockArg)) {
826         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
827       }
828       S.Diag(ErrorLoc,
829              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
830       IllegalParams = true;
831     }
832   }
833 
834   return IllegalParams;
835 }
836 
837 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
838   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
839     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
840         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
841     return true;
842   }
843   return false;
844 }
845 
846 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
847   if (checkArgCount(S, TheCall, 2))
848     return true;
849 
850   if (checkOpenCLSubgroupExt(S, TheCall))
851     return true;
852 
853   // First argument is an ndrange_t type.
854   Expr *NDRangeArg = TheCall->getArg(0);
855   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
856     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
857         << TheCall->getDirectCallee() << "'ndrange_t'";
858     return true;
859   }
860 
861   Expr *BlockArg = TheCall->getArg(1);
862   if (!isBlockPointer(BlockArg)) {
863     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
864         << TheCall->getDirectCallee() << "block";
865     return true;
866   }
867   return checkOpenCLBlockArgs(S, BlockArg);
868 }
869 
870 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
871 /// get_kernel_work_group_size
872 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
873 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
874   if (checkArgCount(S, TheCall, 1))
875     return true;
876 
877   Expr *BlockArg = TheCall->getArg(0);
878   if (!isBlockPointer(BlockArg)) {
879     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
880         << TheCall->getDirectCallee() << "block";
881     return true;
882   }
883   return checkOpenCLBlockArgs(S, BlockArg);
884 }
885 
886 /// Diagnose integer type and any valid implicit conversion to it.
887 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
888                                       const QualType &IntType);
889 
890 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
891                                             unsigned Start, unsigned End) {
892   bool IllegalParams = false;
893   for (unsigned I = Start; I <= End; ++I)
894     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
895                                               S.Context.getSizeType());
896   return IllegalParams;
897 }
898 
899 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
900 /// 'local void*' parameter of passed block.
901 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
902                                            Expr *BlockArg,
903                                            unsigned NumNonVarArgs) {
904   const BlockPointerType *BPT =
905       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
906   unsigned NumBlockParams =
907       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
908   unsigned TotalNumArgs = TheCall->getNumArgs();
909 
910   // For each argument passed to the block, a corresponding uint needs to
911   // be passed to describe the size of the local memory.
912   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
913     S.Diag(TheCall->getBeginLoc(),
914            diag::err_opencl_enqueue_kernel_local_size_args);
915     return true;
916   }
917 
918   // Check that the sizes of the local memory are specified by integers.
919   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
920                                          TotalNumArgs - 1);
921 }
922 
923 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
924 /// overload formats specified in Table 6.13.17.1.
925 /// int enqueue_kernel(queue_t queue,
926 ///                    kernel_enqueue_flags_t flags,
927 ///                    const ndrange_t ndrange,
928 ///                    void (^block)(void))
929 /// int enqueue_kernel(queue_t queue,
930 ///                    kernel_enqueue_flags_t flags,
931 ///                    const ndrange_t ndrange,
932 ///                    uint num_events_in_wait_list,
933 ///                    clk_event_t *event_wait_list,
934 ///                    clk_event_t *event_ret,
935 ///                    void (^block)(void))
936 /// int enqueue_kernel(queue_t queue,
937 ///                    kernel_enqueue_flags_t flags,
938 ///                    const ndrange_t ndrange,
939 ///                    void (^block)(local void*, ...),
940 ///                    uint size0, ...)
941 /// int enqueue_kernel(queue_t queue,
942 ///                    kernel_enqueue_flags_t flags,
943 ///                    const ndrange_t ndrange,
944 ///                    uint num_events_in_wait_list,
945 ///                    clk_event_t *event_wait_list,
946 ///                    clk_event_t *event_ret,
947 ///                    void (^block)(local void*, ...),
948 ///                    uint size0, ...)
949 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
950   unsigned NumArgs = TheCall->getNumArgs();
951 
952   if (NumArgs < 4) {
953     S.Diag(TheCall->getBeginLoc(),
954            diag::err_typecheck_call_too_few_args_at_least)
955         << 0 << 4 << NumArgs;
956     return true;
957   }
958 
959   Expr *Arg0 = TheCall->getArg(0);
960   Expr *Arg1 = TheCall->getArg(1);
961   Expr *Arg2 = TheCall->getArg(2);
962   Expr *Arg3 = TheCall->getArg(3);
963 
964   // First argument always needs to be a queue_t type.
965   if (!Arg0->getType()->isQueueT()) {
966     S.Diag(TheCall->getArg(0)->getBeginLoc(),
967            diag::err_opencl_builtin_expected_type)
968         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
969     return true;
970   }
971 
972   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
973   if (!Arg1->getType()->isIntegerType()) {
974     S.Diag(TheCall->getArg(1)->getBeginLoc(),
975            diag::err_opencl_builtin_expected_type)
976         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
977     return true;
978   }
979 
980   // Third argument is always an ndrange_t type.
981   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
982     S.Diag(TheCall->getArg(2)->getBeginLoc(),
983            diag::err_opencl_builtin_expected_type)
984         << TheCall->getDirectCallee() << "'ndrange_t'";
985     return true;
986   }
987 
988   // With four arguments, there is only one form that the function could be
989   // called in: no events and no variable arguments.
990   if (NumArgs == 4) {
991     // check that the last argument is the right block type.
992     if (!isBlockPointer(Arg3)) {
993       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
994           << TheCall->getDirectCallee() << "block";
995       return true;
996     }
997     // we have a block type, check the prototype
998     const BlockPointerType *BPT =
999         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1000     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1001       S.Diag(Arg3->getBeginLoc(),
1002              diag::err_opencl_enqueue_kernel_blocks_no_args);
1003       return true;
1004     }
1005     return false;
1006   }
1007   // we can have block + varargs.
1008   if (isBlockPointer(Arg3))
1009     return (checkOpenCLBlockArgs(S, Arg3) ||
1010             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1011   // last two cases with either exactly 7 args or 7 args and varargs.
1012   if (NumArgs >= 7) {
1013     // check common block argument.
1014     Expr *Arg6 = TheCall->getArg(6);
1015     if (!isBlockPointer(Arg6)) {
1016       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1017           << TheCall->getDirectCallee() << "block";
1018       return true;
1019     }
1020     if (checkOpenCLBlockArgs(S, Arg6))
1021       return true;
1022 
1023     // Forth argument has to be any integer type.
1024     if (!Arg3->getType()->isIntegerType()) {
1025       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1026              diag::err_opencl_builtin_expected_type)
1027           << TheCall->getDirectCallee() << "integer";
1028       return true;
1029     }
1030     // check remaining common arguments.
1031     Expr *Arg4 = TheCall->getArg(4);
1032     Expr *Arg5 = TheCall->getArg(5);
1033 
1034     // Fifth argument is always passed as a pointer to clk_event_t.
1035     if (!Arg4->isNullPointerConstant(S.Context,
1036                                      Expr::NPC_ValueDependentIsNotNull) &&
1037         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1038       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1039              diag::err_opencl_builtin_expected_type)
1040           << TheCall->getDirectCallee()
1041           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1042       return true;
1043     }
1044 
1045     // Sixth argument is always passed as a pointer to clk_event_t.
1046     if (!Arg5->isNullPointerConstant(S.Context,
1047                                      Expr::NPC_ValueDependentIsNotNull) &&
1048         !(Arg5->getType()->isPointerType() &&
1049           Arg5->getType()->getPointeeType()->isClkEventT())) {
1050       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1051              diag::err_opencl_builtin_expected_type)
1052           << TheCall->getDirectCallee()
1053           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1054       return true;
1055     }
1056 
1057     if (NumArgs == 7)
1058       return false;
1059 
1060     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1061   }
1062 
1063   // None of the specific case has been detected, give generic error
1064   S.Diag(TheCall->getBeginLoc(),
1065          diag::err_opencl_enqueue_kernel_incorrect_args);
1066   return true;
1067 }
1068 
1069 /// Returns OpenCL access qual.
1070 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1071     return D->getAttr<OpenCLAccessAttr>();
1072 }
1073 
1074 /// Returns true if pipe element type is different from the pointer.
1075 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1076   const Expr *Arg0 = Call->getArg(0);
1077   // First argument type should always be pipe.
1078   if (!Arg0->getType()->isPipeType()) {
1079     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1080         << Call->getDirectCallee() << Arg0->getSourceRange();
1081     return true;
1082   }
1083   OpenCLAccessAttr *AccessQual =
1084       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1085   // Validates the access qualifier is compatible with the call.
1086   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1087   // read_only and write_only, and assumed to be read_only if no qualifier is
1088   // specified.
1089   switch (Call->getDirectCallee()->getBuiltinID()) {
1090   case Builtin::BIread_pipe:
1091   case Builtin::BIreserve_read_pipe:
1092   case Builtin::BIcommit_read_pipe:
1093   case Builtin::BIwork_group_reserve_read_pipe:
1094   case Builtin::BIsub_group_reserve_read_pipe:
1095   case Builtin::BIwork_group_commit_read_pipe:
1096   case Builtin::BIsub_group_commit_read_pipe:
1097     if (!(!AccessQual || AccessQual->isReadOnly())) {
1098       S.Diag(Arg0->getBeginLoc(),
1099              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1100           << "read_only" << Arg0->getSourceRange();
1101       return true;
1102     }
1103     break;
1104   case Builtin::BIwrite_pipe:
1105   case Builtin::BIreserve_write_pipe:
1106   case Builtin::BIcommit_write_pipe:
1107   case Builtin::BIwork_group_reserve_write_pipe:
1108   case Builtin::BIsub_group_reserve_write_pipe:
1109   case Builtin::BIwork_group_commit_write_pipe:
1110   case Builtin::BIsub_group_commit_write_pipe:
1111     if (!(AccessQual && AccessQual->isWriteOnly())) {
1112       S.Diag(Arg0->getBeginLoc(),
1113              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1114           << "write_only" << Arg0->getSourceRange();
1115       return true;
1116     }
1117     break;
1118   default:
1119     break;
1120   }
1121   return false;
1122 }
1123 
1124 /// Returns true if pipe element type is different from the pointer.
1125 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1126   const Expr *Arg0 = Call->getArg(0);
1127   const Expr *ArgIdx = Call->getArg(Idx);
1128   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1129   const QualType EltTy = PipeTy->getElementType();
1130   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1131   // The Idx argument should be a pointer and the type of the pointer and
1132   // the type of pipe element should also be the same.
1133   if (!ArgTy ||
1134       !S.Context.hasSameType(
1135           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1136     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1137         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1138         << ArgIdx->getType() << ArgIdx->getSourceRange();
1139     return true;
1140   }
1141   return false;
1142 }
1143 
1144 // Performs semantic analysis for the read/write_pipe call.
1145 // \param S Reference to the semantic analyzer.
1146 // \param Call A pointer to the builtin call.
1147 // \return True if a semantic error has been found, false otherwise.
1148 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1149   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1150   // functions have two forms.
1151   switch (Call->getNumArgs()) {
1152   case 2:
1153     if (checkOpenCLPipeArg(S, Call))
1154       return true;
1155     // The call with 2 arguments should be
1156     // read/write_pipe(pipe T, T*).
1157     // Check packet type T.
1158     if (checkOpenCLPipePacketType(S, Call, 1))
1159       return true;
1160     break;
1161 
1162   case 4: {
1163     if (checkOpenCLPipeArg(S, Call))
1164       return true;
1165     // The call with 4 arguments should be
1166     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1167     // Check reserve_id_t.
1168     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1169       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1170           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1171           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1172       return true;
1173     }
1174 
1175     // Check the index.
1176     const Expr *Arg2 = Call->getArg(2);
1177     if (!Arg2->getType()->isIntegerType() &&
1178         !Arg2->getType()->isUnsignedIntegerType()) {
1179       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1180           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1181           << Arg2->getType() << Arg2->getSourceRange();
1182       return true;
1183     }
1184 
1185     // Check packet type T.
1186     if (checkOpenCLPipePacketType(S, Call, 3))
1187       return true;
1188   } break;
1189   default:
1190     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1191         << Call->getDirectCallee() << Call->getSourceRange();
1192     return true;
1193   }
1194 
1195   return false;
1196 }
1197 
1198 // Performs a semantic analysis on the {work_group_/sub_group_
1199 //        /_}reserve_{read/write}_pipe
1200 // \param S Reference to the semantic analyzer.
1201 // \param Call The call to the builtin function to be analyzed.
1202 // \return True if a semantic error was found, false otherwise.
1203 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1204   if (checkArgCount(S, Call, 2))
1205     return true;
1206 
1207   if (checkOpenCLPipeArg(S, Call))
1208     return true;
1209 
1210   // Check the reserve size.
1211   if (!Call->getArg(1)->getType()->isIntegerType() &&
1212       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1213     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1214         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1215         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1216     return true;
1217   }
1218 
1219   // Since return type of reserve_read/write_pipe built-in function is
1220   // reserve_id_t, which is not defined in the builtin def file , we used int
1221   // as return type and need to override the return type of these functions.
1222   Call->setType(S.Context.OCLReserveIDTy);
1223 
1224   return false;
1225 }
1226 
1227 // Performs a semantic analysis on {work_group_/sub_group_
1228 //        /_}commit_{read/write}_pipe
1229 // \param S Reference to the semantic analyzer.
1230 // \param Call The call to the builtin function to be analyzed.
1231 // \return True if a semantic error was found, false otherwise.
1232 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1233   if (checkArgCount(S, Call, 2))
1234     return true;
1235 
1236   if (checkOpenCLPipeArg(S, Call))
1237     return true;
1238 
1239   // Check reserve_id_t.
1240   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1241     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1242         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1243         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1244     return true;
1245   }
1246 
1247   return false;
1248 }
1249 
1250 // Performs a semantic analysis on the call to built-in Pipe
1251 //        Query Functions.
1252 // \param S Reference to the semantic analyzer.
1253 // \param Call The call to the builtin function to be analyzed.
1254 // \return True if a semantic error was found, false otherwise.
1255 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1256   if (checkArgCount(S, Call, 1))
1257     return true;
1258 
1259   if (!Call->getArg(0)->getType()->isPipeType()) {
1260     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1261         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1262     return true;
1263   }
1264 
1265   return false;
1266 }
1267 
1268 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1269 // Performs semantic analysis for the to_global/local/private call.
1270 // \param S Reference to the semantic analyzer.
1271 // \param BuiltinID ID of the builtin function.
1272 // \param Call A pointer to the builtin call.
1273 // \return True if a semantic error has been found, false otherwise.
1274 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1275                                     CallExpr *Call) {
1276   if (Call->getNumArgs() != 1) {
1277     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
1278         << Call->getDirectCallee() << Call->getSourceRange();
1279     return true;
1280   }
1281 
1282   auto RT = Call->getArg(0)->getType();
1283   if (!RT->isPointerType() || RT->getPointeeType()
1284       .getAddressSpace() == LangAS::opencl_constant) {
1285     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1286         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1287     return true;
1288   }
1289 
1290   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1291     S.Diag(Call->getArg(0)->getBeginLoc(),
1292            diag::warn_opencl_generic_address_space_arg)
1293         << Call->getDirectCallee()->getNameInfo().getAsString()
1294         << Call->getArg(0)->getSourceRange();
1295   }
1296 
1297   RT = RT->getPointeeType();
1298   auto Qual = RT.getQualifiers();
1299   switch (BuiltinID) {
1300   case Builtin::BIto_global:
1301     Qual.setAddressSpace(LangAS::opencl_global);
1302     break;
1303   case Builtin::BIto_local:
1304     Qual.setAddressSpace(LangAS::opencl_local);
1305     break;
1306   case Builtin::BIto_private:
1307     Qual.setAddressSpace(LangAS::opencl_private);
1308     break;
1309   default:
1310     llvm_unreachable("Invalid builtin function");
1311   }
1312   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1313       RT.getUnqualifiedType(), Qual)));
1314 
1315   return false;
1316 }
1317 
1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1319   if (checkArgCount(S, TheCall, 1))
1320     return ExprError();
1321 
1322   // Compute __builtin_launder's parameter type from the argument.
1323   // The parameter type is:
1324   //  * The type of the argument if it's not an array or function type,
1325   //  Otherwise,
1326   //  * The decayed argument type.
1327   QualType ParamTy = [&]() {
1328     QualType ArgTy = TheCall->getArg(0)->getType();
1329     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1330       return S.Context.getPointerType(Ty->getElementType());
1331     if (ArgTy->isFunctionType()) {
1332       return S.Context.getPointerType(ArgTy);
1333     }
1334     return ArgTy;
1335   }();
1336 
1337   TheCall->setType(ParamTy);
1338 
1339   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1340     if (!ParamTy->isPointerType())
1341       return 0;
1342     if (ParamTy->isFunctionPointerType())
1343       return 1;
1344     if (ParamTy->isVoidPointerType())
1345       return 2;
1346     return llvm::Optional<unsigned>{};
1347   }();
1348   if (DiagSelect.hasValue()) {
1349     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1350         << DiagSelect.getValue() << TheCall->getSourceRange();
1351     return ExprError();
1352   }
1353 
1354   // We either have an incomplete class type, or we have a class template
1355   // whose instantiation has not been forced. Example:
1356   //
1357   //   template <class T> struct Foo { T value; };
1358   //   Foo<int> *p = nullptr;
1359   //   auto *d = __builtin_launder(p);
1360   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1361                             diag::err_incomplete_type))
1362     return ExprError();
1363 
1364   assert(ParamTy->getPointeeType()->isObjectType() &&
1365          "Unhandled non-object pointer case");
1366 
1367   InitializedEntity Entity =
1368       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1369   ExprResult Arg =
1370       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1371   if (Arg.isInvalid())
1372     return ExprError();
1373   TheCall->setArg(0, Arg.get());
1374 
1375   return TheCall;
1376 }
1377 
1378 // Emit an error and return true if the current architecture is not in the list
1379 // of supported architectures.
1380 static bool
1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1382                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1383   llvm::Triple::ArchType CurArch =
1384       S.getASTContext().getTargetInfo().getTriple().getArch();
1385   if (llvm::is_contained(SupportedArchs, CurArch))
1386     return false;
1387   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1388       << TheCall->getSourceRange();
1389   return true;
1390 }
1391 
1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1393                                  SourceLocation CallSiteLoc);
1394 
1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1396                                       CallExpr *TheCall) {
1397   switch (TI.getTriple().getArch()) {
1398   default:
1399     // Some builtins don't require additional checking, so just consider these
1400     // acceptable.
1401     return false;
1402   case llvm::Triple::arm:
1403   case llvm::Triple::armeb:
1404   case llvm::Triple::thumb:
1405   case llvm::Triple::thumbeb:
1406     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1407   case llvm::Triple::aarch64:
1408   case llvm::Triple::aarch64_32:
1409   case llvm::Triple::aarch64_be:
1410     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1411   case llvm::Triple::bpfeb:
1412   case llvm::Triple::bpfel:
1413     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1414   case llvm::Triple::hexagon:
1415     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1416   case llvm::Triple::mips:
1417   case llvm::Triple::mipsel:
1418   case llvm::Triple::mips64:
1419   case llvm::Triple::mips64el:
1420     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::systemz:
1422     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1423   case llvm::Triple::x86:
1424   case llvm::Triple::x86_64:
1425     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1426   case llvm::Triple::ppc:
1427   case llvm::Triple::ppc64:
1428   case llvm::Triple::ppc64le:
1429     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1430   case llvm::Triple::amdgcn:
1431     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1432   }
1433 }
1434 
1435 ExprResult
1436 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1437                                CallExpr *TheCall) {
1438   ExprResult TheCallResult(TheCall);
1439 
1440   // Find out if any arguments are required to be integer constant expressions.
1441   unsigned ICEArguments = 0;
1442   ASTContext::GetBuiltinTypeError Error;
1443   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1444   if (Error != ASTContext::GE_None)
1445     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1446 
1447   // If any arguments are required to be ICE's, check and diagnose.
1448   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1449     // Skip arguments not required to be ICE's.
1450     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1451 
1452     llvm::APSInt Result;
1453     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1454       return true;
1455     ICEArguments &= ~(1 << ArgNo);
1456   }
1457 
1458   switch (BuiltinID) {
1459   case Builtin::BI__builtin___CFStringMakeConstantString:
1460     assert(TheCall->getNumArgs() == 1 &&
1461            "Wrong # arguments to builtin CFStringMakeConstantString");
1462     if (CheckObjCString(TheCall->getArg(0)))
1463       return ExprError();
1464     break;
1465   case Builtin::BI__builtin_ms_va_start:
1466   case Builtin::BI__builtin_stdarg_start:
1467   case Builtin::BI__builtin_va_start:
1468     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1469       return ExprError();
1470     break;
1471   case Builtin::BI__va_start: {
1472     switch (Context.getTargetInfo().getTriple().getArch()) {
1473     case llvm::Triple::aarch64:
1474     case llvm::Triple::arm:
1475     case llvm::Triple::thumb:
1476       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1477         return ExprError();
1478       break;
1479     default:
1480       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1481         return ExprError();
1482       break;
1483     }
1484     break;
1485   }
1486 
1487   // The acquire, release, and no fence variants are ARM and AArch64 only.
1488   case Builtin::BI_interlockedbittestandset_acq:
1489   case Builtin::BI_interlockedbittestandset_rel:
1490   case Builtin::BI_interlockedbittestandset_nf:
1491   case Builtin::BI_interlockedbittestandreset_acq:
1492   case Builtin::BI_interlockedbittestandreset_rel:
1493   case Builtin::BI_interlockedbittestandreset_nf:
1494     if (CheckBuiltinTargetSupport(
1495             *this, BuiltinID, TheCall,
1496             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1497       return ExprError();
1498     break;
1499 
1500   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1501   case Builtin::BI_bittest64:
1502   case Builtin::BI_bittestandcomplement64:
1503   case Builtin::BI_bittestandreset64:
1504   case Builtin::BI_bittestandset64:
1505   case Builtin::BI_interlockedbittestandreset64:
1506   case Builtin::BI_interlockedbittestandset64:
1507     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1508                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1509                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1510       return ExprError();
1511     break;
1512 
1513   case Builtin::BI__builtin_isgreater:
1514   case Builtin::BI__builtin_isgreaterequal:
1515   case Builtin::BI__builtin_isless:
1516   case Builtin::BI__builtin_islessequal:
1517   case Builtin::BI__builtin_islessgreater:
1518   case Builtin::BI__builtin_isunordered:
1519     if (SemaBuiltinUnorderedCompare(TheCall))
1520       return ExprError();
1521     break;
1522   case Builtin::BI__builtin_fpclassify:
1523     if (SemaBuiltinFPClassification(TheCall, 6))
1524       return ExprError();
1525     break;
1526   case Builtin::BI__builtin_isfinite:
1527   case Builtin::BI__builtin_isinf:
1528   case Builtin::BI__builtin_isinf_sign:
1529   case Builtin::BI__builtin_isnan:
1530   case Builtin::BI__builtin_isnormal:
1531   case Builtin::BI__builtin_signbit:
1532   case Builtin::BI__builtin_signbitf:
1533   case Builtin::BI__builtin_signbitl:
1534     if (SemaBuiltinFPClassification(TheCall, 1))
1535       return ExprError();
1536     break;
1537   case Builtin::BI__builtin_shufflevector:
1538     return SemaBuiltinShuffleVector(TheCall);
1539     // TheCall will be freed by the smart pointer here, but that's fine, since
1540     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1541   case Builtin::BI__builtin_prefetch:
1542     if (SemaBuiltinPrefetch(TheCall))
1543       return ExprError();
1544     break;
1545   case Builtin::BI__builtin_alloca_with_align:
1546     if (SemaBuiltinAllocaWithAlign(TheCall))
1547       return ExprError();
1548     LLVM_FALLTHROUGH;
1549   case Builtin::BI__builtin_alloca:
1550     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1551         << TheCall->getDirectCallee();
1552     break;
1553   case Builtin::BI__assume:
1554   case Builtin::BI__builtin_assume:
1555     if (SemaBuiltinAssume(TheCall))
1556       return ExprError();
1557     break;
1558   case Builtin::BI__builtin_assume_aligned:
1559     if (SemaBuiltinAssumeAligned(TheCall))
1560       return ExprError();
1561     break;
1562   case Builtin::BI__builtin_dynamic_object_size:
1563   case Builtin::BI__builtin_object_size:
1564     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1565       return ExprError();
1566     break;
1567   case Builtin::BI__builtin_longjmp:
1568     if (SemaBuiltinLongjmp(TheCall))
1569       return ExprError();
1570     break;
1571   case Builtin::BI__builtin_setjmp:
1572     if (SemaBuiltinSetjmp(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI_setjmp:
1576   case Builtin::BI_setjmpex:
1577     if (checkArgCount(*this, TheCall, 1))
1578       return true;
1579     break;
1580   case Builtin::BI__builtin_classify_type:
1581     if (checkArgCount(*this, TheCall, 1)) return true;
1582     TheCall->setType(Context.IntTy);
1583     break;
1584   case Builtin::BI__builtin_constant_p: {
1585     if (checkArgCount(*this, TheCall, 1)) return true;
1586     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1587     if (Arg.isInvalid()) return true;
1588     TheCall->setArg(0, Arg.get());
1589     TheCall->setType(Context.IntTy);
1590     break;
1591   }
1592   case Builtin::BI__builtin_launder:
1593     return SemaBuiltinLaunder(*this, TheCall);
1594   case Builtin::BI__sync_fetch_and_add:
1595   case Builtin::BI__sync_fetch_and_add_1:
1596   case Builtin::BI__sync_fetch_and_add_2:
1597   case Builtin::BI__sync_fetch_and_add_4:
1598   case Builtin::BI__sync_fetch_and_add_8:
1599   case Builtin::BI__sync_fetch_and_add_16:
1600   case Builtin::BI__sync_fetch_and_sub:
1601   case Builtin::BI__sync_fetch_and_sub_1:
1602   case Builtin::BI__sync_fetch_and_sub_2:
1603   case Builtin::BI__sync_fetch_and_sub_4:
1604   case Builtin::BI__sync_fetch_and_sub_8:
1605   case Builtin::BI__sync_fetch_and_sub_16:
1606   case Builtin::BI__sync_fetch_and_or:
1607   case Builtin::BI__sync_fetch_and_or_1:
1608   case Builtin::BI__sync_fetch_and_or_2:
1609   case Builtin::BI__sync_fetch_and_or_4:
1610   case Builtin::BI__sync_fetch_and_or_8:
1611   case Builtin::BI__sync_fetch_and_or_16:
1612   case Builtin::BI__sync_fetch_and_and:
1613   case Builtin::BI__sync_fetch_and_and_1:
1614   case Builtin::BI__sync_fetch_and_and_2:
1615   case Builtin::BI__sync_fetch_and_and_4:
1616   case Builtin::BI__sync_fetch_and_and_8:
1617   case Builtin::BI__sync_fetch_and_and_16:
1618   case Builtin::BI__sync_fetch_and_xor:
1619   case Builtin::BI__sync_fetch_and_xor_1:
1620   case Builtin::BI__sync_fetch_and_xor_2:
1621   case Builtin::BI__sync_fetch_and_xor_4:
1622   case Builtin::BI__sync_fetch_and_xor_8:
1623   case Builtin::BI__sync_fetch_and_xor_16:
1624   case Builtin::BI__sync_fetch_and_nand:
1625   case Builtin::BI__sync_fetch_and_nand_1:
1626   case Builtin::BI__sync_fetch_and_nand_2:
1627   case Builtin::BI__sync_fetch_and_nand_4:
1628   case Builtin::BI__sync_fetch_and_nand_8:
1629   case Builtin::BI__sync_fetch_and_nand_16:
1630   case Builtin::BI__sync_add_and_fetch:
1631   case Builtin::BI__sync_add_and_fetch_1:
1632   case Builtin::BI__sync_add_and_fetch_2:
1633   case Builtin::BI__sync_add_and_fetch_4:
1634   case Builtin::BI__sync_add_and_fetch_8:
1635   case Builtin::BI__sync_add_and_fetch_16:
1636   case Builtin::BI__sync_sub_and_fetch:
1637   case Builtin::BI__sync_sub_and_fetch_1:
1638   case Builtin::BI__sync_sub_and_fetch_2:
1639   case Builtin::BI__sync_sub_and_fetch_4:
1640   case Builtin::BI__sync_sub_and_fetch_8:
1641   case Builtin::BI__sync_sub_and_fetch_16:
1642   case Builtin::BI__sync_and_and_fetch:
1643   case Builtin::BI__sync_and_and_fetch_1:
1644   case Builtin::BI__sync_and_and_fetch_2:
1645   case Builtin::BI__sync_and_and_fetch_4:
1646   case Builtin::BI__sync_and_and_fetch_8:
1647   case Builtin::BI__sync_and_and_fetch_16:
1648   case Builtin::BI__sync_or_and_fetch:
1649   case Builtin::BI__sync_or_and_fetch_1:
1650   case Builtin::BI__sync_or_and_fetch_2:
1651   case Builtin::BI__sync_or_and_fetch_4:
1652   case Builtin::BI__sync_or_and_fetch_8:
1653   case Builtin::BI__sync_or_and_fetch_16:
1654   case Builtin::BI__sync_xor_and_fetch:
1655   case Builtin::BI__sync_xor_and_fetch_1:
1656   case Builtin::BI__sync_xor_and_fetch_2:
1657   case Builtin::BI__sync_xor_and_fetch_4:
1658   case Builtin::BI__sync_xor_and_fetch_8:
1659   case Builtin::BI__sync_xor_and_fetch_16:
1660   case Builtin::BI__sync_nand_and_fetch:
1661   case Builtin::BI__sync_nand_and_fetch_1:
1662   case Builtin::BI__sync_nand_and_fetch_2:
1663   case Builtin::BI__sync_nand_and_fetch_4:
1664   case Builtin::BI__sync_nand_and_fetch_8:
1665   case Builtin::BI__sync_nand_and_fetch_16:
1666   case Builtin::BI__sync_val_compare_and_swap:
1667   case Builtin::BI__sync_val_compare_and_swap_1:
1668   case Builtin::BI__sync_val_compare_and_swap_2:
1669   case Builtin::BI__sync_val_compare_and_swap_4:
1670   case Builtin::BI__sync_val_compare_and_swap_8:
1671   case Builtin::BI__sync_val_compare_and_swap_16:
1672   case Builtin::BI__sync_bool_compare_and_swap:
1673   case Builtin::BI__sync_bool_compare_and_swap_1:
1674   case Builtin::BI__sync_bool_compare_and_swap_2:
1675   case Builtin::BI__sync_bool_compare_and_swap_4:
1676   case Builtin::BI__sync_bool_compare_and_swap_8:
1677   case Builtin::BI__sync_bool_compare_and_swap_16:
1678   case Builtin::BI__sync_lock_test_and_set:
1679   case Builtin::BI__sync_lock_test_and_set_1:
1680   case Builtin::BI__sync_lock_test_and_set_2:
1681   case Builtin::BI__sync_lock_test_and_set_4:
1682   case Builtin::BI__sync_lock_test_and_set_8:
1683   case Builtin::BI__sync_lock_test_and_set_16:
1684   case Builtin::BI__sync_lock_release:
1685   case Builtin::BI__sync_lock_release_1:
1686   case Builtin::BI__sync_lock_release_2:
1687   case Builtin::BI__sync_lock_release_4:
1688   case Builtin::BI__sync_lock_release_8:
1689   case Builtin::BI__sync_lock_release_16:
1690   case Builtin::BI__sync_swap:
1691   case Builtin::BI__sync_swap_1:
1692   case Builtin::BI__sync_swap_2:
1693   case Builtin::BI__sync_swap_4:
1694   case Builtin::BI__sync_swap_8:
1695   case Builtin::BI__sync_swap_16:
1696     return SemaBuiltinAtomicOverloaded(TheCallResult);
1697   case Builtin::BI__sync_synchronize:
1698     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1699         << TheCall->getCallee()->getSourceRange();
1700     break;
1701   case Builtin::BI__builtin_nontemporal_load:
1702   case Builtin::BI__builtin_nontemporal_store:
1703     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1704   case Builtin::BI__builtin_memcpy_inline: {
1705     clang::Expr *SizeOp = TheCall->getArg(2);
1706     // We warn about copying to or from `nullptr` pointers when `size` is
1707     // greater than 0. When `size` is value dependent we cannot evaluate its
1708     // value so we bail out.
1709     if (SizeOp->isValueDependent())
1710       break;
1711     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1712       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1713       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1714     }
1715     break;
1716   }
1717 #define BUILTIN(ID, TYPE, ATTRS)
1718 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1719   case Builtin::BI##ID: \
1720     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1721 #include "clang/Basic/Builtins.def"
1722   case Builtin::BI__annotation:
1723     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1724       return ExprError();
1725     break;
1726   case Builtin::BI__builtin_annotation:
1727     if (SemaBuiltinAnnotation(*this, TheCall))
1728       return ExprError();
1729     break;
1730   case Builtin::BI__builtin_addressof:
1731     if (SemaBuiltinAddressof(*this, TheCall))
1732       return ExprError();
1733     break;
1734   case Builtin::BI__builtin_is_aligned:
1735   case Builtin::BI__builtin_align_up:
1736   case Builtin::BI__builtin_align_down:
1737     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1738       return ExprError();
1739     break;
1740   case Builtin::BI__builtin_add_overflow:
1741   case Builtin::BI__builtin_sub_overflow:
1742   case Builtin::BI__builtin_mul_overflow:
1743     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1744       return ExprError();
1745     break;
1746   case Builtin::BI__builtin_operator_new:
1747   case Builtin::BI__builtin_operator_delete: {
1748     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1749     ExprResult Res =
1750         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1751     if (Res.isInvalid())
1752       CorrectDelayedTyposInExpr(TheCallResult.get());
1753     return Res;
1754   }
1755   case Builtin::BI__builtin_dump_struct: {
1756     // We first want to ensure we are called with 2 arguments
1757     if (checkArgCount(*this, TheCall, 2))
1758       return ExprError();
1759     // Ensure that the first argument is of type 'struct XX *'
1760     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1761     const QualType PtrArgType = PtrArg->getType();
1762     if (!PtrArgType->isPointerType() ||
1763         !PtrArgType->getPointeeType()->isRecordType()) {
1764       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1765           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1766           << "structure pointer";
1767       return ExprError();
1768     }
1769 
1770     // Ensure that the second argument is of type 'FunctionType'
1771     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1772     const QualType FnPtrArgType = FnPtrArg->getType();
1773     if (!FnPtrArgType->isPointerType()) {
1774       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1775           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1776           << FnPtrArgType << "'int (*)(const char *, ...)'";
1777       return ExprError();
1778     }
1779 
1780     const auto *FuncType =
1781         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1782 
1783     if (!FuncType) {
1784       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1785           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1786           << FnPtrArgType << "'int (*)(const char *, ...)'";
1787       return ExprError();
1788     }
1789 
1790     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1791       if (!FT->getNumParams()) {
1792         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1793             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1794             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1795         return ExprError();
1796       }
1797       QualType PT = FT->getParamType(0);
1798       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1799           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1800           !PT->getPointeeType().isConstQualified()) {
1801         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1802             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1803             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1804         return ExprError();
1805       }
1806     }
1807 
1808     TheCall->setType(Context.IntTy);
1809     break;
1810   }
1811   case Builtin::BI__builtin_preserve_access_index:
1812     if (SemaBuiltinPreserveAI(*this, TheCall))
1813       return ExprError();
1814     break;
1815   case Builtin::BI__builtin_call_with_static_chain:
1816     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1817       return ExprError();
1818     break;
1819   case Builtin::BI__exception_code:
1820   case Builtin::BI_exception_code:
1821     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1822                                  diag::err_seh___except_block))
1823       return ExprError();
1824     break;
1825   case Builtin::BI__exception_info:
1826   case Builtin::BI_exception_info:
1827     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1828                                  diag::err_seh___except_filter))
1829       return ExprError();
1830     break;
1831   case Builtin::BI__GetExceptionInfo:
1832     if (checkArgCount(*this, TheCall, 1))
1833       return ExprError();
1834 
1835     if (CheckCXXThrowOperand(
1836             TheCall->getBeginLoc(),
1837             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1838             TheCall))
1839       return ExprError();
1840 
1841     TheCall->setType(Context.VoidPtrTy);
1842     break;
1843   // OpenCL v2.0, s6.13.16 - Pipe functions
1844   case Builtin::BIread_pipe:
1845   case Builtin::BIwrite_pipe:
1846     // Since those two functions are declared with var args, we need a semantic
1847     // check for the argument.
1848     if (SemaBuiltinRWPipe(*this, TheCall))
1849       return ExprError();
1850     break;
1851   case Builtin::BIreserve_read_pipe:
1852   case Builtin::BIreserve_write_pipe:
1853   case Builtin::BIwork_group_reserve_read_pipe:
1854   case Builtin::BIwork_group_reserve_write_pipe:
1855     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1856       return ExprError();
1857     break;
1858   case Builtin::BIsub_group_reserve_read_pipe:
1859   case Builtin::BIsub_group_reserve_write_pipe:
1860     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1861         SemaBuiltinReserveRWPipe(*this, TheCall))
1862       return ExprError();
1863     break;
1864   case Builtin::BIcommit_read_pipe:
1865   case Builtin::BIcommit_write_pipe:
1866   case Builtin::BIwork_group_commit_read_pipe:
1867   case Builtin::BIwork_group_commit_write_pipe:
1868     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1869       return ExprError();
1870     break;
1871   case Builtin::BIsub_group_commit_read_pipe:
1872   case Builtin::BIsub_group_commit_write_pipe:
1873     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1874         SemaBuiltinCommitRWPipe(*this, TheCall))
1875       return ExprError();
1876     break;
1877   case Builtin::BIget_pipe_num_packets:
1878   case Builtin::BIget_pipe_max_packets:
1879     if (SemaBuiltinPipePackets(*this, TheCall))
1880       return ExprError();
1881     break;
1882   case Builtin::BIto_global:
1883   case Builtin::BIto_local:
1884   case Builtin::BIto_private:
1885     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1886       return ExprError();
1887     break;
1888   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1889   case Builtin::BIenqueue_kernel:
1890     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1891       return ExprError();
1892     break;
1893   case Builtin::BIget_kernel_work_group_size:
1894   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1895     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1896       return ExprError();
1897     break;
1898   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1899   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1900     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1901       return ExprError();
1902     break;
1903   case Builtin::BI__builtin_os_log_format:
1904     Cleanup.setExprNeedsCleanups(true);
1905     LLVM_FALLTHROUGH;
1906   case Builtin::BI__builtin_os_log_format_buffer_size:
1907     if (SemaBuiltinOSLogFormat(TheCall))
1908       return ExprError();
1909     break;
1910   case Builtin::BI__builtin_frame_address:
1911   case Builtin::BI__builtin_return_address: {
1912     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1913       return ExprError();
1914 
1915     // -Wframe-address warning if non-zero passed to builtin
1916     // return/frame address.
1917     Expr::EvalResult Result;
1918     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1919         Result.Val.getInt() != 0)
1920       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1921           << ((BuiltinID == Builtin::BI__builtin_return_address)
1922                   ? "__builtin_return_address"
1923                   : "__builtin_frame_address")
1924           << TheCall->getSourceRange();
1925     break;
1926   }
1927 
1928   case Builtin::BI__builtin_matrix_transpose:
1929     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1930 
1931   case Builtin::BI__builtin_matrix_column_major_load:
1932     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1933 
1934   case Builtin::BI__builtin_matrix_column_major_store:
1935     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1936   }
1937 
1938   // Since the target specific builtins for each arch overlap, only check those
1939   // of the arch we are compiling for.
1940   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1941     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1942       assert(Context.getAuxTargetInfo() &&
1943              "Aux Target Builtin, but not an aux target?");
1944 
1945       if (CheckTSBuiltinFunctionCall(
1946               *Context.getAuxTargetInfo(),
1947               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1948         return ExprError();
1949     } else {
1950       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1951                                      TheCall))
1952         return ExprError();
1953     }
1954   }
1955 
1956   return TheCallResult;
1957 }
1958 
1959 // Get the valid immediate range for the specified NEON type code.
1960 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1961   NeonTypeFlags Type(t);
1962   int IsQuad = ForceQuad ? true : Type.isQuad();
1963   switch (Type.getEltType()) {
1964   case NeonTypeFlags::Int8:
1965   case NeonTypeFlags::Poly8:
1966     return shift ? 7 : (8 << IsQuad) - 1;
1967   case NeonTypeFlags::Int16:
1968   case NeonTypeFlags::Poly16:
1969     return shift ? 15 : (4 << IsQuad) - 1;
1970   case NeonTypeFlags::Int32:
1971     return shift ? 31 : (2 << IsQuad) - 1;
1972   case NeonTypeFlags::Int64:
1973   case NeonTypeFlags::Poly64:
1974     return shift ? 63 : (1 << IsQuad) - 1;
1975   case NeonTypeFlags::Poly128:
1976     return shift ? 127 : (1 << IsQuad) - 1;
1977   case NeonTypeFlags::Float16:
1978     assert(!shift && "cannot shift float types!");
1979     return (4 << IsQuad) - 1;
1980   case NeonTypeFlags::Float32:
1981     assert(!shift && "cannot shift float types!");
1982     return (2 << IsQuad) - 1;
1983   case NeonTypeFlags::Float64:
1984     assert(!shift && "cannot shift float types!");
1985     return (1 << IsQuad) - 1;
1986   case NeonTypeFlags::BFloat16:
1987     assert(!shift && "cannot shift float types!");
1988     return (4 << IsQuad) - 1;
1989   }
1990   llvm_unreachable("Invalid NeonTypeFlag!");
1991 }
1992 
1993 /// getNeonEltType - Return the QualType corresponding to the elements of
1994 /// the vector type specified by the NeonTypeFlags.  This is used to check
1995 /// the pointer arguments for Neon load/store intrinsics.
1996 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1997                                bool IsPolyUnsigned, bool IsInt64Long) {
1998   switch (Flags.getEltType()) {
1999   case NeonTypeFlags::Int8:
2000     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2001   case NeonTypeFlags::Int16:
2002     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2003   case NeonTypeFlags::Int32:
2004     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2005   case NeonTypeFlags::Int64:
2006     if (IsInt64Long)
2007       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2008     else
2009       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2010                                 : Context.LongLongTy;
2011   case NeonTypeFlags::Poly8:
2012     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2013   case NeonTypeFlags::Poly16:
2014     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2015   case NeonTypeFlags::Poly64:
2016     if (IsInt64Long)
2017       return Context.UnsignedLongTy;
2018     else
2019       return Context.UnsignedLongLongTy;
2020   case NeonTypeFlags::Poly128:
2021     break;
2022   case NeonTypeFlags::Float16:
2023     return Context.HalfTy;
2024   case NeonTypeFlags::Float32:
2025     return Context.FloatTy;
2026   case NeonTypeFlags::Float64:
2027     return Context.DoubleTy;
2028   case NeonTypeFlags::BFloat16:
2029     return Context.BFloat16Ty;
2030   }
2031   llvm_unreachable("Invalid NeonTypeFlag!");
2032 }
2033 
2034 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2035   // Range check SVE intrinsics that take immediate values.
2036   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2037 
2038   switch (BuiltinID) {
2039   default:
2040     return false;
2041 #define GET_SVE_IMMEDIATE_CHECK
2042 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2043 #undef GET_SVE_IMMEDIATE_CHECK
2044   }
2045 
2046   // Perform all the immediate checks for this builtin call.
2047   bool HasError = false;
2048   for (auto &I : ImmChecks) {
2049     int ArgNum, CheckTy, ElementSizeInBits;
2050     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2051 
2052     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2053 
2054     // Function that checks whether the operand (ArgNum) is an immediate
2055     // that is one of the predefined values.
2056     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2057                                    int ErrDiag) -> bool {
2058       // We can't check the value of a dependent argument.
2059       Expr *Arg = TheCall->getArg(ArgNum);
2060       if (Arg->isTypeDependent() || Arg->isValueDependent())
2061         return false;
2062 
2063       // Check constant-ness first.
2064       llvm::APSInt Imm;
2065       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2066         return true;
2067 
2068       if (!CheckImm(Imm.getSExtValue()))
2069         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2070       return false;
2071     };
2072 
2073     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2074     case SVETypeFlags::ImmCheck0_31:
2075       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2076         HasError = true;
2077       break;
2078     case SVETypeFlags::ImmCheck0_13:
2079       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2080         HasError = true;
2081       break;
2082     case SVETypeFlags::ImmCheck1_16:
2083       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2084         HasError = true;
2085       break;
2086     case SVETypeFlags::ImmCheck0_7:
2087       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2088         HasError = true;
2089       break;
2090     case SVETypeFlags::ImmCheckExtract:
2091       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2092                                       (2048 / ElementSizeInBits) - 1))
2093         HasError = true;
2094       break;
2095     case SVETypeFlags::ImmCheckShiftRight:
2096       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2097         HasError = true;
2098       break;
2099     case SVETypeFlags::ImmCheckShiftRightNarrow:
2100       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2101                                       ElementSizeInBits / 2))
2102         HasError = true;
2103       break;
2104     case SVETypeFlags::ImmCheckShiftLeft:
2105       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2106                                       ElementSizeInBits - 1))
2107         HasError = true;
2108       break;
2109     case SVETypeFlags::ImmCheckLaneIndex:
2110       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2111                                       (128 / (1 * ElementSizeInBits)) - 1))
2112         HasError = true;
2113       break;
2114     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2115       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2116                                       (128 / (2 * ElementSizeInBits)) - 1))
2117         HasError = true;
2118       break;
2119     case SVETypeFlags::ImmCheckLaneIndexDot:
2120       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2121                                       (128 / (4 * ElementSizeInBits)) - 1))
2122         HasError = true;
2123       break;
2124     case SVETypeFlags::ImmCheckComplexRot90_270:
2125       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2126                               diag::err_rotation_argument_to_cadd))
2127         HasError = true;
2128       break;
2129     case SVETypeFlags::ImmCheckComplexRotAll90:
2130       if (CheckImmediateInSet(
2131               [](int64_t V) {
2132                 return V == 0 || V == 90 || V == 180 || V == 270;
2133               },
2134               diag::err_rotation_argument_to_cmla))
2135         HasError = true;
2136       break;
2137     case SVETypeFlags::ImmCheck0_1:
2138       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2139         HasError = true;
2140       break;
2141     case SVETypeFlags::ImmCheck0_2:
2142       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2143         HasError = true;
2144       break;
2145     case SVETypeFlags::ImmCheck0_3:
2146       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2147         HasError = true;
2148       break;
2149     }
2150   }
2151 
2152   return HasError;
2153 }
2154 
2155 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2156                                         unsigned BuiltinID, CallExpr *TheCall) {
2157   llvm::APSInt Result;
2158   uint64_t mask = 0;
2159   unsigned TV = 0;
2160   int PtrArgNum = -1;
2161   bool HasConstPtr = false;
2162   switch (BuiltinID) {
2163 #define GET_NEON_OVERLOAD_CHECK
2164 #include "clang/Basic/arm_neon.inc"
2165 #include "clang/Basic/arm_fp16.inc"
2166 #undef GET_NEON_OVERLOAD_CHECK
2167   }
2168 
2169   // For NEON intrinsics which are overloaded on vector element type, validate
2170   // the immediate which specifies which variant to emit.
2171   unsigned ImmArg = TheCall->getNumArgs()-1;
2172   if (mask) {
2173     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2174       return true;
2175 
2176     TV = Result.getLimitedValue(64);
2177     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2178       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2179              << TheCall->getArg(ImmArg)->getSourceRange();
2180   }
2181 
2182   if (PtrArgNum >= 0) {
2183     // Check that pointer arguments have the specified type.
2184     Expr *Arg = TheCall->getArg(PtrArgNum);
2185     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2186       Arg = ICE->getSubExpr();
2187     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2188     QualType RHSTy = RHS.get()->getType();
2189 
2190     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2191     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2192                           Arch == llvm::Triple::aarch64_32 ||
2193                           Arch == llvm::Triple::aarch64_be;
2194     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2195     QualType EltTy =
2196         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2197     if (HasConstPtr)
2198       EltTy = EltTy.withConst();
2199     QualType LHSTy = Context.getPointerType(EltTy);
2200     AssignConvertType ConvTy;
2201     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2202     if (RHS.isInvalid())
2203       return true;
2204     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2205                                  RHS.get(), AA_Assigning))
2206       return true;
2207   }
2208 
2209   // For NEON intrinsics which take an immediate value as part of the
2210   // instruction, range check them here.
2211   unsigned i = 0, l = 0, u = 0;
2212   switch (BuiltinID) {
2213   default:
2214     return false;
2215   #define GET_NEON_IMMEDIATE_CHECK
2216   #include "clang/Basic/arm_neon.inc"
2217   #include "clang/Basic/arm_fp16.inc"
2218   #undef GET_NEON_IMMEDIATE_CHECK
2219   }
2220 
2221   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2222 }
2223 
2224 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2225   switch (BuiltinID) {
2226   default:
2227     return false;
2228   #include "clang/Basic/arm_mve_builtin_sema.inc"
2229   }
2230 }
2231 
2232 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2233                                        CallExpr *TheCall) {
2234   bool Err = false;
2235   switch (BuiltinID) {
2236   default:
2237     return false;
2238 #include "clang/Basic/arm_cde_builtin_sema.inc"
2239   }
2240 
2241   if (Err)
2242     return true;
2243 
2244   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2245 }
2246 
2247 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2248                                         const Expr *CoprocArg, bool WantCDE) {
2249   if (isConstantEvaluated())
2250     return false;
2251 
2252   // We can't check the value of a dependent argument.
2253   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2254     return false;
2255 
2256   llvm::APSInt CoprocNoAP;
2257   bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context);
2258   (void)IsICE;
2259   assert(IsICE && "Coprocossor immediate is not a constant expression");
2260   int64_t CoprocNo = CoprocNoAP.getExtValue();
2261   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2262 
2263   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2264   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2265 
2266   if (IsCDECoproc != WantCDE)
2267     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2268            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2269 
2270   return false;
2271 }
2272 
2273 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2274                                         unsigned MaxWidth) {
2275   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2276           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2277           BuiltinID == ARM::BI__builtin_arm_strex ||
2278           BuiltinID == ARM::BI__builtin_arm_stlex ||
2279           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2280           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2281           BuiltinID == AArch64::BI__builtin_arm_strex ||
2282           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2283          "unexpected ARM builtin");
2284   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2285                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2286                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2287                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2288 
2289   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2290 
2291   // Ensure that we have the proper number of arguments.
2292   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2293     return true;
2294 
2295   // Inspect the pointer argument of the atomic builtin.  This should always be
2296   // a pointer type, whose element is an integral scalar or pointer type.
2297   // Because it is a pointer type, we don't have to worry about any implicit
2298   // casts here.
2299   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2300   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2301   if (PointerArgRes.isInvalid())
2302     return true;
2303   PointerArg = PointerArgRes.get();
2304 
2305   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2306   if (!pointerType) {
2307     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2308         << PointerArg->getType() << PointerArg->getSourceRange();
2309     return true;
2310   }
2311 
2312   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2313   // task is to insert the appropriate casts into the AST. First work out just
2314   // what the appropriate type is.
2315   QualType ValType = pointerType->getPointeeType();
2316   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2317   if (IsLdrex)
2318     AddrType.addConst();
2319 
2320   // Issue a warning if the cast is dodgy.
2321   CastKind CastNeeded = CK_NoOp;
2322   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2323     CastNeeded = CK_BitCast;
2324     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2325         << PointerArg->getType() << Context.getPointerType(AddrType)
2326         << AA_Passing << PointerArg->getSourceRange();
2327   }
2328 
2329   // Finally, do the cast and replace the argument with the corrected version.
2330   AddrType = Context.getPointerType(AddrType);
2331   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2332   if (PointerArgRes.isInvalid())
2333     return true;
2334   PointerArg = PointerArgRes.get();
2335 
2336   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2337 
2338   // In general, we allow ints, floats and pointers to be loaded and stored.
2339   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2340       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2341     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2342         << PointerArg->getType() << PointerArg->getSourceRange();
2343     return true;
2344   }
2345 
2346   // But ARM doesn't have instructions to deal with 128-bit versions.
2347   if (Context.getTypeSize(ValType) > MaxWidth) {
2348     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2349     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2350         << PointerArg->getType() << PointerArg->getSourceRange();
2351     return true;
2352   }
2353 
2354   switch (ValType.getObjCLifetime()) {
2355   case Qualifiers::OCL_None:
2356   case Qualifiers::OCL_ExplicitNone:
2357     // okay
2358     break;
2359 
2360   case Qualifiers::OCL_Weak:
2361   case Qualifiers::OCL_Strong:
2362   case Qualifiers::OCL_Autoreleasing:
2363     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2364         << ValType << PointerArg->getSourceRange();
2365     return true;
2366   }
2367 
2368   if (IsLdrex) {
2369     TheCall->setType(ValType);
2370     return false;
2371   }
2372 
2373   // Initialize the argument to be stored.
2374   ExprResult ValArg = TheCall->getArg(0);
2375   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2376       Context, ValType, /*consume*/ false);
2377   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2378   if (ValArg.isInvalid())
2379     return true;
2380   TheCall->setArg(0, ValArg.get());
2381 
2382   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2383   // but the custom checker bypasses all default analysis.
2384   TheCall->setType(Context.IntTy);
2385   return false;
2386 }
2387 
2388 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2389                                        CallExpr *TheCall) {
2390   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2391       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2392       BuiltinID == ARM::BI__builtin_arm_strex ||
2393       BuiltinID == ARM::BI__builtin_arm_stlex) {
2394     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2395   }
2396 
2397   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2398     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2399       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2400   }
2401 
2402   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2403       BuiltinID == ARM::BI__builtin_arm_wsr64)
2404     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2405 
2406   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2407       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2408       BuiltinID == ARM::BI__builtin_arm_wsr ||
2409       BuiltinID == ARM::BI__builtin_arm_wsrp)
2410     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2411 
2412   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2413     return true;
2414   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2415     return true;
2416   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2417     return true;
2418 
2419   // For intrinsics which take an immediate value as part of the instruction,
2420   // range check them here.
2421   // FIXME: VFP Intrinsics should error if VFP not present.
2422   switch (BuiltinID) {
2423   default: return false;
2424   case ARM::BI__builtin_arm_ssat:
2425     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2426   case ARM::BI__builtin_arm_usat:
2427     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2428   case ARM::BI__builtin_arm_ssat16:
2429     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2430   case ARM::BI__builtin_arm_usat16:
2431     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2432   case ARM::BI__builtin_arm_vcvtr_f:
2433   case ARM::BI__builtin_arm_vcvtr_d:
2434     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2435   case ARM::BI__builtin_arm_dmb:
2436   case ARM::BI__builtin_arm_dsb:
2437   case ARM::BI__builtin_arm_isb:
2438   case ARM::BI__builtin_arm_dbg:
2439     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2440   case ARM::BI__builtin_arm_cdp:
2441   case ARM::BI__builtin_arm_cdp2:
2442   case ARM::BI__builtin_arm_mcr:
2443   case ARM::BI__builtin_arm_mcr2:
2444   case ARM::BI__builtin_arm_mrc:
2445   case ARM::BI__builtin_arm_mrc2:
2446   case ARM::BI__builtin_arm_mcrr:
2447   case ARM::BI__builtin_arm_mcrr2:
2448   case ARM::BI__builtin_arm_mrrc:
2449   case ARM::BI__builtin_arm_mrrc2:
2450   case ARM::BI__builtin_arm_ldc:
2451   case ARM::BI__builtin_arm_ldcl:
2452   case ARM::BI__builtin_arm_ldc2:
2453   case ARM::BI__builtin_arm_ldc2l:
2454   case ARM::BI__builtin_arm_stc:
2455   case ARM::BI__builtin_arm_stcl:
2456   case ARM::BI__builtin_arm_stc2:
2457   case ARM::BI__builtin_arm_stc2l:
2458     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2459            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2460                                         /*WantCDE*/ false);
2461   }
2462 }
2463 
2464 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2465                                            unsigned BuiltinID,
2466                                            CallExpr *TheCall) {
2467   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2468       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2469       BuiltinID == AArch64::BI__builtin_arm_strex ||
2470       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2471     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2472   }
2473 
2474   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2475     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2476       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2477       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2478       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2479   }
2480 
2481   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2482       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2483     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2484 
2485   // Memory Tagging Extensions (MTE) Intrinsics
2486   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2487       BuiltinID == AArch64::BI__builtin_arm_addg ||
2488       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2489       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2490       BuiltinID == AArch64::BI__builtin_arm_stg ||
2491       BuiltinID == AArch64::BI__builtin_arm_subp) {
2492     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2493   }
2494 
2495   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2496       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2497       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2498       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2499     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2500 
2501   // Only check the valid encoding range. Any constant in this range would be
2502   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2503   // an exception for incorrect registers. This matches MSVC behavior.
2504   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2505       BuiltinID == AArch64::BI_WriteStatusReg)
2506     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2507 
2508   if (BuiltinID == AArch64::BI__getReg)
2509     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2510 
2511   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2512     return true;
2513 
2514   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2515     return true;
2516 
2517   // For intrinsics which take an immediate value as part of the instruction,
2518   // range check them here.
2519   unsigned i = 0, l = 0, u = 0;
2520   switch (BuiltinID) {
2521   default: return false;
2522   case AArch64::BI__builtin_arm_dmb:
2523   case AArch64::BI__builtin_arm_dsb:
2524   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2525   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2526   }
2527 
2528   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2529 }
2530 
2531 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2532                                        CallExpr *TheCall) {
2533   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2534           BuiltinID == BPF::BI__builtin_btf_type_id) &&
2535          "unexpected ARM builtin");
2536 
2537   if (checkArgCount(*this, TheCall, 2))
2538     return true;
2539 
2540   Expr *Arg;
2541   if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2542     // The second argument needs to be a constant int
2543     llvm::APSInt Value;
2544     Arg = TheCall->getArg(1);
2545     if (!Arg->isIntegerConstantExpr(Value, Context)) {
2546       Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const)
2547           << 2 << Arg->getSourceRange();
2548       return true;
2549     }
2550 
2551     TheCall->setType(Context.UnsignedIntTy);
2552     return false;
2553   }
2554 
2555   // The first argument needs to be a record field access.
2556   // If it is an array element access, we delay decision
2557   // to BPF backend to check whether the access is a
2558   // field access or not.
2559   Arg = TheCall->getArg(0);
2560   if (Arg->getType()->getAsPlaceholderType() ||
2561       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2562        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2563        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2564     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2565         << 1 << Arg->getSourceRange();
2566     return true;
2567   }
2568 
2569   // The second argument needs to be a constant int
2570   Arg = TheCall->getArg(1);
2571   llvm::APSInt Value;
2572   if (!Arg->isIntegerConstantExpr(Value, Context)) {
2573     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2574         << 2 << Arg->getSourceRange();
2575     return true;
2576   }
2577 
2578   TheCall->setType(Context.UnsignedIntTy);
2579   return false;
2580 }
2581 
2582 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2583   struct ArgInfo {
2584     uint8_t OpNum;
2585     bool IsSigned;
2586     uint8_t BitWidth;
2587     uint8_t Align;
2588   };
2589   struct BuiltinInfo {
2590     unsigned BuiltinID;
2591     ArgInfo Infos[2];
2592   };
2593 
2594   static BuiltinInfo Infos[] = {
2595     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2596     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2597     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2598     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2599     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2600     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2601     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2602     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2603     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2604     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2605     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2606 
2607     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2608     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2609     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2610     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2611     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2612     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2613     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2614     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2615     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2616     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2617     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2618 
2619     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2620     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2621     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2622     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2623     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2624     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2625     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2626     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2627     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2628     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2629     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2630     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2631     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2632     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2633     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2634     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2635     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2636     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2637     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2638     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2639     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2640     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2641     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2642     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2643     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2644     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2645     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2646     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2647     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2648     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2649     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2650     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2651     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2652     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2653     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2654     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2655     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2656     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2657     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2658     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2659     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2660     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2661     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2662     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2663     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2664     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2665     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2666     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2667     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2668     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2669     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2670     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2671                                                       {{ 1, false, 6,  0 }} },
2672     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2673     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2674     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2675     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2676     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2677     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2678     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2679                                                       {{ 1, false, 5,  0 }} },
2680     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2681     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2682     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2683     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2684     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2685     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2686                                                        { 2, false, 5,  0 }} },
2687     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2688                                                        { 2, false, 6,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2690                                                        { 3, false, 5,  0 }} },
2691     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2692                                                        { 3, false, 6,  0 }} },
2693     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2695     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2696     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2697     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2698     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2699     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2700     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2701     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2702     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2703     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2706     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2709                                                       {{ 2, false, 4,  0 },
2710                                                        { 3, false, 5,  0 }} },
2711     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2712                                                       {{ 2, false, 4,  0 },
2713                                                        { 3, false, 5,  0 }} },
2714     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2715                                                       {{ 2, false, 4,  0 },
2716                                                        { 3, false, 5,  0 }} },
2717     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2718                                                       {{ 2, false, 4,  0 },
2719                                                        { 3, false, 5,  0 }} },
2720     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2721     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2722     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2723     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2724     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2725     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2726     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2727     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2728     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2729     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2730     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2731                                                        { 2, false, 5,  0 }} },
2732     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2733                                                        { 2, false, 6,  0 }} },
2734     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2735     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2736     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2737     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2738     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2739     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2740     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2741     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2742     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2743                                                       {{ 1, false, 4,  0 }} },
2744     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2745     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2746                                                       {{ 1, false, 4,  0 }} },
2747     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2748     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2749     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2750     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2751     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2752     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2753     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2754     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2755     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2756     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2757     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2759     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2760     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2761     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2762     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2767                                                       {{ 3, false, 1,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2772                                                       {{ 3, false, 1,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2777                                                       {{ 3, false, 1,  0 }} },
2778   };
2779 
2780   // Use a dynamically initialized static to sort the table exactly once on
2781   // first run.
2782   static const bool SortOnce =
2783       (llvm::sort(Infos,
2784                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2785                    return LHS.BuiltinID < RHS.BuiltinID;
2786                  }),
2787        true);
2788   (void)SortOnce;
2789 
2790   const BuiltinInfo *F = llvm::partition_point(
2791       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2792   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2793     return false;
2794 
2795   bool Error = false;
2796 
2797   for (const ArgInfo &A : F->Infos) {
2798     // Ignore empty ArgInfo elements.
2799     if (A.BitWidth == 0)
2800       continue;
2801 
2802     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2803     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2804     if (!A.Align) {
2805       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2806     } else {
2807       unsigned M = 1 << A.Align;
2808       Min *= M;
2809       Max *= M;
2810       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2811                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2812     }
2813   }
2814   return Error;
2815 }
2816 
2817 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2818                                            CallExpr *TheCall) {
2819   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2820 }
2821 
2822 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2823                                         unsigned BuiltinID, CallExpr *TheCall) {
2824   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2825          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2826 }
2827 
2828 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2829                                CallExpr *TheCall) {
2830 
2831   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2832       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2833     if (!TI.hasFeature("dsp"))
2834       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2835   }
2836 
2837   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2838       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2839     if (!TI.hasFeature("dspr2"))
2840       return Diag(TheCall->getBeginLoc(),
2841                   diag::err_mips_builtin_requires_dspr2);
2842   }
2843 
2844   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2845       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2846     if (!TI.hasFeature("msa"))
2847       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2848   }
2849 
2850   return false;
2851 }
2852 
2853 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2854 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2855 // ordering for DSP is unspecified. MSA is ordered by the data format used
2856 // by the underlying instruction i.e., df/m, df/n and then by size.
2857 //
2858 // FIXME: The size tests here should instead be tablegen'd along with the
2859 //        definitions from include/clang/Basic/BuiltinsMips.def.
2860 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2861 //        be too.
2862 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2863   unsigned i = 0, l = 0, u = 0, m = 0;
2864   switch (BuiltinID) {
2865   default: return false;
2866   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2867   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2868   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2869   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2870   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2871   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2872   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2873   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2874   // df/m field.
2875   // These intrinsics take an unsigned 3 bit immediate.
2876   case Mips::BI__builtin_msa_bclri_b:
2877   case Mips::BI__builtin_msa_bnegi_b:
2878   case Mips::BI__builtin_msa_bseti_b:
2879   case Mips::BI__builtin_msa_sat_s_b:
2880   case Mips::BI__builtin_msa_sat_u_b:
2881   case Mips::BI__builtin_msa_slli_b:
2882   case Mips::BI__builtin_msa_srai_b:
2883   case Mips::BI__builtin_msa_srari_b:
2884   case Mips::BI__builtin_msa_srli_b:
2885   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2886   case Mips::BI__builtin_msa_binsli_b:
2887   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2888   // These intrinsics take an unsigned 4 bit immediate.
2889   case Mips::BI__builtin_msa_bclri_h:
2890   case Mips::BI__builtin_msa_bnegi_h:
2891   case Mips::BI__builtin_msa_bseti_h:
2892   case Mips::BI__builtin_msa_sat_s_h:
2893   case Mips::BI__builtin_msa_sat_u_h:
2894   case Mips::BI__builtin_msa_slli_h:
2895   case Mips::BI__builtin_msa_srai_h:
2896   case Mips::BI__builtin_msa_srari_h:
2897   case Mips::BI__builtin_msa_srli_h:
2898   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2899   case Mips::BI__builtin_msa_binsli_h:
2900   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2901   // These intrinsics take an unsigned 5 bit immediate.
2902   // The first block of intrinsics actually have an unsigned 5 bit field,
2903   // not a df/n field.
2904   case Mips::BI__builtin_msa_cfcmsa:
2905   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
2906   case Mips::BI__builtin_msa_clei_u_b:
2907   case Mips::BI__builtin_msa_clei_u_h:
2908   case Mips::BI__builtin_msa_clei_u_w:
2909   case Mips::BI__builtin_msa_clei_u_d:
2910   case Mips::BI__builtin_msa_clti_u_b:
2911   case Mips::BI__builtin_msa_clti_u_h:
2912   case Mips::BI__builtin_msa_clti_u_w:
2913   case Mips::BI__builtin_msa_clti_u_d:
2914   case Mips::BI__builtin_msa_maxi_u_b:
2915   case Mips::BI__builtin_msa_maxi_u_h:
2916   case Mips::BI__builtin_msa_maxi_u_w:
2917   case Mips::BI__builtin_msa_maxi_u_d:
2918   case Mips::BI__builtin_msa_mini_u_b:
2919   case Mips::BI__builtin_msa_mini_u_h:
2920   case Mips::BI__builtin_msa_mini_u_w:
2921   case Mips::BI__builtin_msa_mini_u_d:
2922   case Mips::BI__builtin_msa_addvi_b:
2923   case Mips::BI__builtin_msa_addvi_h:
2924   case Mips::BI__builtin_msa_addvi_w:
2925   case Mips::BI__builtin_msa_addvi_d:
2926   case Mips::BI__builtin_msa_bclri_w:
2927   case Mips::BI__builtin_msa_bnegi_w:
2928   case Mips::BI__builtin_msa_bseti_w:
2929   case Mips::BI__builtin_msa_sat_s_w:
2930   case Mips::BI__builtin_msa_sat_u_w:
2931   case Mips::BI__builtin_msa_slli_w:
2932   case Mips::BI__builtin_msa_srai_w:
2933   case Mips::BI__builtin_msa_srari_w:
2934   case Mips::BI__builtin_msa_srli_w:
2935   case Mips::BI__builtin_msa_srlri_w:
2936   case Mips::BI__builtin_msa_subvi_b:
2937   case Mips::BI__builtin_msa_subvi_h:
2938   case Mips::BI__builtin_msa_subvi_w:
2939   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2940   case Mips::BI__builtin_msa_binsli_w:
2941   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2942   // These intrinsics take an unsigned 6 bit immediate.
2943   case Mips::BI__builtin_msa_bclri_d:
2944   case Mips::BI__builtin_msa_bnegi_d:
2945   case Mips::BI__builtin_msa_bseti_d:
2946   case Mips::BI__builtin_msa_sat_s_d:
2947   case Mips::BI__builtin_msa_sat_u_d:
2948   case Mips::BI__builtin_msa_slli_d:
2949   case Mips::BI__builtin_msa_srai_d:
2950   case Mips::BI__builtin_msa_srari_d:
2951   case Mips::BI__builtin_msa_srli_d:
2952   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2953   case Mips::BI__builtin_msa_binsli_d:
2954   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2955   // These intrinsics take a signed 5 bit immediate.
2956   case Mips::BI__builtin_msa_ceqi_b:
2957   case Mips::BI__builtin_msa_ceqi_h:
2958   case Mips::BI__builtin_msa_ceqi_w:
2959   case Mips::BI__builtin_msa_ceqi_d:
2960   case Mips::BI__builtin_msa_clti_s_b:
2961   case Mips::BI__builtin_msa_clti_s_h:
2962   case Mips::BI__builtin_msa_clti_s_w:
2963   case Mips::BI__builtin_msa_clti_s_d:
2964   case Mips::BI__builtin_msa_clei_s_b:
2965   case Mips::BI__builtin_msa_clei_s_h:
2966   case Mips::BI__builtin_msa_clei_s_w:
2967   case Mips::BI__builtin_msa_clei_s_d:
2968   case Mips::BI__builtin_msa_maxi_s_b:
2969   case Mips::BI__builtin_msa_maxi_s_h:
2970   case Mips::BI__builtin_msa_maxi_s_w:
2971   case Mips::BI__builtin_msa_maxi_s_d:
2972   case Mips::BI__builtin_msa_mini_s_b:
2973   case Mips::BI__builtin_msa_mini_s_h:
2974   case Mips::BI__builtin_msa_mini_s_w:
2975   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2976   // These intrinsics take an unsigned 8 bit immediate.
2977   case Mips::BI__builtin_msa_andi_b:
2978   case Mips::BI__builtin_msa_nori_b:
2979   case Mips::BI__builtin_msa_ori_b:
2980   case Mips::BI__builtin_msa_shf_b:
2981   case Mips::BI__builtin_msa_shf_h:
2982   case Mips::BI__builtin_msa_shf_w:
2983   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2984   case Mips::BI__builtin_msa_bseli_b:
2985   case Mips::BI__builtin_msa_bmnzi_b:
2986   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2987   // df/n format
2988   // These intrinsics take an unsigned 4 bit immediate.
2989   case Mips::BI__builtin_msa_copy_s_b:
2990   case Mips::BI__builtin_msa_copy_u_b:
2991   case Mips::BI__builtin_msa_insve_b:
2992   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2993   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2994   // These intrinsics take an unsigned 3 bit immediate.
2995   case Mips::BI__builtin_msa_copy_s_h:
2996   case Mips::BI__builtin_msa_copy_u_h:
2997   case Mips::BI__builtin_msa_insve_h:
2998   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2999   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3000   // These intrinsics take an unsigned 2 bit immediate.
3001   case Mips::BI__builtin_msa_copy_s_w:
3002   case Mips::BI__builtin_msa_copy_u_w:
3003   case Mips::BI__builtin_msa_insve_w:
3004   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3005   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3006   // These intrinsics take an unsigned 1 bit immediate.
3007   case Mips::BI__builtin_msa_copy_s_d:
3008   case Mips::BI__builtin_msa_copy_u_d:
3009   case Mips::BI__builtin_msa_insve_d:
3010   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3011   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3012   // Memory offsets and immediate loads.
3013   // These intrinsics take a signed 10 bit immediate.
3014   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3015   case Mips::BI__builtin_msa_ldi_h:
3016   case Mips::BI__builtin_msa_ldi_w:
3017   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3018   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3019   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3020   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3021   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3022   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3023   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3024   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3025   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3026   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3027   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3028   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3029   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3030   }
3031 
3032   if (!m)
3033     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3034 
3035   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3036          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3037 }
3038 
3039 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3040                                        CallExpr *TheCall) {
3041   unsigned i = 0, l = 0, u = 0;
3042   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3043                       BuiltinID == PPC::BI__builtin_divdeu ||
3044                       BuiltinID == PPC::BI__builtin_bpermd;
3045   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3046   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3047                        BuiltinID == PPC::BI__builtin_divweu ||
3048                        BuiltinID == PPC::BI__builtin_divde ||
3049                        BuiltinID == PPC::BI__builtin_divdeu;
3050 
3051   if (Is64BitBltin && !IsTarget64Bit)
3052     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3053            << TheCall->getSourceRange();
3054 
3055   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3056       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3057     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3058            << TheCall->getSourceRange();
3059 
3060   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3061     if (!TI.hasFeature("vsx"))
3062       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3063              << TheCall->getSourceRange();
3064     return false;
3065   };
3066 
3067   switch (BuiltinID) {
3068   default: return false;
3069   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3070   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3071     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3072            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3073   case PPC::BI__builtin_altivec_dss:
3074     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3075   case PPC::BI__builtin_tbegin:
3076   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3077   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3078   case PPC::BI__builtin_tabortwc:
3079   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3080   case PPC::BI__builtin_tabortwci:
3081   case PPC::BI__builtin_tabortdci:
3082     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3083            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3084   case PPC::BI__builtin_altivec_dst:
3085   case PPC::BI__builtin_altivec_dstt:
3086   case PPC::BI__builtin_altivec_dstst:
3087   case PPC::BI__builtin_altivec_dststt:
3088     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3089   case PPC::BI__builtin_vsx_xxpermdi:
3090   case PPC::BI__builtin_vsx_xxsldwi:
3091     return SemaBuiltinVSX(TheCall);
3092   case PPC::BI__builtin_unpack_vector_int128:
3093     return SemaVSXCheck(TheCall) ||
3094            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3095   case PPC::BI__builtin_pack_vector_int128:
3096     return SemaVSXCheck(TheCall);
3097   }
3098   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3099 }
3100 
3101 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3102                                           CallExpr *TheCall) {
3103   // position of memory order and scope arguments in the builtin
3104   unsigned OrderIndex, ScopeIndex;
3105   switch (BuiltinID) {
3106   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3107   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3108   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3109   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3110     OrderIndex = 2;
3111     ScopeIndex = 3;
3112     break;
3113   case AMDGPU::BI__builtin_amdgcn_fence:
3114     OrderIndex = 0;
3115     ScopeIndex = 1;
3116     break;
3117   default:
3118     return false;
3119   }
3120 
3121   ExprResult Arg = TheCall->getArg(OrderIndex);
3122   auto ArgExpr = Arg.get();
3123   Expr::EvalResult ArgResult;
3124 
3125   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3126     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3127            << ArgExpr->getType();
3128   int ord = ArgResult.Val.getInt().getZExtValue();
3129 
3130   // Check valididty of memory ordering as per C11 / C++11's memody model.
3131   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3132   case llvm::AtomicOrderingCABI::acquire:
3133   case llvm::AtomicOrderingCABI::release:
3134   case llvm::AtomicOrderingCABI::acq_rel:
3135   case llvm::AtomicOrderingCABI::seq_cst:
3136     break;
3137   default: {
3138     return Diag(ArgExpr->getBeginLoc(),
3139                 diag::warn_atomic_op_has_invalid_memory_order)
3140            << ArgExpr->getSourceRange();
3141   }
3142   }
3143 
3144   Arg = TheCall->getArg(ScopeIndex);
3145   ArgExpr = Arg.get();
3146   Expr::EvalResult ArgResult1;
3147   // Check that sync scope is a constant literal
3148   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen,
3149                                        Context))
3150     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3151            << ArgExpr->getType();
3152 
3153   return false;
3154 }
3155 
3156 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3157                                            CallExpr *TheCall) {
3158   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3159     Expr *Arg = TheCall->getArg(0);
3160     llvm::APSInt AbortCode(32);
3161     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3162         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3163       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3164              << Arg->getSourceRange();
3165   }
3166 
3167   // For intrinsics which take an immediate value as part of the instruction,
3168   // range check them here.
3169   unsigned i = 0, l = 0, u = 0;
3170   switch (BuiltinID) {
3171   default: return false;
3172   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3173   case SystemZ::BI__builtin_s390_verimb:
3174   case SystemZ::BI__builtin_s390_verimh:
3175   case SystemZ::BI__builtin_s390_verimf:
3176   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3177   case SystemZ::BI__builtin_s390_vfaeb:
3178   case SystemZ::BI__builtin_s390_vfaeh:
3179   case SystemZ::BI__builtin_s390_vfaef:
3180   case SystemZ::BI__builtin_s390_vfaebs:
3181   case SystemZ::BI__builtin_s390_vfaehs:
3182   case SystemZ::BI__builtin_s390_vfaefs:
3183   case SystemZ::BI__builtin_s390_vfaezb:
3184   case SystemZ::BI__builtin_s390_vfaezh:
3185   case SystemZ::BI__builtin_s390_vfaezf:
3186   case SystemZ::BI__builtin_s390_vfaezbs:
3187   case SystemZ::BI__builtin_s390_vfaezhs:
3188   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3189   case SystemZ::BI__builtin_s390_vfisb:
3190   case SystemZ::BI__builtin_s390_vfidb:
3191     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3192            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3193   case SystemZ::BI__builtin_s390_vftcisb:
3194   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3195   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3196   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3197   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3198   case SystemZ::BI__builtin_s390_vstrcb:
3199   case SystemZ::BI__builtin_s390_vstrch:
3200   case SystemZ::BI__builtin_s390_vstrcf:
3201   case SystemZ::BI__builtin_s390_vstrczb:
3202   case SystemZ::BI__builtin_s390_vstrczh:
3203   case SystemZ::BI__builtin_s390_vstrczf:
3204   case SystemZ::BI__builtin_s390_vstrcbs:
3205   case SystemZ::BI__builtin_s390_vstrchs:
3206   case SystemZ::BI__builtin_s390_vstrcfs:
3207   case SystemZ::BI__builtin_s390_vstrczbs:
3208   case SystemZ::BI__builtin_s390_vstrczhs:
3209   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3210   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3211   case SystemZ::BI__builtin_s390_vfminsb:
3212   case SystemZ::BI__builtin_s390_vfmaxsb:
3213   case SystemZ::BI__builtin_s390_vfmindb:
3214   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3215   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3216   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3217   }
3218   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3219 }
3220 
3221 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3222 /// This checks that the target supports __builtin_cpu_supports and
3223 /// that the string argument is constant and valid.
3224 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3225                                    CallExpr *TheCall) {
3226   Expr *Arg = TheCall->getArg(0);
3227 
3228   // Check if the argument is a string literal.
3229   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3230     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3231            << Arg->getSourceRange();
3232 
3233   // Check the contents of the string.
3234   StringRef Feature =
3235       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3236   if (!TI.validateCpuSupports(Feature))
3237     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3238            << Arg->getSourceRange();
3239   return false;
3240 }
3241 
3242 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3243 /// This checks that the target supports __builtin_cpu_is and
3244 /// that the string argument is constant and valid.
3245 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3246   Expr *Arg = TheCall->getArg(0);
3247 
3248   // Check if the argument is a string literal.
3249   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3250     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3251            << Arg->getSourceRange();
3252 
3253   // Check the contents of the string.
3254   StringRef Feature =
3255       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3256   if (!TI.validateCpuIs(Feature))
3257     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3258            << Arg->getSourceRange();
3259   return false;
3260 }
3261 
3262 // Check if the rounding mode is legal.
3263 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3264   // Indicates if this instruction has rounding control or just SAE.
3265   bool HasRC = false;
3266 
3267   unsigned ArgNum = 0;
3268   switch (BuiltinID) {
3269   default:
3270     return false;
3271   case X86::BI__builtin_ia32_vcvttsd2si32:
3272   case X86::BI__builtin_ia32_vcvttsd2si64:
3273   case X86::BI__builtin_ia32_vcvttsd2usi32:
3274   case X86::BI__builtin_ia32_vcvttsd2usi64:
3275   case X86::BI__builtin_ia32_vcvttss2si32:
3276   case X86::BI__builtin_ia32_vcvttss2si64:
3277   case X86::BI__builtin_ia32_vcvttss2usi32:
3278   case X86::BI__builtin_ia32_vcvttss2usi64:
3279     ArgNum = 1;
3280     break;
3281   case X86::BI__builtin_ia32_maxpd512:
3282   case X86::BI__builtin_ia32_maxps512:
3283   case X86::BI__builtin_ia32_minpd512:
3284   case X86::BI__builtin_ia32_minps512:
3285     ArgNum = 2;
3286     break;
3287   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3288   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3289   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3290   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3291   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3292   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3293   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3294   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3295   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3296   case X86::BI__builtin_ia32_exp2pd_mask:
3297   case X86::BI__builtin_ia32_exp2ps_mask:
3298   case X86::BI__builtin_ia32_getexppd512_mask:
3299   case X86::BI__builtin_ia32_getexpps512_mask:
3300   case X86::BI__builtin_ia32_rcp28pd_mask:
3301   case X86::BI__builtin_ia32_rcp28ps_mask:
3302   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3303   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3304   case X86::BI__builtin_ia32_vcomisd:
3305   case X86::BI__builtin_ia32_vcomiss:
3306   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3307     ArgNum = 3;
3308     break;
3309   case X86::BI__builtin_ia32_cmppd512_mask:
3310   case X86::BI__builtin_ia32_cmpps512_mask:
3311   case X86::BI__builtin_ia32_cmpsd_mask:
3312   case X86::BI__builtin_ia32_cmpss_mask:
3313   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3314   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3315   case X86::BI__builtin_ia32_getexpss128_round_mask:
3316   case X86::BI__builtin_ia32_getmantpd512_mask:
3317   case X86::BI__builtin_ia32_getmantps512_mask:
3318   case X86::BI__builtin_ia32_maxsd_round_mask:
3319   case X86::BI__builtin_ia32_maxss_round_mask:
3320   case X86::BI__builtin_ia32_minsd_round_mask:
3321   case X86::BI__builtin_ia32_minss_round_mask:
3322   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3323   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3324   case X86::BI__builtin_ia32_reducepd512_mask:
3325   case X86::BI__builtin_ia32_reduceps512_mask:
3326   case X86::BI__builtin_ia32_rndscalepd_mask:
3327   case X86::BI__builtin_ia32_rndscaleps_mask:
3328   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3329   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3330     ArgNum = 4;
3331     break;
3332   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3333   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3334   case X86::BI__builtin_ia32_fixupimmps512_mask:
3335   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3336   case X86::BI__builtin_ia32_fixupimmsd_mask:
3337   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3338   case X86::BI__builtin_ia32_fixupimmss_mask:
3339   case X86::BI__builtin_ia32_fixupimmss_maskz:
3340   case X86::BI__builtin_ia32_getmantsd_round_mask:
3341   case X86::BI__builtin_ia32_getmantss_round_mask:
3342   case X86::BI__builtin_ia32_rangepd512_mask:
3343   case X86::BI__builtin_ia32_rangeps512_mask:
3344   case X86::BI__builtin_ia32_rangesd128_round_mask:
3345   case X86::BI__builtin_ia32_rangess128_round_mask:
3346   case X86::BI__builtin_ia32_reducesd_mask:
3347   case X86::BI__builtin_ia32_reducess_mask:
3348   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3349   case X86::BI__builtin_ia32_rndscaless_round_mask:
3350     ArgNum = 5;
3351     break;
3352   case X86::BI__builtin_ia32_vcvtsd2si64:
3353   case X86::BI__builtin_ia32_vcvtsd2si32:
3354   case X86::BI__builtin_ia32_vcvtsd2usi32:
3355   case X86::BI__builtin_ia32_vcvtsd2usi64:
3356   case X86::BI__builtin_ia32_vcvtss2si32:
3357   case X86::BI__builtin_ia32_vcvtss2si64:
3358   case X86::BI__builtin_ia32_vcvtss2usi32:
3359   case X86::BI__builtin_ia32_vcvtss2usi64:
3360   case X86::BI__builtin_ia32_sqrtpd512:
3361   case X86::BI__builtin_ia32_sqrtps512:
3362     ArgNum = 1;
3363     HasRC = true;
3364     break;
3365   case X86::BI__builtin_ia32_addpd512:
3366   case X86::BI__builtin_ia32_addps512:
3367   case X86::BI__builtin_ia32_divpd512:
3368   case X86::BI__builtin_ia32_divps512:
3369   case X86::BI__builtin_ia32_mulpd512:
3370   case X86::BI__builtin_ia32_mulps512:
3371   case X86::BI__builtin_ia32_subpd512:
3372   case X86::BI__builtin_ia32_subps512:
3373   case X86::BI__builtin_ia32_cvtsi2sd64:
3374   case X86::BI__builtin_ia32_cvtsi2ss32:
3375   case X86::BI__builtin_ia32_cvtsi2ss64:
3376   case X86::BI__builtin_ia32_cvtusi2sd64:
3377   case X86::BI__builtin_ia32_cvtusi2ss32:
3378   case X86::BI__builtin_ia32_cvtusi2ss64:
3379     ArgNum = 2;
3380     HasRC = true;
3381     break;
3382   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3383   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3384   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3385   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3386   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3387   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3388   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3389   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3390   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3391   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3392   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3393   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3394   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3395   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3396   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3397     ArgNum = 3;
3398     HasRC = true;
3399     break;
3400   case X86::BI__builtin_ia32_addss_round_mask:
3401   case X86::BI__builtin_ia32_addsd_round_mask:
3402   case X86::BI__builtin_ia32_divss_round_mask:
3403   case X86::BI__builtin_ia32_divsd_round_mask:
3404   case X86::BI__builtin_ia32_mulss_round_mask:
3405   case X86::BI__builtin_ia32_mulsd_round_mask:
3406   case X86::BI__builtin_ia32_subss_round_mask:
3407   case X86::BI__builtin_ia32_subsd_round_mask:
3408   case X86::BI__builtin_ia32_scalefpd512_mask:
3409   case X86::BI__builtin_ia32_scalefps512_mask:
3410   case X86::BI__builtin_ia32_scalefsd_round_mask:
3411   case X86::BI__builtin_ia32_scalefss_round_mask:
3412   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3413   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3414   case X86::BI__builtin_ia32_sqrtss_round_mask:
3415   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3416   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3417   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3418   case X86::BI__builtin_ia32_vfmaddss3_mask:
3419   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3420   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3421   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3422   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3423   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3424   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3425   case X86::BI__builtin_ia32_vfmaddps512_mask:
3426   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3427   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3428   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3429   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3430   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3431   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3432   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3433   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3434   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3435   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3436   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3437     ArgNum = 4;
3438     HasRC = true;
3439     break;
3440   }
3441 
3442   llvm::APSInt Result;
3443 
3444   // We can't check the value of a dependent argument.
3445   Expr *Arg = TheCall->getArg(ArgNum);
3446   if (Arg->isTypeDependent() || Arg->isValueDependent())
3447     return false;
3448 
3449   // Check constant-ness first.
3450   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3451     return true;
3452 
3453   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3454   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3455   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3456   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3457   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3458       Result == 8/*ROUND_NO_EXC*/ ||
3459       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3460       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3461     return false;
3462 
3463   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3464          << Arg->getSourceRange();
3465 }
3466 
3467 // Check if the gather/scatter scale is legal.
3468 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3469                                              CallExpr *TheCall) {
3470   unsigned ArgNum = 0;
3471   switch (BuiltinID) {
3472   default:
3473     return false;
3474   case X86::BI__builtin_ia32_gatherpfdpd:
3475   case X86::BI__builtin_ia32_gatherpfdps:
3476   case X86::BI__builtin_ia32_gatherpfqpd:
3477   case X86::BI__builtin_ia32_gatherpfqps:
3478   case X86::BI__builtin_ia32_scatterpfdpd:
3479   case X86::BI__builtin_ia32_scatterpfdps:
3480   case X86::BI__builtin_ia32_scatterpfqpd:
3481   case X86::BI__builtin_ia32_scatterpfqps:
3482     ArgNum = 3;
3483     break;
3484   case X86::BI__builtin_ia32_gatherd_pd:
3485   case X86::BI__builtin_ia32_gatherd_pd256:
3486   case X86::BI__builtin_ia32_gatherq_pd:
3487   case X86::BI__builtin_ia32_gatherq_pd256:
3488   case X86::BI__builtin_ia32_gatherd_ps:
3489   case X86::BI__builtin_ia32_gatherd_ps256:
3490   case X86::BI__builtin_ia32_gatherq_ps:
3491   case X86::BI__builtin_ia32_gatherq_ps256:
3492   case X86::BI__builtin_ia32_gatherd_q:
3493   case X86::BI__builtin_ia32_gatherd_q256:
3494   case X86::BI__builtin_ia32_gatherq_q:
3495   case X86::BI__builtin_ia32_gatherq_q256:
3496   case X86::BI__builtin_ia32_gatherd_d:
3497   case X86::BI__builtin_ia32_gatherd_d256:
3498   case X86::BI__builtin_ia32_gatherq_d:
3499   case X86::BI__builtin_ia32_gatherq_d256:
3500   case X86::BI__builtin_ia32_gather3div2df:
3501   case X86::BI__builtin_ia32_gather3div2di:
3502   case X86::BI__builtin_ia32_gather3div4df:
3503   case X86::BI__builtin_ia32_gather3div4di:
3504   case X86::BI__builtin_ia32_gather3div4sf:
3505   case X86::BI__builtin_ia32_gather3div4si:
3506   case X86::BI__builtin_ia32_gather3div8sf:
3507   case X86::BI__builtin_ia32_gather3div8si:
3508   case X86::BI__builtin_ia32_gather3siv2df:
3509   case X86::BI__builtin_ia32_gather3siv2di:
3510   case X86::BI__builtin_ia32_gather3siv4df:
3511   case X86::BI__builtin_ia32_gather3siv4di:
3512   case X86::BI__builtin_ia32_gather3siv4sf:
3513   case X86::BI__builtin_ia32_gather3siv4si:
3514   case X86::BI__builtin_ia32_gather3siv8sf:
3515   case X86::BI__builtin_ia32_gather3siv8si:
3516   case X86::BI__builtin_ia32_gathersiv8df:
3517   case X86::BI__builtin_ia32_gathersiv16sf:
3518   case X86::BI__builtin_ia32_gatherdiv8df:
3519   case X86::BI__builtin_ia32_gatherdiv16sf:
3520   case X86::BI__builtin_ia32_gathersiv8di:
3521   case X86::BI__builtin_ia32_gathersiv16si:
3522   case X86::BI__builtin_ia32_gatherdiv8di:
3523   case X86::BI__builtin_ia32_gatherdiv16si:
3524   case X86::BI__builtin_ia32_scatterdiv2df:
3525   case X86::BI__builtin_ia32_scatterdiv2di:
3526   case X86::BI__builtin_ia32_scatterdiv4df:
3527   case X86::BI__builtin_ia32_scatterdiv4di:
3528   case X86::BI__builtin_ia32_scatterdiv4sf:
3529   case X86::BI__builtin_ia32_scatterdiv4si:
3530   case X86::BI__builtin_ia32_scatterdiv8sf:
3531   case X86::BI__builtin_ia32_scatterdiv8si:
3532   case X86::BI__builtin_ia32_scattersiv2df:
3533   case X86::BI__builtin_ia32_scattersiv2di:
3534   case X86::BI__builtin_ia32_scattersiv4df:
3535   case X86::BI__builtin_ia32_scattersiv4di:
3536   case X86::BI__builtin_ia32_scattersiv4sf:
3537   case X86::BI__builtin_ia32_scattersiv4si:
3538   case X86::BI__builtin_ia32_scattersiv8sf:
3539   case X86::BI__builtin_ia32_scattersiv8si:
3540   case X86::BI__builtin_ia32_scattersiv8df:
3541   case X86::BI__builtin_ia32_scattersiv16sf:
3542   case X86::BI__builtin_ia32_scatterdiv8df:
3543   case X86::BI__builtin_ia32_scatterdiv16sf:
3544   case X86::BI__builtin_ia32_scattersiv8di:
3545   case X86::BI__builtin_ia32_scattersiv16si:
3546   case X86::BI__builtin_ia32_scatterdiv8di:
3547   case X86::BI__builtin_ia32_scatterdiv16si:
3548     ArgNum = 4;
3549     break;
3550   }
3551 
3552   llvm::APSInt Result;
3553 
3554   // We can't check the value of a dependent argument.
3555   Expr *Arg = TheCall->getArg(ArgNum);
3556   if (Arg->isTypeDependent() || Arg->isValueDependent())
3557     return false;
3558 
3559   // Check constant-ness first.
3560   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3561     return true;
3562 
3563   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3564     return false;
3565 
3566   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3567          << Arg->getSourceRange();
3568 }
3569 
3570 static bool isX86_32Builtin(unsigned BuiltinID) {
3571   // These builtins only work on x86-32 targets.
3572   switch (BuiltinID) {
3573   case X86::BI__builtin_ia32_readeflags_u32:
3574   case X86::BI__builtin_ia32_writeeflags_u32:
3575     return true;
3576   }
3577 
3578   return false;
3579 }
3580 
3581 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3582                                        CallExpr *TheCall) {
3583   if (BuiltinID == X86::BI__builtin_cpu_supports)
3584     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3585 
3586   if (BuiltinID == X86::BI__builtin_cpu_is)
3587     return SemaBuiltinCpuIs(*this, TI, TheCall);
3588 
3589   // Check for 32-bit only builtins on a 64-bit target.
3590   const llvm::Triple &TT = TI.getTriple();
3591   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3592     return Diag(TheCall->getCallee()->getBeginLoc(),
3593                 diag::err_32_bit_builtin_64_bit_tgt);
3594 
3595   // If the intrinsic has rounding or SAE make sure its valid.
3596   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3597     return true;
3598 
3599   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3600   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3601     return true;
3602 
3603   // For intrinsics which take an immediate value as part of the instruction,
3604   // range check them here.
3605   int i = 0, l = 0, u = 0;
3606   switch (BuiltinID) {
3607   default:
3608     return false;
3609   case X86::BI__builtin_ia32_vec_ext_v2si:
3610   case X86::BI__builtin_ia32_vec_ext_v2di:
3611   case X86::BI__builtin_ia32_vextractf128_pd256:
3612   case X86::BI__builtin_ia32_vextractf128_ps256:
3613   case X86::BI__builtin_ia32_vextractf128_si256:
3614   case X86::BI__builtin_ia32_extract128i256:
3615   case X86::BI__builtin_ia32_extractf64x4_mask:
3616   case X86::BI__builtin_ia32_extracti64x4_mask:
3617   case X86::BI__builtin_ia32_extractf32x8_mask:
3618   case X86::BI__builtin_ia32_extracti32x8_mask:
3619   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3620   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3621   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3622   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3623     i = 1; l = 0; u = 1;
3624     break;
3625   case X86::BI__builtin_ia32_vec_set_v2di:
3626   case X86::BI__builtin_ia32_vinsertf128_pd256:
3627   case X86::BI__builtin_ia32_vinsertf128_ps256:
3628   case X86::BI__builtin_ia32_vinsertf128_si256:
3629   case X86::BI__builtin_ia32_insert128i256:
3630   case X86::BI__builtin_ia32_insertf32x8:
3631   case X86::BI__builtin_ia32_inserti32x8:
3632   case X86::BI__builtin_ia32_insertf64x4:
3633   case X86::BI__builtin_ia32_inserti64x4:
3634   case X86::BI__builtin_ia32_insertf64x2_256:
3635   case X86::BI__builtin_ia32_inserti64x2_256:
3636   case X86::BI__builtin_ia32_insertf32x4_256:
3637   case X86::BI__builtin_ia32_inserti32x4_256:
3638     i = 2; l = 0; u = 1;
3639     break;
3640   case X86::BI__builtin_ia32_vpermilpd:
3641   case X86::BI__builtin_ia32_vec_ext_v4hi:
3642   case X86::BI__builtin_ia32_vec_ext_v4si:
3643   case X86::BI__builtin_ia32_vec_ext_v4sf:
3644   case X86::BI__builtin_ia32_vec_ext_v4di:
3645   case X86::BI__builtin_ia32_extractf32x4_mask:
3646   case X86::BI__builtin_ia32_extracti32x4_mask:
3647   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3648   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3649     i = 1; l = 0; u = 3;
3650     break;
3651   case X86::BI_mm_prefetch:
3652   case X86::BI__builtin_ia32_vec_ext_v8hi:
3653   case X86::BI__builtin_ia32_vec_ext_v8si:
3654     i = 1; l = 0; u = 7;
3655     break;
3656   case X86::BI__builtin_ia32_sha1rnds4:
3657   case X86::BI__builtin_ia32_blendpd:
3658   case X86::BI__builtin_ia32_shufpd:
3659   case X86::BI__builtin_ia32_vec_set_v4hi:
3660   case X86::BI__builtin_ia32_vec_set_v4si:
3661   case X86::BI__builtin_ia32_vec_set_v4di:
3662   case X86::BI__builtin_ia32_shuf_f32x4_256:
3663   case X86::BI__builtin_ia32_shuf_f64x2_256:
3664   case X86::BI__builtin_ia32_shuf_i32x4_256:
3665   case X86::BI__builtin_ia32_shuf_i64x2_256:
3666   case X86::BI__builtin_ia32_insertf64x2_512:
3667   case X86::BI__builtin_ia32_inserti64x2_512:
3668   case X86::BI__builtin_ia32_insertf32x4:
3669   case X86::BI__builtin_ia32_inserti32x4:
3670     i = 2; l = 0; u = 3;
3671     break;
3672   case X86::BI__builtin_ia32_vpermil2pd:
3673   case X86::BI__builtin_ia32_vpermil2pd256:
3674   case X86::BI__builtin_ia32_vpermil2ps:
3675   case X86::BI__builtin_ia32_vpermil2ps256:
3676     i = 3; l = 0; u = 3;
3677     break;
3678   case X86::BI__builtin_ia32_cmpb128_mask:
3679   case X86::BI__builtin_ia32_cmpw128_mask:
3680   case X86::BI__builtin_ia32_cmpd128_mask:
3681   case X86::BI__builtin_ia32_cmpq128_mask:
3682   case X86::BI__builtin_ia32_cmpb256_mask:
3683   case X86::BI__builtin_ia32_cmpw256_mask:
3684   case X86::BI__builtin_ia32_cmpd256_mask:
3685   case X86::BI__builtin_ia32_cmpq256_mask:
3686   case X86::BI__builtin_ia32_cmpb512_mask:
3687   case X86::BI__builtin_ia32_cmpw512_mask:
3688   case X86::BI__builtin_ia32_cmpd512_mask:
3689   case X86::BI__builtin_ia32_cmpq512_mask:
3690   case X86::BI__builtin_ia32_ucmpb128_mask:
3691   case X86::BI__builtin_ia32_ucmpw128_mask:
3692   case X86::BI__builtin_ia32_ucmpd128_mask:
3693   case X86::BI__builtin_ia32_ucmpq128_mask:
3694   case X86::BI__builtin_ia32_ucmpb256_mask:
3695   case X86::BI__builtin_ia32_ucmpw256_mask:
3696   case X86::BI__builtin_ia32_ucmpd256_mask:
3697   case X86::BI__builtin_ia32_ucmpq256_mask:
3698   case X86::BI__builtin_ia32_ucmpb512_mask:
3699   case X86::BI__builtin_ia32_ucmpw512_mask:
3700   case X86::BI__builtin_ia32_ucmpd512_mask:
3701   case X86::BI__builtin_ia32_ucmpq512_mask:
3702   case X86::BI__builtin_ia32_vpcomub:
3703   case X86::BI__builtin_ia32_vpcomuw:
3704   case X86::BI__builtin_ia32_vpcomud:
3705   case X86::BI__builtin_ia32_vpcomuq:
3706   case X86::BI__builtin_ia32_vpcomb:
3707   case X86::BI__builtin_ia32_vpcomw:
3708   case X86::BI__builtin_ia32_vpcomd:
3709   case X86::BI__builtin_ia32_vpcomq:
3710   case X86::BI__builtin_ia32_vec_set_v8hi:
3711   case X86::BI__builtin_ia32_vec_set_v8si:
3712     i = 2; l = 0; u = 7;
3713     break;
3714   case X86::BI__builtin_ia32_vpermilpd256:
3715   case X86::BI__builtin_ia32_roundps:
3716   case X86::BI__builtin_ia32_roundpd:
3717   case X86::BI__builtin_ia32_roundps256:
3718   case X86::BI__builtin_ia32_roundpd256:
3719   case X86::BI__builtin_ia32_getmantpd128_mask:
3720   case X86::BI__builtin_ia32_getmantpd256_mask:
3721   case X86::BI__builtin_ia32_getmantps128_mask:
3722   case X86::BI__builtin_ia32_getmantps256_mask:
3723   case X86::BI__builtin_ia32_getmantpd512_mask:
3724   case X86::BI__builtin_ia32_getmantps512_mask:
3725   case X86::BI__builtin_ia32_vec_ext_v16qi:
3726   case X86::BI__builtin_ia32_vec_ext_v16hi:
3727     i = 1; l = 0; u = 15;
3728     break;
3729   case X86::BI__builtin_ia32_pblendd128:
3730   case X86::BI__builtin_ia32_blendps:
3731   case X86::BI__builtin_ia32_blendpd256:
3732   case X86::BI__builtin_ia32_shufpd256:
3733   case X86::BI__builtin_ia32_roundss:
3734   case X86::BI__builtin_ia32_roundsd:
3735   case X86::BI__builtin_ia32_rangepd128_mask:
3736   case X86::BI__builtin_ia32_rangepd256_mask:
3737   case X86::BI__builtin_ia32_rangepd512_mask:
3738   case X86::BI__builtin_ia32_rangeps128_mask:
3739   case X86::BI__builtin_ia32_rangeps256_mask:
3740   case X86::BI__builtin_ia32_rangeps512_mask:
3741   case X86::BI__builtin_ia32_getmantsd_round_mask:
3742   case X86::BI__builtin_ia32_getmantss_round_mask:
3743   case X86::BI__builtin_ia32_vec_set_v16qi:
3744   case X86::BI__builtin_ia32_vec_set_v16hi:
3745     i = 2; l = 0; u = 15;
3746     break;
3747   case X86::BI__builtin_ia32_vec_ext_v32qi:
3748     i = 1; l = 0; u = 31;
3749     break;
3750   case X86::BI__builtin_ia32_cmpps:
3751   case X86::BI__builtin_ia32_cmpss:
3752   case X86::BI__builtin_ia32_cmppd:
3753   case X86::BI__builtin_ia32_cmpsd:
3754   case X86::BI__builtin_ia32_cmpps256:
3755   case X86::BI__builtin_ia32_cmppd256:
3756   case X86::BI__builtin_ia32_cmpps128_mask:
3757   case X86::BI__builtin_ia32_cmppd128_mask:
3758   case X86::BI__builtin_ia32_cmpps256_mask:
3759   case X86::BI__builtin_ia32_cmppd256_mask:
3760   case X86::BI__builtin_ia32_cmpps512_mask:
3761   case X86::BI__builtin_ia32_cmppd512_mask:
3762   case X86::BI__builtin_ia32_cmpsd_mask:
3763   case X86::BI__builtin_ia32_cmpss_mask:
3764   case X86::BI__builtin_ia32_vec_set_v32qi:
3765     i = 2; l = 0; u = 31;
3766     break;
3767   case X86::BI__builtin_ia32_permdf256:
3768   case X86::BI__builtin_ia32_permdi256:
3769   case X86::BI__builtin_ia32_permdf512:
3770   case X86::BI__builtin_ia32_permdi512:
3771   case X86::BI__builtin_ia32_vpermilps:
3772   case X86::BI__builtin_ia32_vpermilps256:
3773   case X86::BI__builtin_ia32_vpermilpd512:
3774   case X86::BI__builtin_ia32_vpermilps512:
3775   case X86::BI__builtin_ia32_pshufd:
3776   case X86::BI__builtin_ia32_pshufd256:
3777   case X86::BI__builtin_ia32_pshufd512:
3778   case X86::BI__builtin_ia32_pshufhw:
3779   case X86::BI__builtin_ia32_pshufhw256:
3780   case X86::BI__builtin_ia32_pshufhw512:
3781   case X86::BI__builtin_ia32_pshuflw:
3782   case X86::BI__builtin_ia32_pshuflw256:
3783   case X86::BI__builtin_ia32_pshuflw512:
3784   case X86::BI__builtin_ia32_vcvtps2ph:
3785   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3786   case X86::BI__builtin_ia32_vcvtps2ph256:
3787   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3788   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3789   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3790   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3791   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3792   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3793   case X86::BI__builtin_ia32_rndscaleps_mask:
3794   case X86::BI__builtin_ia32_rndscalepd_mask:
3795   case X86::BI__builtin_ia32_reducepd128_mask:
3796   case X86::BI__builtin_ia32_reducepd256_mask:
3797   case X86::BI__builtin_ia32_reducepd512_mask:
3798   case X86::BI__builtin_ia32_reduceps128_mask:
3799   case X86::BI__builtin_ia32_reduceps256_mask:
3800   case X86::BI__builtin_ia32_reduceps512_mask:
3801   case X86::BI__builtin_ia32_prold512:
3802   case X86::BI__builtin_ia32_prolq512:
3803   case X86::BI__builtin_ia32_prold128:
3804   case X86::BI__builtin_ia32_prold256:
3805   case X86::BI__builtin_ia32_prolq128:
3806   case X86::BI__builtin_ia32_prolq256:
3807   case X86::BI__builtin_ia32_prord512:
3808   case X86::BI__builtin_ia32_prorq512:
3809   case X86::BI__builtin_ia32_prord128:
3810   case X86::BI__builtin_ia32_prord256:
3811   case X86::BI__builtin_ia32_prorq128:
3812   case X86::BI__builtin_ia32_prorq256:
3813   case X86::BI__builtin_ia32_fpclasspd128_mask:
3814   case X86::BI__builtin_ia32_fpclasspd256_mask:
3815   case X86::BI__builtin_ia32_fpclassps128_mask:
3816   case X86::BI__builtin_ia32_fpclassps256_mask:
3817   case X86::BI__builtin_ia32_fpclassps512_mask:
3818   case X86::BI__builtin_ia32_fpclasspd512_mask:
3819   case X86::BI__builtin_ia32_fpclasssd_mask:
3820   case X86::BI__builtin_ia32_fpclassss_mask:
3821   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3822   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3823   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3824   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3825   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3826   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3827   case X86::BI__builtin_ia32_kshiftliqi:
3828   case X86::BI__builtin_ia32_kshiftlihi:
3829   case X86::BI__builtin_ia32_kshiftlisi:
3830   case X86::BI__builtin_ia32_kshiftlidi:
3831   case X86::BI__builtin_ia32_kshiftriqi:
3832   case X86::BI__builtin_ia32_kshiftrihi:
3833   case X86::BI__builtin_ia32_kshiftrisi:
3834   case X86::BI__builtin_ia32_kshiftridi:
3835     i = 1; l = 0; u = 255;
3836     break;
3837   case X86::BI__builtin_ia32_vperm2f128_pd256:
3838   case X86::BI__builtin_ia32_vperm2f128_ps256:
3839   case X86::BI__builtin_ia32_vperm2f128_si256:
3840   case X86::BI__builtin_ia32_permti256:
3841   case X86::BI__builtin_ia32_pblendw128:
3842   case X86::BI__builtin_ia32_pblendw256:
3843   case X86::BI__builtin_ia32_blendps256:
3844   case X86::BI__builtin_ia32_pblendd256:
3845   case X86::BI__builtin_ia32_palignr128:
3846   case X86::BI__builtin_ia32_palignr256:
3847   case X86::BI__builtin_ia32_palignr512:
3848   case X86::BI__builtin_ia32_alignq512:
3849   case X86::BI__builtin_ia32_alignd512:
3850   case X86::BI__builtin_ia32_alignd128:
3851   case X86::BI__builtin_ia32_alignd256:
3852   case X86::BI__builtin_ia32_alignq128:
3853   case X86::BI__builtin_ia32_alignq256:
3854   case X86::BI__builtin_ia32_vcomisd:
3855   case X86::BI__builtin_ia32_vcomiss:
3856   case X86::BI__builtin_ia32_shuf_f32x4:
3857   case X86::BI__builtin_ia32_shuf_f64x2:
3858   case X86::BI__builtin_ia32_shuf_i32x4:
3859   case X86::BI__builtin_ia32_shuf_i64x2:
3860   case X86::BI__builtin_ia32_shufpd512:
3861   case X86::BI__builtin_ia32_shufps:
3862   case X86::BI__builtin_ia32_shufps256:
3863   case X86::BI__builtin_ia32_shufps512:
3864   case X86::BI__builtin_ia32_dbpsadbw128:
3865   case X86::BI__builtin_ia32_dbpsadbw256:
3866   case X86::BI__builtin_ia32_dbpsadbw512:
3867   case X86::BI__builtin_ia32_vpshldd128:
3868   case X86::BI__builtin_ia32_vpshldd256:
3869   case X86::BI__builtin_ia32_vpshldd512:
3870   case X86::BI__builtin_ia32_vpshldq128:
3871   case X86::BI__builtin_ia32_vpshldq256:
3872   case X86::BI__builtin_ia32_vpshldq512:
3873   case X86::BI__builtin_ia32_vpshldw128:
3874   case X86::BI__builtin_ia32_vpshldw256:
3875   case X86::BI__builtin_ia32_vpshldw512:
3876   case X86::BI__builtin_ia32_vpshrdd128:
3877   case X86::BI__builtin_ia32_vpshrdd256:
3878   case X86::BI__builtin_ia32_vpshrdd512:
3879   case X86::BI__builtin_ia32_vpshrdq128:
3880   case X86::BI__builtin_ia32_vpshrdq256:
3881   case X86::BI__builtin_ia32_vpshrdq512:
3882   case X86::BI__builtin_ia32_vpshrdw128:
3883   case X86::BI__builtin_ia32_vpshrdw256:
3884   case X86::BI__builtin_ia32_vpshrdw512:
3885     i = 2; l = 0; u = 255;
3886     break;
3887   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3888   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3889   case X86::BI__builtin_ia32_fixupimmps512_mask:
3890   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3891   case X86::BI__builtin_ia32_fixupimmsd_mask:
3892   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3893   case X86::BI__builtin_ia32_fixupimmss_mask:
3894   case X86::BI__builtin_ia32_fixupimmss_maskz:
3895   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3896   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3897   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3898   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3899   case X86::BI__builtin_ia32_fixupimmps128_mask:
3900   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3901   case X86::BI__builtin_ia32_fixupimmps256_mask:
3902   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3903   case X86::BI__builtin_ia32_pternlogd512_mask:
3904   case X86::BI__builtin_ia32_pternlogd512_maskz:
3905   case X86::BI__builtin_ia32_pternlogq512_mask:
3906   case X86::BI__builtin_ia32_pternlogq512_maskz:
3907   case X86::BI__builtin_ia32_pternlogd128_mask:
3908   case X86::BI__builtin_ia32_pternlogd128_maskz:
3909   case X86::BI__builtin_ia32_pternlogd256_mask:
3910   case X86::BI__builtin_ia32_pternlogd256_maskz:
3911   case X86::BI__builtin_ia32_pternlogq128_mask:
3912   case X86::BI__builtin_ia32_pternlogq128_maskz:
3913   case X86::BI__builtin_ia32_pternlogq256_mask:
3914   case X86::BI__builtin_ia32_pternlogq256_maskz:
3915     i = 3; l = 0; u = 255;
3916     break;
3917   case X86::BI__builtin_ia32_gatherpfdpd:
3918   case X86::BI__builtin_ia32_gatherpfdps:
3919   case X86::BI__builtin_ia32_gatherpfqpd:
3920   case X86::BI__builtin_ia32_gatherpfqps:
3921   case X86::BI__builtin_ia32_scatterpfdpd:
3922   case X86::BI__builtin_ia32_scatterpfdps:
3923   case X86::BI__builtin_ia32_scatterpfqpd:
3924   case X86::BI__builtin_ia32_scatterpfqps:
3925     i = 4; l = 2; u = 3;
3926     break;
3927   case X86::BI__builtin_ia32_reducesd_mask:
3928   case X86::BI__builtin_ia32_reducess_mask:
3929   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3930   case X86::BI__builtin_ia32_rndscaless_round_mask:
3931     i = 4; l = 0; u = 255;
3932     break;
3933   }
3934 
3935   // Note that we don't force a hard error on the range check here, allowing
3936   // template-generated or macro-generated dead code to potentially have out-of-
3937   // range values. These need to code generate, but don't need to necessarily
3938   // make any sense. We use a warning that defaults to an error.
3939   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3940 }
3941 
3942 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3943 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3944 /// Returns true when the format fits the function and the FormatStringInfo has
3945 /// been populated.
3946 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3947                                FormatStringInfo *FSI) {
3948   FSI->HasVAListArg = Format->getFirstArg() == 0;
3949   FSI->FormatIdx = Format->getFormatIdx() - 1;
3950   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3951 
3952   // The way the format attribute works in GCC, the implicit this argument
3953   // of member functions is counted. However, it doesn't appear in our own
3954   // lists, so decrement format_idx in that case.
3955   if (IsCXXMember) {
3956     if(FSI->FormatIdx == 0)
3957       return false;
3958     --FSI->FormatIdx;
3959     if (FSI->FirstDataArg != 0)
3960       --FSI->FirstDataArg;
3961   }
3962   return true;
3963 }
3964 
3965 /// Checks if a the given expression evaluates to null.
3966 ///
3967 /// Returns true if the value evaluates to null.
3968 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3969   // If the expression has non-null type, it doesn't evaluate to null.
3970   if (auto nullability
3971         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3972     if (*nullability == NullabilityKind::NonNull)
3973       return false;
3974   }
3975 
3976   // As a special case, transparent unions initialized with zero are
3977   // considered null for the purposes of the nonnull attribute.
3978   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3979     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3980       if (const CompoundLiteralExpr *CLE =
3981           dyn_cast<CompoundLiteralExpr>(Expr))
3982         if (const InitListExpr *ILE =
3983             dyn_cast<InitListExpr>(CLE->getInitializer()))
3984           Expr = ILE->getInit(0);
3985   }
3986 
3987   bool Result;
3988   return (!Expr->isValueDependent() &&
3989           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3990           !Result);
3991 }
3992 
3993 static void CheckNonNullArgument(Sema &S,
3994                                  const Expr *ArgExpr,
3995                                  SourceLocation CallSiteLoc) {
3996   if (CheckNonNullExpr(S, ArgExpr))
3997     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3998                           S.PDiag(diag::warn_null_arg)
3999                               << ArgExpr->getSourceRange());
4000 }
4001 
4002 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4003   FormatStringInfo FSI;
4004   if ((GetFormatStringType(Format) == FST_NSString) &&
4005       getFormatStringInfo(Format, false, &FSI)) {
4006     Idx = FSI.FormatIdx;
4007     return true;
4008   }
4009   return false;
4010 }
4011 
4012 /// Diagnose use of %s directive in an NSString which is being passed
4013 /// as formatting string to formatting method.
4014 static void
4015 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4016                                         const NamedDecl *FDecl,
4017                                         Expr **Args,
4018                                         unsigned NumArgs) {
4019   unsigned Idx = 0;
4020   bool Format = false;
4021   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4022   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4023     Idx = 2;
4024     Format = true;
4025   }
4026   else
4027     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4028       if (S.GetFormatNSStringIdx(I, Idx)) {
4029         Format = true;
4030         break;
4031       }
4032     }
4033   if (!Format || NumArgs <= Idx)
4034     return;
4035   const Expr *FormatExpr = Args[Idx];
4036   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4037     FormatExpr = CSCE->getSubExpr();
4038   const StringLiteral *FormatString;
4039   if (const ObjCStringLiteral *OSL =
4040       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4041     FormatString = OSL->getString();
4042   else
4043     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4044   if (!FormatString)
4045     return;
4046   if (S.FormatStringHasSArg(FormatString)) {
4047     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4048       << "%s" << 1 << 1;
4049     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4050       << FDecl->getDeclName();
4051   }
4052 }
4053 
4054 /// Determine whether the given type has a non-null nullability annotation.
4055 static bool isNonNullType(ASTContext &ctx, QualType type) {
4056   if (auto nullability = type->getNullability(ctx))
4057     return *nullability == NullabilityKind::NonNull;
4058 
4059   return false;
4060 }
4061 
4062 static void CheckNonNullArguments(Sema &S,
4063                                   const NamedDecl *FDecl,
4064                                   const FunctionProtoType *Proto,
4065                                   ArrayRef<const Expr *> Args,
4066                                   SourceLocation CallSiteLoc) {
4067   assert((FDecl || Proto) && "Need a function declaration or prototype");
4068 
4069   // Already checked by by constant evaluator.
4070   if (S.isConstantEvaluated())
4071     return;
4072   // Check the attributes attached to the method/function itself.
4073   llvm::SmallBitVector NonNullArgs;
4074   if (FDecl) {
4075     // Handle the nonnull attribute on the function/method declaration itself.
4076     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4077       if (!NonNull->args_size()) {
4078         // Easy case: all pointer arguments are nonnull.
4079         for (const auto *Arg : Args)
4080           if (S.isValidPointerAttrType(Arg->getType()))
4081             CheckNonNullArgument(S, Arg, CallSiteLoc);
4082         return;
4083       }
4084 
4085       for (const ParamIdx &Idx : NonNull->args()) {
4086         unsigned IdxAST = Idx.getASTIndex();
4087         if (IdxAST >= Args.size())
4088           continue;
4089         if (NonNullArgs.empty())
4090           NonNullArgs.resize(Args.size());
4091         NonNullArgs.set(IdxAST);
4092       }
4093     }
4094   }
4095 
4096   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4097     // Handle the nonnull attribute on the parameters of the
4098     // function/method.
4099     ArrayRef<ParmVarDecl*> parms;
4100     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4101       parms = FD->parameters();
4102     else
4103       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4104 
4105     unsigned ParamIndex = 0;
4106     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4107          I != E; ++I, ++ParamIndex) {
4108       const ParmVarDecl *PVD = *I;
4109       if (PVD->hasAttr<NonNullAttr>() ||
4110           isNonNullType(S.Context, PVD->getType())) {
4111         if (NonNullArgs.empty())
4112           NonNullArgs.resize(Args.size());
4113 
4114         NonNullArgs.set(ParamIndex);
4115       }
4116     }
4117   } else {
4118     // If we have a non-function, non-method declaration but no
4119     // function prototype, try to dig out the function prototype.
4120     if (!Proto) {
4121       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4122         QualType type = VD->getType().getNonReferenceType();
4123         if (auto pointerType = type->getAs<PointerType>())
4124           type = pointerType->getPointeeType();
4125         else if (auto blockType = type->getAs<BlockPointerType>())
4126           type = blockType->getPointeeType();
4127         // FIXME: data member pointers?
4128 
4129         // Dig out the function prototype, if there is one.
4130         Proto = type->getAs<FunctionProtoType>();
4131       }
4132     }
4133 
4134     // Fill in non-null argument information from the nullability
4135     // information on the parameter types (if we have them).
4136     if (Proto) {
4137       unsigned Index = 0;
4138       for (auto paramType : Proto->getParamTypes()) {
4139         if (isNonNullType(S.Context, paramType)) {
4140           if (NonNullArgs.empty())
4141             NonNullArgs.resize(Args.size());
4142 
4143           NonNullArgs.set(Index);
4144         }
4145 
4146         ++Index;
4147       }
4148     }
4149   }
4150 
4151   // Check for non-null arguments.
4152   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4153        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4154     if (NonNullArgs[ArgIndex])
4155       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4156   }
4157 }
4158 
4159 /// Handles the checks for format strings, non-POD arguments to vararg
4160 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4161 /// attributes.
4162 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4163                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4164                      bool IsMemberFunction, SourceLocation Loc,
4165                      SourceRange Range, VariadicCallType CallType) {
4166   // FIXME: We should check as much as we can in the template definition.
4167   if (CurContext->isDependentContext())
4168     return;
4169 
4170   // Printf and scanf checking.
4171   llvm::SmallBitVector CheckedVarArgs;
4172   if (FDecl) {
4173     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4174       // Only create vector if there are format attributes.
4175       CheckedVarArgs.resize(Args.size());
4176 
4177       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4178                            CheckedVarArgs);
4179     }
4180   }
4181 
4182   // Refuse POD arguments that weren't caught by the format string
4183   // checks above.
4184   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4185   if (CallType != VariadicDoesNotApply &&
4186       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4187     unsigned NumParams = Proto ? Proto->getNumParams()
4188                        : FDecl && isa<FunctionDecl>(FDecl)
4189                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4190                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4191                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4192                        : 0;
4193 
4194     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4195       // Args[ArgIdx] can be null in malformed code.
4196       if (const Expr *Arg = Args[ArgIdx]) {
4197         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4198           checkVariadicArgument(Arg, CallType);
4199       }
4200     }
4201   }
4202 
4203   if (FDecl || Proto) {
4204     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4205 
4206     // Type safety checking.
4207     if (FDecl) {
4208       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4209         CheckArgumentWithTypeTag(I, Args, Loc);
4210     }
4211   }
4212 
4213   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4214     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4215     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4216     if (!Arg->isValueDependent()) {
4217       Expr::EvalResult Align;
4218       if (Arg->EvaluateAsInt(Align, Context)) {
4219         const llvm::APSInt &I = Align.Val.getInt();
4220         if (!I.isPowerOf2())
4221           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4222               << Arg->getSourceRange();
4223 
4224         if (I > Sema::MaximumAlignment)
4225           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4226               << Arg->getSourceRange() << Sema::MaximumAlignment;
4227       }
4228     }
4229   }
4230 
4231   if (FD)
4232     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4233 }
4234 
4235 /// CheckConstructorCall - Check a constructor call for correctness and safety
4236 /// properties not enforced by the C type system.
4237 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4238                                 ArrayRef<const Expr *> Args,
4239                                 const FunctionProtoType *Proto,
4240                                 SourceLocation Loc) {
4241   VariadicCallType CallType =
4242     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4243   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4244             Loc, SourceRange(), CallType);
4245 }
4246 
4247 /// CheckFunctionCall - Check a direct function call for various correctness
4248 /// and safety properties not strictly enforced by the C type system.
4249 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4250                              const FunctionProtoType *Proto) {
4251   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4252                               isa<CXXMethodDecl>(FDecl);
4253   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4254                           IsMemberOperatorCall;
4255   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4256                                                   TheCall->getCallee());
4257   Expr** Args = TheCall->getArgs();
4258   unsigned NumArgs = TheCall->getNumArgs();
4259 
4260   Expr *ImplicitThis = nullptr;
4261   if (IsMemberOperatorCall) {
4262     // If this is a call to a member operator, hide the first argument
4263     // from checkCall.
4264     // FIXME: Our choice of AST representation here is less than ideal.
4265     ImplicitThis = Args[0];
4266     ++Args;
4267     --NumArgs;
4268   } else if (IsMemberFunction)
4269     ImplicitThis =
4270         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4271 
4272   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4273             IsMemberFunction, TheCall->getRParenLoc(),
4274             TheCall->getCallee()->getSourceRange(), CallType);
4275 
4276   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4277   // None of the checks below are needed for functions that don't have
4278   // simple names (e.g., C++ conversion functions).
4279   if (!FnInfo)
4280     return false;
4281 
4282   CheckAbsoluteValueFunction(TheCall, FDecl);
4283   CheckMaxUnsignedZero(TheCall, FDecl);
4284 
4285   if (getLangOpts().ObjC)
4286     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4287 
4288   unsigned CMId = FDecl->getMemoryFunctionKind();
4289   if (CMId == 0)
4290     return false;
4291 
4292   // Handle memory setting and copying functions.
4293   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4294     CheckStrlcpycatArguments(TheCall, FnInfo);
4295   else if (CMId == Builtin::BIstrncat)
4296     CheckStrncatArguments(TheCall, FnInfo);
4297   else
4298     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4299 
4300   return false;
4301 }
4302 
4303 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4304                                ArrayRef<const Expr *> Args) {
4305   VariadicCallType CallType =
4306       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4307 
4308   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4309             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4310             CallType);
4311 
4312   return false;
4313 }
4314 
4315 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4316                             const FunctionProtoType *Proto) {
4317   QualType Ty;
4318   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4319     Ty = V->getType().getNonReferenceType();
4320   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4321     Ty = F->getType().getNonReferenceType();
4322   else
4323     return false;
4324 
4325   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4326       !Ty->isFunctionProtoType())
4327     return false;
4328 
4329   VariadicCallType CallType;
4330   if (!Proto || !Proto->isVariadic()) {
4331     CallType = VariadicDoesNotApply;
4332   } else if (Ty->isBlockPointerType()) {
4333     CallType = VariadicBlock;
4334   } else { // Ty->isFunctionPointerType()
4335     CallType = VariadicFunction;
4336   }
4337 
4338   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4339             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4340             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4341             TheCall->getCallee()->getSourceRange(), CallType);
4342 
4343   return false;
4344 }
4345 
4346 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4347 /// such as function pointers returned from functions.
4348 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4349   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4350                                                   TheCall->getCallee());
4351   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4352             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4353             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4354             TheCall->getCallee()->getSourceRange(), CallType);
4355 
4356   return false;
4357 }
4358 
4359 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4360   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4361     return false;
4362 
4363   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4364   switch (Op) {
4365   case AtomicExpr::AO__c11_atomic_init:
4366   case AtomicExpr::AO__opencl_atomic_init:
4367     llvm_unreachable("There is no ordering argument for an init");
4368 
4369   case AtomicExpr::AO__c11_atomic_load:
4370   case AtomicExpr::AO__opencl_atomic_load:
4371   case AtomicExpr::AO__atomic_load_n:
4372   case AtomicExpr::AO__atomic_load:
4373     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4374            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4375 
4376   case AtomicExpr::AO__c11_atomic_store:
4377   case AtomicExpr::AO__opencl_atomic_store:
4378   case AtomicExpr::AO__atomic_store:
4379   case AtomicExpr::AO__atomic_store_n:
4380     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4381            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4382            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4383 
4384   default:
4385     return true;
4386   }
4387 }
4388 
4389 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4390                                          AtomicExpr::AtomicOp Op) {
4391   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4392   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4393   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4394   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4395                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4396                          Op);
4397 }
4398 
4399 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4400                                  SourceLocation RParenLoc, MultiExprArg Args,
4401                                  AtomicExpr::AtomicOp Op,
4402                                  AtomicArgumentOrder ArgOrder) {
4403   // All the non-OpenCL operations take one of the following forms.
4404   // The OpenCL operations take the __c11 forms with one extra argument for
4405   // synchronization scope.
4406   enum {
4407     // C    __c11_atomic_init(A *, C)
4408     Init,
4409 
4410     // C    __c11_atomic_load(A *, int)
4411     Load,
4412 
4413     // void __atomic_load(A *, CP, int)
4414     LoadCopy,
4415 
4416     // void __atomic_store(A *, CP, int)
4417     Copy,
4418 
4419     // C    __c11_atomic_add(A *, M, int)
4420     Arithmetic,
4421 
4422     // C    __atomic_exchange_n(A *, CP, int)
4423     Xchg,
4424 
4425     // void __atomic_exchange(A *, C *, CP, int)
4426     GNUXchg,
4427 
4428     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4429     C11CmpXchg,
4430 
4431     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4432     GNUCmpXchg
4433   } Form = Init;
4434 
4435   const unsigned NumForm = GNUCmpXchg + 1;
4436   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4437   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4438   // where:
4439   //   C is an appropriate type,
4440   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4441   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4442   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4443   //   the int parameters are for orderings.
4444 
4445   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4446       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4447       "need to update code for modified forms");
4448   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4449                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4450                         AtomicExpr::AO__atomic_load,
4451                 "need to update code for modified C11 atomics");
4452   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4453                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4454   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4455                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4456                IsOpenCL;
4457   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4458              Op == AtomicExpr::AO__atomic_store_n ||
4459              Op == AtomicExpr::AO__atomic_exchange_n ||
4460              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4461   bool IsAddSub = false;
4462 
4463   switch (Op) {
4464   case AtomicExpr::AO__c11_atomic_init:
4465   case AtomicExpr::AO__opencl_atomic_init:
4466     Form = Init;
4467     break;
4468 
4469   case AtomicExpr::AO__c11_atomic_load:
4470   case AtomicExpr::AO__opencl_atomic_load:
4471   case AtomicExpr::AO__atomic_load_n:
4472     Form = Load;
4473     break;
4474 
4475   case AtomicExpr::AO__atomic_load:
4476     Form = LoadCopy;
4477     break;
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     Form = Copy;
4484     break;
4485 
4486   case AtomicExpr::AO__c11_atomic_fetch_add:
4487   case AtomicExpr::AO__c11_atomic_fetch_sub:
4488   case AtomicExpr::AO__opencl_atomic_fetch_add:
4489   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4490   case AtomicExpr::AO__atomic_fetch_add:
4491   case AtomicExpr::AO__atomic_fetch_sub:
4492   case AtomicExpr::AO__atomic_add_fetch:
4493   case AtomicExpr::AO__atomic_sub_fetch:
4494     IsAddSub = true;
4495     LLVM_FALLTHROUGH;
4496   case AtomicExpr::AO__c11_atomic_fetch_and:
4497   case AtomicExpr::AO__c11_atomic_fetch_or:
4498   case AtomicExpr::AO__c11_atomic_fetch_xor:
4499   case AtomicExpr::AO__opencl_atomic_fetch_and:
4500   case AtomicExpr::AO__opencl_atomic_fetch_or:
4501   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4502   case AtomicExpr::AO__atomic_fetch_and:
4503   case AtomicExpr::AO__atomic_fetch_or:
4504   case AtomicExpr::AO__atomic_fetch_xor:
4505   case AtomicExpr::AO__atomic_fetch_nand:
4506   case AtomicExpr::AO__atomic_and_fetch:
4507   case AtomicExpr::AO__atomic_or_fetch:
4508   case AtomicExpr::AO__atomic_xor_fetch:
4509   case AtomicExpr::AO__atomic_nand_fetch:
4510   case AtomicExpr::AO__c11_atomic_fetch_min:
4511   case AtomicExpr::AO__c11_atomic_fetch_max:
4512   case AtomicExpr::AO__opencl_atomic_fetch_min:
4513   case AtomicExpr::AO__opencl_atomic_fetch_max:
4514   case AtomicExpr::AO__atomic_min_fetch:
4515   case AtomicExpr::AO__atomic_max_fetch:
4516   case AtomicExpr::AO__atomic_fetch_min:
4517   case AtomicExpr::AO__atomic_fetch_max:
4518     Form = Arithmetic;
4519     break;
4520 
4521   case AtomicExpr::AO__c11_atomic_exchange:
4522   case AtomicExpr::AO__opencl_atomic_exchange:
4523   case AtomicExpr::AO__atomic_exchange_n:
4524     Form = Xchg;
4525     break;
4526 
4527   case AtomicExpr::AO__atomic_exchange:
4528     Form = GNUXchg;
4529     break;
4530 
4531   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4532   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4533   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4534   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4535     Form = C11CmpXchg;
4536     break;
4537 
4538   case AtomicExpr::AO__atomic_compare_exchange:
4539   case AtomicExpr::AO__atomic_compare_exchange_n:
4540     Form = GNUCmpXchg;
4541     break;
4542   }
4543 
4544   unsigned AdjustedNumArgs = NumArgs[Form];
4545   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4546     ++AdjustedNumArgs;
4547   // Check we have the right number of arguments.
4548   if (Args.size() < AdjustedNumArgs) {
4549     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4550         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4551         << ExprRange;
4552     return ExprError();
4553   } else if (Args.size() > AdjustedNumArgs) {
4554     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4555          diag::err_typecheck_call_too_many_args)
4556         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4557         << ExprRange;
4558     return ExprError();
4559   }
4560 
4561   // Inspect the first argument of the atomic operation.
4562   Expr *Ptr = Args[0];
4563   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4564   if (ConvertedPtr.isInvalid())
4565     return ExprError();
4566 
4567   Ptr = ConvertedPtr.get();
4568   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4569   if (!pointerType) {
4570     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4571         << Ptr->getType() << Ptr->getSourceRange();
4572     return ExprError();
4573   }
4574 
4575   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4576   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4577   QualType ValType = AtomTy; // 'C'
4578   if (IsC11) {
4579     if (!AtomTy->isAtomicType()) {
4580       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4581           << Ptr->getType() << Ptr->getSourceRange();
4582       return ExprError();
4583     }
4584     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4585         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4586       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4587           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4588           << Ptr->getSourceRange();
4589       return ExprError();
4590     }
4591     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4592   } else if (Form != Load && Form != LoadCopy) {
4593     if (ValType.isConstQualified()) {
4594       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4595           << Ptr->getType() << Ptr->getSourceRange();
4596       return ExprError();
4597     }
4598   }
4599 
4600   // For an arithmetic operation, the implied arithmetic must be well-formed.
4601   if (Form == Arithmetic) {
4602     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4603     if (IsAddSub && !ValType->isIntegerType()
4604         && !ValType->isPointerType()) {
4605       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4606           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4607       return ExprError();
4608     }
4609     if (!IsAddSub && !ValType->isIntegerType()) {
4610       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4611           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4612       return ExprError();
4613     }
4614     if (IsC11 && ValType->isPointerType() &&
4615         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4616                             diag::err_incomplete_type)) {
4617       return ExprError();
4618     }
4619   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4620     // For __atomic_*_n operations, the value type must be a scalar integral or
4621     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4622     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4623         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4624     return ExprError();
4625   }
4626 
4627   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4628       !AtomTy->isScalarType()) {
4629     // For GNU atomics, require a trivially-copyable type. This is not part of
4630     // the GNU atomics specification, but we enforce it for sanity.
4631     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4632         << Ptr->getType() << Ptr->getSourceRange();
4633     return ExprError();
4634   }
4635 
4636   switch (ValType.getObjCLifetime()) {
4637   case Qualifiers::OCL_None:
4638   case Qualifiers::OCL_ExplicitNone:
4639     // okay
4640     break;
4641 
4642   case Qualifiers::OCL_Weak:
4643   case Qualifiers::OCL_Strong:
4644   case Qualifiers::OCL_Autoreleasing:
4645     // FIXME: Can this happen? By this point, ValType should be known
4646     // to be trivially copyable.
4647     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4648         << ValType << Ptr->getSourceRange();
4649     return ExprError();
4650   }
4651 
4652   // All atomic operations have an overload which takes a pointer to a volatile
4653   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4654   // into the result or the other operands. Similarly atomic_load takes a
4655   // pointer to a const 'A'.
4656   ValType.removeLocalVolatile();
4657   ValType.removeLocalConst();
4658   QualType ResultType = ValType;
4659   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4660       Form == Init)
4661     ResultType = Context.VoidTy;
4662   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4663     ResultType = Context.BoolTy;
4664 
4665   // The type of a parameter passed 'by value'. In the GNU atomics, such
4666   // arguments are actually passed as pointers.
4667   QualType ByValType = ValType; // 'CP'
4668   bool IsPassedByAddress = false;
4669   if (!IsC11 && !IsN) {
4670     ByValType = Ptr->getType();
4671     IsPassedByAddress = true;
4672   }
4673 
4674   SmallVector<Expr *, 5> APIOrderedArgs;
4675   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4676     APIOrderedArgs.push_back(Args[0]);
4677     switch (Form) {
4678     case Init:
4679     case Load:
4680       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4681       break;
4682     case LoadCopy:
4683     case Copy:
4684     case Arithmetic:
4685     case Xchg:
4686       APIOrderedArgs.push_back(Args[2]); // Val1
4687       APIOrderedArgs.push_back(Args[1]); // Order
4688       break;
4689     case GNUXchg:
4690       APIOrderedArgs.push_back(Args[2]); // Val1
4691       APIOrderedArgs.push_back(Args[3]); // Val2
4692       APIOrderedArgs.push_back(Args[1]); // Order
4693       break;
4694     case C11CmpXchg:
4695       APIOrderedArgs.push_back(Args[2]); // Val1
4696       APIOrderedArgs.push_back(Args[4]); // Val2
4697       APIOrderedArgs.push_back(Args[1]); // Order
4698       APIOrderedArgs.push_back(Args[3]); // OrderFail
4699       break;
4700     case GNUCmpXchg:
4701       APIOrderedArgs.push_back(Args[2]); // Val1
4702       APIOrderedArgs.push_back(Args[4]); // Val2
4703       APIOrderedArgs.push_back(Args[5]); // Weak
4704       APIOrderedArgs.push_back(Args[1]); // Order
4705       APIOrderedArgs.push_back(Args[3]); // OrderFail
4706       break;
4707     }
4708   } else
4709     APIOrderedArgs.append(Args.begin(), Args.end());
4710 
4711   // The first argument's non-CV pointer type is used to deduce the type of
4712   // subsequent arguments, except for:
4713   //  - weak flag (always converted to bool)
4714   //  - memory order (always converted to int)
4715   //  - scope  (always converted to int)
4716   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4717     QualType Ty;
4718     if (i < NumVals[Form] + 1) {
4719       switch (i) {
4720       case 0:
4721         // The first argument is always a pointer. It has a fixed type.
4722         // It is always dereferenced, a nullptr is undefined.
4723         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4724         // Nothing else to do: we already know all we want about this pointer.
4725         continue;
4726       case 1:
4727         // The second argument is the non-atomic operand. For arithmetic, this
4728         // is always passed by value, and for a compare_exchange it is always
4729         // passed by address. For the rest, GNU uses by-address and C11 uses
4730         // by-value.
4731         assert(Form != Load);
4732         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4733           Ty = ValType;
4734         else if (Form == Copy || Form == Xchg) {
4735           if (IsPassedByAddress) {
4736             // The value pointer is always dereferenced, a nullptr is undefined.
4737             CheckNonNullArgument(*this, APIOrderedArgs[i],
4738                                  ExprRange.getBegin());
4739           }
4740           Ty = ByValType;
4741         } else if (Form == Arithmetic)
4742           Ty = Context.getPointerDiffType();
4743         else {
4744           Expr *ValArg = APIOrderedArgs[i];
4745           // The value pointer is always dereferenced, a nullptr is undefined.
4746           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4747           LangAS AS = LangAS::Default;
4748           // Keep address space of non-atomic pointer type.
4749           if (const PointerType *PtrTy =
4750                   ValArg->getType()->getAs<PointerType>()) {
4751             AS = PtrTy->getPointeeType().getAddressSpace();
4752           }
4753           Ty = Context.getPointerType(
4754               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4755         }
4756         break;
4757       case 2:
4758         // The third argument to compare_exchange / GNU exchange is the desired
4759         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4760         if (IsPassedByAddress)
4761           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4762         Ty = ByValType;
4763         break;
4764       case 3:
4765         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4766         Ty = Context.BoolTy;
4767         break;
4768       }
4769     } else {
4770       // The order(s) and scope are always converted to int.
4771       Ty = Context.IntTy;
4772     }
4773 
4774     InitializedEntity Entity =
4775         InitializedEntity::InitializeParameter(Context, Ty, false);
4776     ExprResult Arg = APIOrderedArgs[i];
4777     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4778     if (Arg.isInvalid())
4779       return true;
4780     APIOrderedArgs[i] = Arg.get();
4781   }
4782 
4783   // Permute the arguments into a 'consistent' order.
4784   SmallVector<Expr*, 5> SubExprs;
4785   SubExprs.push_back(Ptr);
4786   switch (Form) {
4787   case Init:
4788     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4789     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4790     break;
4791   case Load:
4792     SubExprs.push_back(APIOrderedArgs[1]); // Order
4793     break;
4794   case LoadCopy:
4795   case Copy:
4796   case Arithmetic:
4797   case Xchg:
4798     SubExprs.push_back(APIOrderedArgs[2]); // Order
4799     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4800     break;
4801   case GNUXchg:
4802     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4803     SubExprs.push_back(APIOrderedArgs[3]); // Order
4804     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4805     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4806     break;
4807   case C11CmpXchg:
4808     SubExprs.push_back(APIOrderedArgs[3]); // Order
4809     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4810     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4811     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4812     break;
4813   case GNUCmpXchg:
4814     SubExprs.push_back(APIOrderedArgs[4]); // Order
4815     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4816     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4817     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4818     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4819     break;
4820   }
4821 
4822   if (SubExprs.size() >= 2 && Form != Init) {
4823     llvm::APSInt Result(32);
4824     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4825         !isValidOrderingForOp(Result.getSExtValue(), Op))
4826       Diag(SubExprs[1]->getBeginLoc(),
4827            diag::warn_atomic_op_has_invalid_memory_order)
4828           << SubExprs[1]->getSourceRange();
4829   }
4830 
4831   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4832     auto *Scope = Args[Args.size() - 1];
4833     llvm::APSInt Result(32);
4834     if (Scope->isIntegerConstantExpr(Result, Context) &&
4835         !ScopeModel->isValid(Result.getZExtValue())) {
4836       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4837           << Scope->getSourceRange();
4838     }
4839     SubExprs.push_back(Scope);
4840   }
4841 
4842   AtomicExpr *AE = new (Context)
4843       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4844 
4845   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4846        Op == AtomicExpr::AO__c11_atomic_store ||
4847        Op == AtomicExpr::AO__opencl_atomic_load ||
4848        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4849       Context.AtomicUsesUnsupportedLibcall(AE))
4850     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4851         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4852              Op == AtomicExpr::AO__opencl_atomic_load)
4853                 ? 0
4854                 : 1);
4855 
4856   return AE;
4857 }
4858 
4859 /// checkBuiltinArgument - Given a call to a builtin function, perform
4860 /// normal type-checking on the given argument, updating the call in
4861 /// place.  This is useful when a builtin function requires custom
4862 /// type-checking for some of its arguments but not necessarily all of
4863 /// them.
4864 ///
4865 /// Returns true on error.
4866 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4867   FunctionDecl *Fn = E->getDirectCallee();
4868   assert(Fn && "builtin call without direct callee!");
4869 
4870   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4871   InitializedEntity Entity =
4872     InitializedEntity::InitializeParameter(S.Context, Param);
4873 
4874   ExprResult Arg = E->getArg(0);
4875   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4876   if (Arg.isInvalid())
4877     return true;
4878 
4879   E->setArg(ArgIndex, Arg.get());
4880   return false;
4881 }
4882 
4883 /// We have a call to a function like __sync_fetch_and_add, which is an
4884 /// overloaded function based on the pointer type of its first argument.
4885 /// The main BuildCallExpr routines have already promoted the types of
4886 /// arguments because all of these calls are prototyped as void(...).
4887 ///
4888 /// This function goes through and does final semantic checking for these
4889 /// builtins, as well as generating any warnings.
4890 ExprResult
4891 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4892   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4893   Expr *Callee = TheCall->getCallee();
4894   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4895   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4896 
4897   // Ensure that we have at least one argument to do type inference from.
4898   if (TheCall->getNumArgs() < 1) {
4899     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4900         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4901     return ExprError();
4902   }
4903 
4904   // Inspect the first argument of the atomic builtin.  This should always be
4905   // a pointer type, whose element is an integral scalar or pointer type.
4906   // Because it is a pointer type, we don't have to worry about any implicit
4907   // casts here.
4908   // FIXME: We don't allow floating point scalars as input.
4909   Expr *FirstArg = TheCall->getArg(0);
4910   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4911   if (FirstArgResult.isInvalid())
4912     return ExprError();
4913   FirstArg = FirstArgResult.get();
4914   TheCall->setArg(0, FirstArg);
4915 
4916   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4917   if (!pointerType) {
4918     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4919         << FirstArg->getType() << FirstArg->getSourceRange();
4920     return ExprError();
4921   }
4922 
4923   QualType ValType = pointerType->getPointeeType();
4924   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4925       !ValType->isBlockPointerType()) {
4926     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4927         << FirstArg->getType() << FirstArg->getSourceRange();
4928     return ExprError();
4929   }
4930 
4931   if (ValType.isConstQualified()) {
4932     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4933         << FirstArg->getType() << FirstArg->getSourceRange();
4934     return ExprError();
4935   }
4936 
4937   switch (ValType.getObjCLifetime()) {
4938   case Qualifiers::OCL_None:
4939   case Qualifiers::OCL_ExplicitNone:
4940     // okay
4941     break;
4942 
4943   case Qualifiers::OCL_Weak:
4944   case Qualifiers::OCL_Strong:
4945   case Qualifiers::OCL_Autoreleasing:
4946     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4947         << ValType << FirstArg->getSourceRange();
4948     return ExprError();
4949   }
4950 
4951   // Strip any qualifiers off ValType.
4952   ValType = ValType.getUnqualifiedType();
4953 
4954   // The majority of builtins return a value, but a few have special return
4955   // types, so allow them to override appropriately below.
4956   QualType ResultType = ValType;
4957 
4958   // We need to figure out which concrete builtin this maps onto.  For example,
4959   // __sync_fetch_and_add with a 2 byte object turns into
4960   // __sync_fetch_and_add_2.
4961 #define BUILTIN_ROW(x) \
4962   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4963     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4964 
4965   static const unsigned BuiltinIndices[][5] = {
4966     BUILTIN_ROW(__sync_fetch_and_add),
4967     BUILTIN_ROW(__sync_fetch_and_sub),
4968     BUILTIN_ROW(__sync_fetch_and_or),
4969     BUILTIN_ROW(__sync_fetch_and_and),
4970     BUILTIN_ROW(__sync_fetch_and_xor),
4971     BUILTIN_ROW(__sync_fetch_and_nand),
4972 
4973     BUILTIN_ROW(__sync_add_and_fetch),
4974     BUILTIN_ROW(__sync_sub_and_fetch),
4975     BUILTIN_ROW(__sync_and_and_fetch),
4976     BUILTIN_ROW(__sync_or_and_fetch),
4977     BUILTIN_ROW(__sync_xor_and_fetch),
4978     BUILTIN_ROW(__sync_nand_and_fetch),
4979 
4980     BUILTIN_ROW(__sync_val_compare_and_swap),
4981     BUILTIN_ROW(__sync_bool_compare_and_swap),
4982     BUILTIN_ROW(__sync_lock_test_and_set),
4983     BUILTIN_ROW(__sync_lock_release),
4984     BUILTIN_ROW(__sync_swap)
4985   };
4986 #undef BUILTIN_ROW
4987 
4988   // Determine the index of the size.
4989   unsigned SizeIndex;
4990   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4991   case 1: SizeIndex = 0; break;
4992   case 2: SizeIndex = 1; break;
4993   case 4: SizeIndex = 2; break;
4994   case 8: SizeIndex = 3; break;
4995   case 16: SizeIndex = 4; break;
4996   default:
4997     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4998         << FirstArg->getType() << FirstArg->getSourceRange();
4999     return ExprError();
5000   }
5001 
5002   // Each of these builtins has one pointer argument, followed by some number of
5003   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5004   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5005   // as the number of fixed args.
5006   unsigned BuiltinID = FDecl->getBuiltinID();
5007   unsigned BuiltinIndex, NumFixed = 1;
5008   bool WarnAboutSemanticsChange = false;
5009   switch (BuiltinID) {
5010   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5011   case Builtin::BI__sync_fetch_and_add:
5012   case Builtin::BI__sync_fetch_and_add_1:
5013   case Builtin::BI__sync_fetch_and_add_2:
5014   case Builtin::BI__sync_fetch_and_add_4:
5015   case Builtin::BI__sync_fetch_and_add_8:
5016   case Builtin::BI__sync_fetch_and_add_16:
5017     BuiltinIndex = 0;
5018     break;
5019 
5020   case Builtin::BI__sync_fetch_and_sub:
5021   case Builtin::BI__sync_fetch_and_sub_1:
5022   case Builtin::BI__sync_fetch_and_sub_2:
5023   case Builtin::BI__sync_fetch_and_sub_4:
5024   case Builtin::BI__sync_fetch_and_sub_8:
5025   case Builtin::BI__sync_fetch_and_sub_16:
5026     BuiltinIndex = 1;
5027     break;
5028 
5029   case Builtin::BI__sync_fetch_and_or:
5030   case Builtin::BI__sync_fetch_and_or_1:
5031   case Builtin::BI__sync_fetch_and_or_2:
5032   case Builtin::BI__sync_fetch_and_or_4:
5033   case Builtin::BI__sync_fetch_and_or_8:
5034   case Builtin::BI__sync_fetch_and_or_16:
5035     BuiltinIndex = 2;
5036     break;
5037 
5038   case Builtin::BI__sync_fetch_and_and:
5039   case Builtin::BI__sync_fetch_and_and_1:
5040   case Builtin::BI__sync_fetch_and_and_2:
5041   case Builtin::BI__sync_fetch_and_and_4:
5042   case Builtin::BI__sync_fetch_and_and_8:
5043   case Builtin::BI__sync_fetch_and_and_16:
5044     BuiltinIndex = 3;
5045     break;
5046 
5047   case Builtin::BI__sync_fetch_and_xor:
5048   case Builtin::BI__sync_fetch_and_xor_1:
5049   case Builtin::BI__sync_fetch_and_xor_2:
5050   case Builtin::BI__sync_fetch_and_xor_4:
5051   case Builtin::BI__sync_fetch_and_xor_8:
5052   case Builtin::BI__sync_fetch_and_xor_16:
5053     BuiltinIndex = 4;
5054     break;
5055 
5056   case Builtin::BI__sync_fetch_and_nand:
5057   case Builtin::BI__sync_fetch_and_nand_1:
5058   case Builtin::BI__sync_fetch_and_nand_2:
5059   case Builtin::BI__sync_fetch_and_nand_4:
5060   case Builtin::BI__sync_fetch_and_nand_8:
5061   case Builtin::BI__sync_fetch_and_nand_16:
5062     BuiltinIndex = 5;
5063     WarnAboutSemanticsChange = true;
5064     break;
5065 
5066   case Builtin::BI__sync_add_and_fetch:
5067   case Builtin::BI__sync_add_and_fetch_1:
5068   case Builtin::BI__sync_add_and_fetch_2:
5069   case Builtin::BI__sync_add_and_fetch_4:
5070   case Builtin::BI__sync_add_and_fetch_8:
5071   case Builtin::BI__sync_add_and_fetch_16:
5072     BuiltinIndex = 6;
5073     break;
5074 
5075   case Builtin::BI__sync_sub_and_fetch:
5076   case Builtin::BI__sync_sub_and_fetch_1:
5077   case Builtin::BI__sync_sub_and_fetch_2:
5078   case Builtin::BI__sync_sub_and_fetch_4:
5079   case Builtin::BI__sync_sub_and_fetch_8:
5080   case Builtin::BI__sync_sub_and_fetch_16:
5081     BuiltinIndex = 7;
5082     break;
5083 
5084   case Builtin::BI__sync_and_and_fetch:
5085   case Builtin::BI__sync_and_and_fetch_1:
5086   case Builtin::BI__sync_and_and_fetch_2:
5087   case Builtin::BI__sync_and_and_fetch_4:
5088   case Builtin::BI__sync_and_and_fetch_8:
5089   case Builtin::BI__sync_and_and_fetch_16:
5090     BuiltinIndex = 8;
5091     break;
5092 
5093   case Builtin::BI__sync_or_and_fetch:
5094   case Builtin::BI__sync_or_and_fetch_1:
5095   case Builtin::BI__sync_or_and_fetch_2:
5096   case Builtin::BI__sync_or_and_fetch_4:
5097   case Builtin::BI__sync_or_and_fetch_8:
5098   case Builtin::BI__sync_or_and_fetch_16:
5099     BuiltinIndex = 9;
5100     break;
5101 
5102   case Builtin::BI__sync_xor_and_fetch:
5103   case Builtin::BI__sync_xor_and_fetch_1:
5104   case Builtin::BI__sync_xor_and_fetch_2:
5105   case Builtin::BI__sync_xor_and_fetch_4:
5106   case Builtin::BI__sync_xor_and_fetch_8:
5107   case Builtin::BI__sync_xor_and_fetch_16:
5108     BuiltinIndex = 10;
5109     break;
5110 
5111   case Builtin::BI__sync_nand_and_fetch:
5112   case Builtin::BI__sync_nand_and_fetch_1:
5113   case Builtin::BI__sync_nand_and_fetch_2:
5114   case Builtin::BI__sync_nand_and_fetch_4:
5115   case Builtin::BI__sync_nand_and_fetch_8:
5116   case Builtin::BI__sync_nand_and_fetch_16:
5117     BuiltinIndex = 11;
5118     WarnAboutSemanticsChange = true;
5119     break;
5120 
5121   case Builtin::BI__sync_val_compare_and_swap:
5122   case Builtin::BI__sync_val_compare_and_swap_1:
5123   case Builtin::BI__sync_val_compare_and_swap_2:
5124   case Builtin::BI__sync_val_compare_and_swap_4:
5125   case Builtin::BI__sync_val_compare_and_swap_8:
5126   case Builtin::BI__sync_val_compare_and_swap_16:
5127     BuiltinIndex = 12;
5128     NumFixed = 2;
5129     break;
5130 
5131   case Builtin::BI__sync_bool_compare_and_swap:
5132   case Builtin::BI__sync_bool_compare_and_swap_1:
5133   case Builtin::BI__sync_bool_compare_and_swap_2:
5134   case Builtin::BI__sync_bool_compare_and_swap_4:
5135   case Builtin::BI__sync_bool_compare_and_swap_8:
5136   case Builtin::BI__sync_bool_compare_and_swap_16:
5137     BuiltinIndex = 13;
5138     NumFixed = 2;
5139     ResultType = Context.BoolTy;
5140     break;
5141 
5142   case Builtin::BI__sync_lock_test_and_set:
5143   case Builtin::BI__sync_lock_test_and_set_1:
5144   case Builtin::BI__sync_lock_test_and_set_2:
5145   case Builtin::BI__sync_lock_test_and_set_4:
5146   case Builtin::BI__sync_lock_test_and_set_8:
5147   case Builtin::BI__sync_lock_test_and_set_16:
5148     BuiltinIndex = 14;
5149     break;
5150 
5151   case Builtin::BI__sync_lock_release:
5152   case Builtin::BI__sync_lock_release_1:
5153   case Builtin::BI__sync_lock_release_2:
5154   case Builtin::BI__sync_lock_release_4:
5155   case Builtin::BI__sync_lock_release_8:
5156   case Builtin::BI__sync_lock_release_16:
5157     BuiltinIndex = 15;
5158     NumFixed = 0;
5159     ResultType = Context.VoidTy;
5160     break;
5161 
5162   case Builtin::BI__sync_swap:
5163   case Builtin::BI__sync_swap_1:
5164   case Builtin::BI__sync_swap_2:
5165   case Builtin::BI__sync_swap_4:
5166   case Builtin::BI__sync_swap_8:
5167   case Builtin::BI__sync_swap_16:
5168     BuiltinIndex = 16;
5169     break;
5170   }
5171 
5172   // Now that we know how many fixed arguments we expect, first check that we
5173   // have at least that many.
5174   if (TheCall->getNumArgs() < 1+NumFixed) {
5175     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5176         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5177         << Callee->getSourceRange();
5178     return ExprError();
5179   }
5180 
5181   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5182       << Callee->getSourceRange();
5183 
5184   if (WarnAboutSemanticsChange) {
5185     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5186         << Callee->getSourceRange();
5187   }
5188 
5189   // Get the decl for the concrete builtin from this, we can tell what the
5190   // concrete integer type we should convert to is.
5191   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5192   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5193   FunctionDecl *NewBuiltinDecl;
5194   if (NewBuiltinID == BuiltinID)
5195     NewBuiltinDecl = FDecl;
5196   else {
5197     // Perform builtin lookup to avoid redeclaring it.
5198     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5199     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5200     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5201     assert(Res.getFoundDecl());
5202     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5203     if (!NewBuiltinDecl)
5204       return ExprError();
5205   }
5206 
5207   // The first argument --- the pointer --- has a fixed type; we
5208   // deduce the types of the rest of the arguments accordingly.  Walk
5209   // the remaining arguments, converting them to the deduced value type.
5210   for (unsigned i = 0; i != NumFixed; ++i) {
5211     ExprResult Arg = TheCall->getArg(i+1);
5212 
5213     // GCC does an implicit conversion to the pointer or integer ValType.  This
5214     // can fail in some cases (1i -> int**), check for this error case now.
5215     // Initialize the argument.
5216     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5217                                                    ValType, /*consume*/ false);
5218     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5219     if (Arg.isInvalid())
5220       return ExprError();
5221 
5222     // Okay, we have something that *can* be converted to the right type.  Check
5223     // to see if there is a potentially weird extension going on here.  This can
5224     // happen when you do an atomic operation on something like an char* and
5225     // pass in 42.  The 42 gets converted to char.  This is even more strange
5226     // for things like 45.123 -> char, etc.
5227     // FIXME: Do this check.
5228     TheCall->setArg(i+1, Arg.get());
5229   }
5230 
5231   // Create a new DeclRefExpr to refer to the new decl.
5232   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5233       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5234       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5235       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5236 
5237   // Set the callee in the CallExpr.
5238   // FIXME: This loses syntactic information.
5239   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5240   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5241                                               CK_BuiltinFnToFnPtr);
5242   TheCall->setCallee(PromotedCall.get());
5243 
5244   // Change the result type of the call to match the original value type. This
5245   // is arbitrary, but the codegen for these builtins ins design to handle it
5246   // gracefully.
5247   TheCall->setType(ResultType);
5248 
5249   return TheCallResult;
5250 }
5251 
5252 /// SemaBuiltinNontemporalOverloaded - We have a call to
5253 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5254 /// overloaded function based on the pointer type of its last argument.
5255 ///
5256 /// This function goes through and does final semantic checking for these
5257 /// builtins.
5258 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5259   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5260   DeclRefExpr *DRE =
5261       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5262   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5263   unsigned BuiltinID = FDecl->getBuiltinID();
5264   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5265           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5266          "Unexpected nontemporal load/store builtin!");
5267   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5268   unsigned numArgs = isStore ? 2 : 1;
5269 
5270   // Ensure that we have the proper number of arguments.
5271   if (checkArgCount(*this, TheCall, numArgs))
5272     return ExprError();
5273 
5274   // Inspect the last argument of the nontemporal builtin.  This should always
5275   // be a pointer type, from which we imply the type of the memory access.
5276   // Because it is a pointer type, we don't have to worry about any implicit
5277   // casts here.
5278   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5279   ExprResult PointerArgResult =
5280       DefaultFunctionArrayLvalueConversion(PointerArg);
5281 
5282   if (PointerArgResult.isInvalid())
5283     return ExprError();
5284   PointerArg = PointerArgResult.get();
5285   TheCall->setArg(numArgs - 1, PointerArg);
5286 
5287   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5288   if (!pointerType) {
5289     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5290         << PointerArg->getType() << PointerArg->getSourceRange();
5291     return ExprError();
5292   }
5293 
5294   QualType ValType = pointerType->getPointeeType();
5295 
5296   // Strip any qualifiers off ValType.
5297   ValType = ValType.getUnqualifiedType();
5298   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5299       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5300       !ValType->isVectorType()) {
5301     Diag(DRE->getBeginLoc(),
5302          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5303         << PointerArg->getType() << PointerArg->getSourceRange();
5304     return ExprError();
5305   }
5306 
5307   if (!isStore) {
5308     TheCall->setType(ValType);
5309     return TheCallResult;
5310   }
5311 
5312   ExprResult ValArg = TheCall->getArg(0);
5313   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5314       Context, ValType, /*consume*/ false);
5315   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5316   if (ValArg.isInvalid())
5317     return ExprError();
5318 
5319   TheCall->setArg(0, ValArg.get());
5320   TheCall->setType(Context.VoidTy);
5321   return TheCallResult;
5322 }
5323 
5324 /// CheckObjCString - Checks that the argument to the builtin
5325 /// CFString constructor is correct
5326 /// Note: It might also make sense to do the UTF-16 conversion here (would
5327 /// simplify the backend).
5328 bool Sema::CheckObjCString(Expr *Arg) {
5329   Arg = Arg->IgnoreParenCasts();
5330   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5331 
5332   if (!Literal || !Literal->isAscii()) {
5333     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5334         << Arg->getSourceRange();
5335     return true;
5336   }
5337 
5338   if (Literal->containsNonAsciiOrNull()) {
5339     StringRef String = Literal->getString();
5340     unsigned NumBytes = String.size();
5341     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5342     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5343     llvm::UTF16 *ToPtr = &ToBuf[0];
5344 
5345     llvm::ConversionResult Result =
5346         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5347                                  ToPtr + NumBytes, llvm::strictConversion);
5348     // Check for conversion failure.
5349     if (Result != llvm::conversionOK)
5350       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5351           << Arg->getSourceRange();
5352   }
5353   return false;
5354 }
5355 
5356 /// CheckObjCString - Checks that the format string argument to the os_log()
5357 /// and os_trace() functions is correct, and converts it to const char *.
5358 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5359   Arg = Arg->IgnoreParenCasts();
5360   auto *Literal = dyn_cast<StringLiteral>(Arg);
5361   if (!Literal) {
5362     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5363       Literal = ObjcLiteral->getString();
5364     }
5365   }
5366 
5367   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5368     return ExprError(
5369         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5370         << Arg->getSourceRange());
5371   }
5372 
5373   ExprResult Result(Literal);
5374   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5375   InitializedEntity Entity =
5376       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5377   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5378   return Result;
5379 }
5380 
5381 /// Check that the user is calling the appropriate va_start builtin for the
5382 /// target and calling convention.
5383 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5384   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5385   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5386   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5387                     TT.getArch() == llvm::Triple::aarch64_32);
5388   bool IsWindows = TT.isOSWindows();
5389   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5390   if (IsX64 || IsAArch64) {
5391     CallingConv CC = CC_C;
5392     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5393       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5394     if (IsMSVAStart) {
5395       // Don't allow this in System V ABI functions.
5396       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5397         return S.Diag(Fn->getBeginLoc(),
5398                       diag::err_ms_va_start_used_in_sysv_function);
5399     } else {
5400       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5401       // On x64 Windows, don't allow this in System V ABI functions.
5402       // (Yes, that means there's no corresponding way to support variadic
5403       // System V ABI functions on Windows.)
5404       if ((IsWindows && CC == CC_X86_64SysV) ||
5405           (!IsWindows && CC == CC_Win64))
5406         return S.Diag(Fn->getBeginLoc(),
5407                       diag::err_va_start_used_in_wrong_abi_function)
5408                << !IsWindows;
5409     }
5410     return false;
5411   }
5412 
5413   if (IsMSVAStart)
5414     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5415   return false;
5416 }
5417 
5418 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5419                                              ParmVarDecl **LastParam = nullptr) {
5420   // Determine whether the current function, block, or obj-c method is variadic
5421   // and get its parameter list.
5422   bool IsVariadic = false;
5423   ArrayRef<ParmVarDecl *> Params;
5424   DeclContext *Caller = S.CurContext;
5425   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5426     IsVariadic = Block->isVariadic();
5427     Params = Block->parameters();
5428   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5429     IsVariadic = FD->isVariadic();
5430     Params = FD->parameters();
5431   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5432     IsVariadic = MD->isVariadic();
5433     // FIXME: This isn't correct for methods (results in bogus warning).
5434     Params = MD->parameters();
5435   } else if (isa<CapturedDecl>(Caller)) {
5436     // We don't support va_start in a CapturedDecl.
5437     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5438     return true;
5439   } else {
5440     // This must be some other declcontext that parses exprs.
5441     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5442     return true;
5443   }
5444 
5445   if (!IsVariadic) {
5446     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5447     return true;
5448   }
5449 
5450   if (LastParam)
5451     *LastParam = Params.empty() ? nullptr : Params.back();
5452 
5453   return false;
5454 }
5455 
5456 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5457 /// for validity.  Emit an error and return true on failure; return false
5458 /// on success.
5459 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5460   Expr *Fn = TheCall->getCallee();
5461 
5462   if (checkVAStartABI(*this, BuiltinID, Fn))
5463     return true;
5464 
5465   if (TheCall->getNumArgs() > 2) {
5466     Diag(TheCall->getArg(2)->getBeginLoc(),
5467          diag::err_typecheck_call_too_many_args)
5468         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5469         << Fn->getSourceRange()
5470         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5471                        (*(TheCall->arg_end() - 1))->getEndLoc());
5472     return true;
5473   }
5474 
5475   if (TheCall->getNumArgs() < 2) {
5476     return Diag(TheCall->getEndLoc(),
5477                 diag::err_typecheck_call_too_few_args_at_least)
5478            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5479   }
5480 
5481   // Type-check the first argument normally.
5482   if (checkBuiltinArgument(*this, TheCall, 0))
5483     return true;
5484 
5485   // Check that the current function is variadic, and get its last parameter.
5486   ParmVarDecl *LastParam;
5487   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5488     return true;
5489 
5490   // Verify that the second argument to the builtin is the last argument of the
5491   // current function or method.
5492   bool SecondArgIsLastNamedArgument = false;
5493   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5494 
5495   // These are valid if SecondArgIsLastNamedArgument is false after the next
5496   // block.
5497   QualType Type;
5498   SourceLocation ParamLoc;
5499   bool IsCRegister = false;
5500 
5501   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5502     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5503       SecondArgIsLastNamedArgument = PV == LastParam;
5504 
5505       Type = PV->getType();
5506       ParamLoc = PV->getLocation();
5507       IsCRegister =
5508           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5509     }
5510   }
5511 
5512   if (!SecondArgIsLastNamedArgument)
5513     Diag(TheCall->getArg(1)->getBeginLoc(),
5514          diag::warn_second_arg_of_va_start_not_last_named_param);
5515   else if (IsCRegister || Type->isReferenceType() ||
5516            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5517              // Promotable integers are UB, but enumerations need a bit of
5518              // extra checking to see what their promotable type actually is.
5519              if (!Type->isPromotableIntegerType())
5520                return false;
5521              if (!Type->isEnumeralType())
5522                return true;
5523              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5524              return !(ED &&
5525                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5526            }()) {
5527     unsigned Reason = 0;
5528     if (Type->isReferenceType())  Reason = 1;
5529     else if (IsCRegister)         Reason = 2;
5530     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5531     Diag(ParamLoc, diag::note_parameter_type) << Type;
5532   }
5533 
5534   TheCall->setType(Context.VoidTy);
5535   return false;
5536 }
5537 
5538 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5539   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5540   //                 const char *named_addr);
5541 
5542   Expr *Func = Call->getCallee();
5543 
5544   if (Call->getNumArgs() < 3)
5545     return Diag(Call->getEndLoc(),
5546                 diag::err_typecheck_call_too_few_args_at_least)
5547            << 0 /*function call*/ << 3 << Call->getNumArgs();
5548 
5549   // Type-check the first argument normally.
5550   if (checkBuiltinArgument(*this, Call, 0))
5551     return true;
5552 
5553   // Check that the current function is variadic.
5554   if (checkVAStartIsInVariadicFunction(*this, Func))
5555     return true;
5556 
5557   // __va_start on Windows does not validate the parameter qualifiers
5558 
5559   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5560   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5561 
5562   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5563   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5564 
5565   const QualType &ConstCharPtrTy =
5566       Context.getPointerType(Context.CharTy.withConst());
5567   if (!Arg1Ty->isPointerType() ||
5568       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5569     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5570         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5571         << 0                                      /* qualifier difference */
5572         << 3                                      /* parameter mismatch */
5573         << 2 << Arg1->getType() << ConstCharPtrTy;
5574 
5575   const QualType SizeTy = Context.getSizeType();
5576   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5577     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5578         << Arg2->getType() << SizeTy << 1 /* different class */
5579         << 0                              /* qualifier difference */
5580         << 3                              /* parameter mismatch */
5581         << 3 << Arg2->getType() << SizeTy;
5582 
5583   return false;
5584 }
5585 
5586 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5587 /// friends.  This is declared to take (...), so we have to check everything.
5588 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5589   if (TheCall->getNumArgs() < 2)
5590     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5591            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5592   if (TheCall->getNumArgs() > 2)
5593     return Diag(TheCall->getArg(2)->getBeginLoc(),
5594                 diag::err_typecheck_call_too_many_args)
5595            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5596            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5597                           (*(TheCall->arg_end() - 1))->getEndLoc());
5598 
5599   ExprResult OrigArg0 = TheCall->getArg(0);
5600   ExprResult OrigArg1 = TheCall->getArg(1);
5601 
5602   // Do standard promotions between the two arguments, returning their common
5603   // type.
5604   QualType Res = UsualArithmeticConversions(
5605       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5606   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5607     return true;
5608 
5609   // Make sure any conversions are pushed back into the call; this is
5610   // type safe since unordered compare builtins are declared as "_Bool
5611   // foo(...)".
5612   TheCall->setArg(0, OrigArg0.get());
5613   TheCall->setArg(1, OrigArg1.get());
5614 
5615   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5616     return false;
5617 
5618   // If the common type isn't a real floating type, then the arguments were
5619   // invalid for this operation.
5620   if (Res.isNull() || !Res->isRealFloatingType())
5621     return Diag(OrigArg0.get()->getBeginLoc(),
5622                 diag::err_typecheck_call_invalid_ordered_compare)
5623            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5624            << SourceRange(OrigArg0.get()->getBeginLoc(),
5625                           OrigArg1.get()->getEndLoc());
5626 
5627   return false;
5628 }
5629 
5630 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5631 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5632 /// to check everything. We expect the last argument to be a floating point
5633 /// value.
5634 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5635   if (TheCall->getNumArgs() < NumArgs)
5636     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5637            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5638   if (TheCall->getNumArgs() > NumArgs)
5639     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5640                 diag::err_typecheck_call_too_many_args)
5641            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5642            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5643                           (*(TheCall->arg_end() - 1))->getEndLoc());
5644 
5645   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5646   // on all preceding parameters just being int.  Try all of those.
5647   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5648     Expr *Arg = TheCall->getArg(i);
5649 
5650     if (Arg->isTypeDependent())
5651       return false;
5652 
5653     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5654 
5655     if (Res.isInvalid())
5656       return true;
5657     TheCall->setArg(i, Res.get());
5658   }
5659 
5660   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5661 
5662   if (OrigArg->isTypeDependent())
5663     return false;
5664 
5665   // Usual Unary Conversions will convert half to float, which we want for
5666   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5667   // type how it is, but do normal L->Rvalue conversions.
5668   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5669     OrigArg = UsualUnaryConversions(OrigArg).get();
5670   else
5671     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5672   TheCall->setArg(NumArgs - 1, OrigArg);
5673 
5674   // This operation requires a non-_Complex floating-point number.
5675   if (!OrigArg->getType()->isRealFloatingType())
5676     return Diag(OrigArg->getBeginLoc(),
5677                 diag::err_typecheck_call_invalid_unary_fp)
5678            << OrigArg->getType() << OrigArg->getSourceRange();
5679 
5680   return false;
5681 }
5682 
5683 // Customized Sema Checking for VSX builtins that have the following signature:
5684 // vector [...] builtinName(vector [...], vector [...], const int);
5685 // Which takes the same type of vectors (any legal vector type) for the first
5686 // two arguments and takes compile time constant for the third argument.
5687 // Example builtins are :
5688 // vector double vec_xxpermdi(vector double, vector double, int);
5689 // vector short vec_xxsldwi(vector short, vector short, int);
5690 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5691   unsigned ExpectedNumArgs = 3;
5692   if (TheCall->getNumArgs() < ExpectedNumArgs)
5693     return Diag(TheCall->getEndLoc(),
5694                 diag::err_typecheck_call_too_few_args_at_least)
5695            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5696            << TheCall->getSourceRange();
5697 
5698   if (TheCall->getNumArgs() > ExpectedNumArgs)
5699     return Diag(TheCall->getEndLoc(),
5700                 diag::err_typecheck_call_too_many_args_at_most)
5701            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5702            << TheCall->getSourceRange();
5703 
5704   // Check the third argument is a compile time constant
5705   llvm::APSInt Value;
5706   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5707     return Diag(TheCall->getBeginLoc(),
5708                 diag::err_vsx_builtin_nonconstant_argument)
5709            << 3 /* argument index */ << TheCall->getDirectCallee()
5710            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5711                           TheCall->getArg(2)->getEndLoc());
5712 
5713   QualType Arg1Ty = TheCall->getArg(0)->getType();
5714   QualType Arg2Ty = TheCall->getArg(1)->getType();
5715 
5716   // Check the type of argument 1 and argument 2 are vectors.
5717   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5718   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5719       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5720     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5721            << TheCall->getDirectCallee()
5722            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5723                           TheCall->getArg(1)->getEndLoc());
5724   }
5725 
5726   // Check the first two arguments are the same type.
5727   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5728     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5729            << TheCall->getDirectCallee()
5730            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5731                           TheCall->getArg(1)->getEndLoc());
5732   }
5733 
5734   // When default clang type checking is turned off and the customized type
5735   // checking is used, the returning type of the function must be explicitly
5736   // set. Otherwise it is _Bool by default.
5737   TheCall->setType(Arg1Ty);
5738 
5739   return false;
5740 }
5741 
5742 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5743 // This is declared to take (...), so we have to check everything.
5744 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5745   if (TheCall->getNumArgs() < 2)
5746     return ExprError(Diag(TheCall->getEndLoc(),
5747                           diag::err_typecheck_call_too_few_args_at_least)
5748                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5749                      << TheCall->getSourceRange());
5750 
5751   // Determine which of the following types of shufflevector we're checking:
5752   // 1) unary, vector mask: (lhs, mask)
5753   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5754   QualType resType = TheCall->getArg(0)->getType();
5755   unsigned numElements = 0;
5756 
5757   if (!TheCall->getArg(0)->isTypeDependent() &&
5758       !TheCall->getArg(1)->isTypeDependent()) {
5759     QualType LHSType = TheCall->getArg(0)->getType();
5760     QualType RHSType = TheCall->getArg(1)->getType();
5761 
5762     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5763       return ExprError(
5764           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5765           << TheCall->getDirectCallee()
5766           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5767                          TheCall->getArg(1)->getEndLoc()));
5768 
5769     numElements = LHSType->castAs<VectorType>()->getNumElements();
5770     unsigned numResElements = TheCall->getNumArgs() - 2;
5771 
5772     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5773     // with mask.  If so, verify that RHS is an integer vector type with the
5774     // same number of elts as lhs.
5775     if (TheCall->getNumArgs() == 2) {
5776       if (!RHSType->hasIntegerRepresentation() ||
5777           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5778         return ExprError(Diag(TheCall->getBeginLoc(),
5779                               diag::err_vec_builtin_incompatible_vector)
5780                          << TheCall->getDirectCallee()
5781                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5782                                         TheCall->getArg(1)->getEndLoc()));
5783     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5784       return ExprError(Diag(TheCall->getBeginLoc(),
5785                             diag::err_vec_builtin_incompatible_vector)
5786                        << TheCall->getDirectCallee()
5787                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5788                                       TheCall->getArg(1)->getEndLoc()));
5789     } else if (numElements != numResElements) {
5790       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5791       resType = Context.getVectorType(eltType, numResElements,
5792                                       VectorType::GenericVector);
5793     }
5794   }
5795 
5796   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5797     if (TheCall->getArg(i)->isTypeDependent() ||
5798         TheCall->getArg(i)->isValueDependent())
5799       continue;
5800 
5801     llvm::APSInt Result(32);
5802     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5803       return ExprError(Diag(TheCall->getBeginLoc(),
5804                             diag::err_shufflevector_nonconstant_argument)
5805                        << TheCall->getArg(i)->getSourceRange());
5806 
5807     // Allow -1 which will be translated to undef in the IR.
5808     if (Result.isSigned() && Result.isAllOnesValue())
5809       continue;
5810 
5811     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5812       return ExprError(Diag(TheCall->getBeginLoc(),
5813                             diag::err_shufflevector_argument_too_large)
5814                        << TheCall->getArg(i)->getSourceRange());
5815   }
5816 
5817   SmallVector<Expr*, 32> exprs;
5818 
5819   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5820     exprs.push_back(TheCall->getArg(i));
5821     TheCall->setArg(i, nullptr);
5822   }
5823 
5824   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5825                                          TheCall->getCallee()->getBeginLoc(),
5826                                          TheCall->getRParenLoc());
5827 }
5828 
5829 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5830 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5831                                        SourceLocation BuiltinLoc,
5832                                        SourceLocation RParenLoc) {
5833   ExprValueKind VK = VK_RValue;
5834   ExprObjectKind OK = OK_Ordinary;
5835   QualType DstTy = TInfo->getType();
5836   QualType SrcTy = E->getType();
5837 
5838   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5839     return ExprError(Diag(BuiltinLoc,
5840                           diag::err_convertvector_non_vector)
5841                      << E->getSourceRange());
5842   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5843     return ExprError(Diag(BuiltinLoc,
5844                           diag::err_convertvector_non_vector_type));
5845 
5846   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5847     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5848     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5849     if (SrcElts != DstElts)
5850       return ExprError(Diag(BuiltinLoc,
5851                             diag::err_convertvector_incompatible_vector)
5852                        << E->getSourceRange());
5853   }
5854 
5855   return new (Context)
5856       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5857 }
5858 
5859 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5860 // This is declared to take (const void*, ...) and can take two
5861 // optional constant int args.
5862 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5863   unsigned NumArgs = TheCall->getNumArgs();
5864 
5865   if (NumArgs > 3)
5866     return Diag(TheCall->getEndLoc(),
5867                 diag::err_typecheck_call_too_many_args_at_most)
5868            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5869 
5870   // Argument 0 is checked for us and the remaining arguments must be
5871   // constant integers.
5872   for (unsigned i = 1; i != NumArgs; ++i)
5873     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5874       return true;
5875 
5876   return false;
5877 }
5878 
5879 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5880 // __assume does not evaluate its arguments, and should warn if its argument
5881 // has side effects.
5882 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5883   Expr *Arg = TheCall->getArg(0);
5884   if (Arg->isInstantiationDependent()) return false;
5885 
5886   if (Arg->HasSideEffects(Context))
5887     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5888         << Arg->getSourceRange()
5889         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5890 
5891   return false;
5892 }
5893 
5894 /// Handle __builtin_alloca_with_align. This is declared
5895 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5896 /// than 8.
5897 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5898   // The alignment must be a constant integer.
5899   Expr *Arg = TheCall->getArg(1);
5900 
5901   // We can't check the value of a dependent argument.
5902   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5903     if (const auto *UE =
5904             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5905       if (UE->getKind() == UETT_AlignOf ||
5906           UE->getKind() == UETT_PreferredAlignOf)
5907         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5908             << Arg->getSourceRange();
5909 
5910     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5911 
5912     if (!Result.isPowerOf2())
5913       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5914              << Arg->getSourceRange();
5915 
5916     if (Result < Context.getCharWidth())
5917       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5918              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5919 
5920     if (Result > std::numeric_limits<int32_t>::max())
5921       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5922              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5923   }
5924 
5925   return false;
5926 }
5927 
5928 /// Handle __builtin_assume_aligned. This is declared
5929 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5930 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5931   unsigned NumArgs = TheCall->getNumArgs();
5932 
5933   if (NumArgs > 3)
5934     return Diag(TheCall->getEndLoc(),
5935                 diag::err_typecheck_call_too_many_args_at_most)
5936            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5937 
5938   // The alignment must be a constant integer.
5939   Expr *Arg = TheCall->getArg(1);
5940 
5941   // We can't check the value of a dependent argument.
5942   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5943     llvm::APSInt Result;
5944     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5945       return true;
5946 
5947     if (!Result.isPowerOf2())
5948       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5949              << Arg->getSourceRange();
5950 
5951     if (Result > Sema::MaximumAlignment)
5952       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5953           << Arg->getSourceRange() << Sema::MaximumAlignment;
5954   }
5955 
5956   if (NumArgs > 2) {
5957     ExprResult Arg(TheCall->getArg(2));
5958     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5959       Context.getSizeType(), false);
5960     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5961     if (Arg.isInvalid()) return true;
5962     TheCall->setArg(2, Arg.get());
5963   }
5964 
5965   return false;
5966 }
5967 
5968 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5969   unsigned BuiltinID =
5970       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5971   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5972 
5973   unsigned NumArgs = TheCall->getNumArgs();
5974   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5975   if (NumArgs < NumRequiredArgs) {
5976     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5977            << 0 /* function call */ << NumRequiredArgs << NumArgs
5978            << TheCall->getSourceRange();
5979   }
5980   if (NumArgs >= NumRequiredArgs + 0x100) {
5981     return Diag(TheCall->getEndLoc(),
5982                 diag::err_typecheck_call_too_many_args_at_most)
5983            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5984            << TheCall->getSourceRange();
5985   }
5986   unsigned i = 0;
5987 
5988   // For formatting call, check buffer arg.
5989   if (!IsSizeCall) {
5990     ExprResult Arg(TheCall->getArg(i));
5991     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5992         Context, Context.VoidPtrTy, false);
5993     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5994     if (Arg.isInvalid())
5995       return true;
5996     TheCall->setArg(i, Arg.get());
5997     i++;
5998   }
5999 
6000   // Check string literal arg.
6001   unsigned FormatIdx = i;
6002   {
6003     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6004     if (Arg.isInvalid())
6005       return true;
6006     TheCall->setArg(i, Arg.get());
6007     i++;
6008   }
6009 
6010   // Make sure variadic args are scalar.
6011   unsigned FirstDataArg = i;
6012   while (i < NumArgs) {
6013     ExprResult Arg = DefaultVariadicArgumentPromotion(
6014         TheCall->getArg(i), VariadicFunction, nullptr);
6015     if (Arg.isInvalid())
6016       return true;
6017     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6018     if (ArgSize.getQuantity() >= 0x100) {
6019       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6020              << i << (int)ArgSize.getQuantity() << 0xff
6021              << TheCall->getSourceRange();
6022     }
6023     TheCall->setArg(i, Arg.get());
6024     i++;
6025   }
6026 
6027   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6028   // call to avoid duplicate diagnostics.
6029   if (!IsSizeCall) {
6030     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6031     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6032     bool Success = CheckFormatArguments(
6033         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6034         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6035         CheckedVarArgs);
6036     if (!Success)
6037       return true;
6038   }
6039 
6040   if (IsSizeCall) {
6041     TheCall->setType(Context.getSizeType());
6042   } else {
6043     TheCall->setType(Context.VoidPtrTy);
6044   }
6045   return false;
6046 }
6047 
6048 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6049 /// TheCall is a constant expression.
6050 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6051                                   llvm::APSInt &Result) {
6052   Expr *Arg = TheCall->getArg(ArgNum);
6053   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6054   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6055 
6056   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6057 
6058   if (!Arg->isIntegerConstantExpr(Result, Context))
6059     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6060            << FDecl->getDeclName() << Arg->getSourceRange();
6061 
6062   return false;
6063 }
6064 
6065 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6066 /// TheCall is a constant expression in the range [Low, High].
6067 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6068                                        int Low, int High, bool RangeIsError) {
6069   if (isConstantEvaluated())
6070     return false;
6071   llvm::APSInt Result;
6072 
6073   // We can't check the value of a dependent argument.
6074   Expr *Arg = TheCall->getArg(ArgNum);
6075   if (Arg->isTypeDependent() || Arg->isValueDependent())
6076     return false;
6077 
6078   // Check constant-ness first.
6079   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6080     return true;
6081 
6082   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6083     if (RangeIsError)
6084       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6085              << Result.toString(10) << Low << High << Arg->getSourceRange();
6086     else
6087       // Defer the warning until we know if the code will be emitted so that
6088       // dead code can ignore this.
6089       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6090                           PDiag(diag::warn_argument_invalid_range)
6091                               << Result.toString(10) << Low << High
6092                               << Arg->getSourceRange());
6093   }
6094 
6095   return false;
6096 }
6097 
6098 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6099 /// TheCall is a constant expression is a multiple of Num..
6100 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6101                                           unsigned Num) {
6102   llvm::APSInt Result;
6103 
6104   // We can't check the value of a dependent argument.
6105   Expr *Arg = TheCall->getArg(ArgNum);
6106   if (Arg->isTypeDependent() || Arg->isValueDependent())
6107     return false;
6108 
6109   // Check constant-ness first.
6110   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6111     return true;
6112 
6113   if (Result.getSExtValue() % Num != 0)
6114     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6115            << Num << Arg->getSourceRange();
6116 
6117   return false;
6118 }
6119 
6120 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6121 /// constant expression representing a power of 2.
6122 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6123   llvm::APSInt Result;
6124 
6125   // We can't check the value of a dependent argument.
6126   Expr *Arg = TheCall->getArg(ArgNum);
6127   if (Arg->isTypeDependent() || Arg->isValueDependent())
6128     return false;
6129 
6130   // Check constant-ness first.
6131   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6132     return true;
6133 
6134   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6135   // and only if x is a power of 2.
6136   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6137     return false;
6138 
6139   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6140          << Arg->getSourceRange();
6141 }
6142 
6143 static bool IsShiftedByte(llvm::APSInt Value) {
6144   if (Value.isNegative())
6145     return false;
6146 
6147   // Check if it's a shifted byte, by shifting it down
6148   while (true) {
6149     // If the value fits in the bottom byte, the check passes.
6150     if (Value < 0x100)
6151       return true;
6152 
6153     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6154     // fails.
6155     if ((Value & 0xFF) != 0)
6156       return false;
6157 
6158     // If the bottom 8 bits are all 0, but something above that is nonzero,
6159     // then shifting the value right by 8 bits won't affect whether it's a
6160     // shifted byte or not. So do that, and go round again.
6161     Value >>= 8;
6162   }
6163 }
6164 
6165 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6166 /// a constant expression representing an arbitrary byte value shifted left by
6167 /// a multiple of 8 bits.
6168 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6169                                              unsigned ArgBits) {
6170   llvm::APSInt Result;
6171 
6172   // We can't check the value of a dependent argument.
6173   Expr *Arg = TheCall->getArg(ArgNum);
6174   if (Arg->isTypeDependent() || Arg->isValueDependent())
6175     return false;
6176 
6177   // Check constant-ness first.
6178   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6179     return true;
6180 
6181   // Truncate to the given size.
6182   Result = Result.getLoBits(ArgBits);
6183   Result.setIsUnsigned(true);
6184 
6185   if (IsShiftedByte(Result))
6186     return false;
6187 
6188   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6189          << Arg->getSourceRange();
6190 }
6191 
6192 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6193 /// TheCall is a constant expression representing either a shifted byte value,
6194 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6195 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6196 /// Arm MVE intrinsics.
6197 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6198                                                    int ArgNum,
6199                                                    unsigned ArgBits) {
6200   llvm::APSInt Result;
6201 
6202   // We can't check the value of a dependent argument.
6203   Expr *Arg = TheCall->getArg(ArgNum);
6204   if (Arg->isTypeDependent() || Arg->isValueDependent())
6205     return false;
6206 
6207   // Check constant-ness first.
6208   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6209     return true;
6210 
6211   // Truncate to the given size.
6212   Result = Result.getLoBits(ArgBits);
6213   Result.setIsUnsigned(true);
6214 
6215   // Check to see if it's in either of the required forms.
6216   if (IsShiftedByte(Result) ||
6217       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6218     return false;
6219 
6220   return Diag(TheCall->getBeginLoc(),
6221               diag::err_argument_not_shifted_byte_or_xxff)
6222          << Arg->getSourceRange();
6223 }
6224 
6225 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6226 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6227   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6228     if (checkArgCount(*this, TheCall, 2))
6229       return true;
6230     Expr *Arg0 = TheCall->getArg(0);
6231     Expr *Arg1 = TheCall->getArg(1);
6232 
6233     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6234     if (FirstArg.isInvalid())
6235       return true;
6236     QualType FirstArgType = FirstArg.get()->getType();
6237     if (!FirstArgType->isAnyPointerType())
6238       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6239                << "first" << FirstArgType << Arg0->getSourceRange();
6240     TheCall->setArg(0, FirstArg.get());
6241 
6242     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6243     if (SecArg.isInvalid())
6244       return true;
6245     QualType SecArgType = SecArg.get()->getType();
6246     if (!SecArgType->isIntegerType())
6247       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6248                << "second" << SecArgType << Arg1->getSourceRange();
6249 
6250     // Derive the return type from the pointer argument.
6251     TheCall->setType(FirstArgType);
6252     return false;
6253   }
6254 
6255   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6256     if (checkArgCount(*this, TheCall, 2))
6257       return true;
6258 
6259     Expr *Arg0 = TheCall->getArg(0);
6260     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6261     if (FirstArg.isInvalid())
6262       return true;
6263     QualType FirstArgType = FirstArg.get()->getType();
6264     if (!FirstArgType->isAnyPointerType())
6265       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6266                << "first" << FirstArgType << Arg0->getSourceRange();
6267     TheCall->setArg(0, FirstArg.get());
6268 
6269     // Derive the return type from the pointer argument.
6270     TheCall->setType(FirstArgType);
6271 
6272     // Second arg must be an constant in range [0,15]
6273     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6274   }
6275 
6276   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6277     if (checkArgCount(*this, TheCall, 2))
6278       return true;
6279     Expr *Arg0 = TheCall->getArg(0);
6280     Expr *Arg1 = TheCall->getArg(1);
6281 
6282     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6283     if (FirstArg.isInvalid())
6284       return true;
6285     QualType FirstArgType = FirstArg.get()->getType();
6286     if (!FirstArgType->isAnyPointerType())
6287       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6288                << "first" << FirstArgType << Arg0->getSourceRange();
6289 
6290     QualType SecArgType = Arg1->getType();
6291     if (!SecArgType->isIntegerType())
6292       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6293                << "second" << SecArgType << Arg1->getSourceRange();
6294     TheCall->setType(Context.IntTy);
6295     return false;
6296   }
6297 
6298   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6299       BuiltinID == AArch64::BI__builtin_arm_stg) {
6300     if (checkArgCount(*this, TheCall, 1))
6301       return true;
6302     Expr *Arg0 = TheCall->getArg(0);
6303     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6304     if (FirstArg.isInvalid())
6305       return true;
6306 
6307     QualType FirstArgType = FirstArg.get()->getType();
6308     if (!FirstArgType->isAnyPointerType())
6309       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6310                << "first" << FirstArgType << Arg0->getSourceRange();
6311     TheCall->setArg(0, FirstArg.get());
6312 
6313     // Derive the return type from the pointer argument.
6314     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6315       TheCall->setType(FirstArgType);
6316     return false;
6317   }
6318 
6319   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6320     Expr *ArgA = TheCall->getArg(0);
6321     Expr *ArgB = TheCall->getArg(1);
6322 
6323     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6324     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6325 
6326     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6327       return true;
6328 
6329     QualType ArgTypeA = ArgExprA.get()->getType();
6330     QualType ArgTypeB = ArgExprB.get()->getType();
6331 
6332     auto isNull = [&] (Expr *E) -> bool {
6333       return E->isNullPointerConstant(
6334                         Context, Expr::NPC_ValueDependentIsNotNull); };
6335 
6336     // argument should be either a pointer or null
6337     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6338       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6339         << "first" << ArgTypeA << ArgA->getSourceRange();
6340 
6341     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6342       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6343         << "second" << ArgTypeB << ArgB->getSourceRange();
6344 
6345     // Ensure Pointee types are compatible
6346     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6347         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6348       QualType pointeeA = ArgTypeA->getPointeeType();
6349       QualType pointeeB = ArgTypeB->getPointeeType();
6350       if (!Context.typesAreCompatible(
6351              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6352              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6353         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6354           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6355           << ArgB->getSourceRange();
6356       }
6357     }
6358 
6359     // at least one argument should be pointer type
6360     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6361       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6362         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6363 
6364     if (isNull(ArgA)) // adopt type of the other pointer
6365       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6366 
6367     if (isNull(ArgB))
6368       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6369 
6370     TheCall->setArg(0, ArgExprA.get());
6371     TheCall->setArg(1, ArgExprB.get());
6372     TheCall->setType(Context.LongLongTy);
6373     return false;
6374   }
6375   assert(false && "Unhandled ARM MTE intrinsic");
6376   return true;
6377 }
6378 
6379 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6380 /// TheCall is an ARM/AArch64 special register string literal.
6381 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6382                                     int ArgNum, unsigned ExpectedFieldNum,
6383                                     bool AllowName) {
6384   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6385                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6386                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6387                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6388                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6389                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6390   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6391                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6392                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6393                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6394                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6395                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6396   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6397 
6398   // We can't check the value of a dependent argument.
6399   Expr *Arg = TheCall->getArg(ArgNum);
6400   if (Arg->isTypeDependent() || Arg->isValueDependent())
6401     return false;
6402 
6403   // Check if the argument is a string literal.
6404   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6405     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6406            << Arg->getSourceRange();
6407 
6408   // Check the type of special register given.
6409   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6410   SmallVector<StringRef, 6> Fields;
6411   Reg.split(Fields, ":");
6412 
6413   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6414     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6415            << Arg->getSourceRange();
6416 
6417   // If the string is the name of a register then we cannot check that it is
6418   // valid here but if the string is of one the forms described in ACLE then we
6419   // can check that the supplied fields are integers and within the valid
6420   // ranges.
6421   if (Fields.size() > 1) {
6422     bool FiveFields = Fields.size() == 5;
6423 
6424     bool ValidString = true;
6425     if (IsARMBuiltin) {
6426       ValidString &= Fields[0].startswith_lower("cp") ||
6427                      Fields[0].startswith_lower("p");
6428       if (ValidString)
6429         Fields[0] =
6430           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6431 
6432       ValidString &= Fields[2].startswith_lower("c");
6433       if (ValidString)
6434         Fields[2] = Fields[2].drop_front(1);
6435 
6436       if (FiveFields) {
6437         ValidString &= Fields[3].startswith_lower("c");
6438         if (ValidString)
6439           Fields[3] = Fields[3].drop_front(1);
6440       }
6441     }
6442 
6443     SmallVector<int, 5> Ranges;
6444     if (FiveFields)
6445       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6446     else
6447       Ranges.append({15, 7, 15});
6448 
6449     for (unsigned i=0; i<Fields.size(); ++i) {
6450       int IntField;
6451       ValidString &= !Fields[i].getAsInteger(10, IntField);
6452       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6453     }
6454 
6455     if (!ValidString)
6456       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6457              << Arg->getSourceRange();
6458   } else if (IsAArch64Builtin && Fields.size() == 1) {
6459     // If the register name is one of those that appear in the condition below
6460     // and the special register builtin being used is one of the write builtins,
6461     // then we require that the argument provided for writing to the register
6462     // is an integer constant expression. This is because it will be lowered to
6463     // an MSR (immediate) instruction, so we need to know the immediate at
6464     // compile time.
6465     if (TheCall->getNumArgs() != 2)
6466       return false;
6467 
6468     std::string RegLower = Reg.lower();
6469     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6470         RegLower != "pan" && RegLower != "uao")
6471       return false;
6472 
6473     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6474   }
6475 
6476   return false;
6477 }
6478 
6479 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6480 /// This checks that the target supports __builtin_longjmp and
6481 /// that val is a constant 1.
6482 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6483   if (!Context.getTargetInfo().hasSjLjLowering())
6484     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6485            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6486 
6487   Expr *Arg = TheCall->getArg(1);
6488   llvm::APSInt Result;
6489 
6490   // TODO: This is less than ideal. Overload this to take a value.
6491   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6492     return true;
6493 
6494   if (Result != 1)
6495     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6496            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6497 
6498   return false;
6499 }
6500 
6501 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6502 /// This checks that the target supports __builtin_setjmp.
6503 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6504   if (!Context.getTargetInfo().hasSjLjLowering())
6505     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6506            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6507   return false;
6508 }
6509 
6510 namespace {
6511 
6512 class UncoveredArgHandler {
6513   enum { Unknown = -1, AllCovered = -2 };
6514 
6515   signed FirstUncoveredArg = Unknown;
6516   SmallVector<const Expr *, 4> DiagnosticExprs;
6517 
6518 public:
6519   UncoveredArgHandler() = default;
6520 
6521   bool hasUncoveredArg() const {
6522     return (FirstUncoveredArg >= 0);
6523   }
6524 
6525   unsigned getUncoveredArg() const {
6526     assert(hasUncoveredArg() && "no uncovered argument");
6527     return FirstUncoveredArg;
6528   }
6529 
6530   void setAllCovered() {
6531     // A string has been found with all arguments covered, so clear out
6532     // the diagnostics.
6533     DiagnosticExprs.clear();
6534     FirstUncoveredArg = AllCovered;
6535   }
6536 
6537   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6538     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6539 
6540     // Don't update if a previous string covers all arguments.
6541     if (FirstUncoveredArg == AllCovered)
6542       return;
6543 
6544     // UncoveredArgHandler tracks the highest uncovered argument index
6545     // and with it all the strings that match this index.
6546     if (NewFirstUncoveredArg == FirstUncoveredArg)
6547       DiagnosticExprs.push_back(StrExpr);
6548     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6549       DiagnosticExprs.clear();
6550       DiagnosticExprs.push_back(StrExpr);
6551       FirstUncoveredArg = NewFirstUncoveredArg;
6552     }
6553   }
6554 
6555   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6556 };
6557 
6558 enum StringLiteralCheckType {
6559   SLCT_NotALiteral,
6560   SLCT_UncheckedLiteral,
6561   SLCT_CheckedLiteral
6562 };
6563 
6564 } // namespace
6565 
6566 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6567                                      BinaryOperatorKind BinOpKind,
6568                                      bool AddendIsRight) {
6569   unsigned BitWidth = Offset.getBitWidth();
6570   unsigned AddendBitWidth = Addend.getBitWidth();
6571   // There might be negative interim results.
6572   if (Addend.isUnsigned()) {
6573     Addend = Addend.zext(++AddendBitWidth);
6574     Addend.setIsSigned(true);
6575   }
6576   // Adjust the bit width of the APSInts.
6577   if (AddendBitWidth > BitWidth) {
6578     Offset = Offset.sext(AddendBitWidth);
6579     BitWidth = AddendBitWidth;
6580   } else if (BitWidth > AddendBitWidth) {
6581     Addend = Addend.sext(BitWidth);
6582   }
6583 
6584   bool Ov = false;
6585   llvm::APSInt ResOffset = Offset;
6586   if (BinOpKind == BO_Add)
6587     ResOffset = Offset.sadd_ov(Addend, Ov);
6588   else {
6589     assert(AddendIsRight && BinOpKind == BO_Sub &&
6590            "operator must be add or sub with addend on the right");
6591     ResOffset = Offset.ssub_ov(Addend, Ov);
6592   }
6593 
6594   // We add an offset to a pointer here so we should support an offset as big as
6595   // possible.
6596   if (Ov) {
6597     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6598            "index (intermediate) result too big");
6599     Offset = Offset.sext(2 * BitWidth);
6600     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6601     return;
6602   }
6603 
6604   Offset = ResOffset;
6605 }
6606 
6607 namespace {
6608 
6609 // This is a wrapper class around StringLiteral to support offsetted string
6610 // literals as format strings. It takes the offset into account when returning
6611 // the string and its length or the source locations to display notes correctly.
6612 class FormatStringLiteral {
6613   const StringLiteral *FExpr;
6614   int64_t Offset;
6615 
6616  public:
6617   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6618       : FExpr(fexpr), Offset(Offset) {}
6619 
6620   StringRef getString() const {
6621     return FExpr->getString().drop_front(Offset);
6622   }
6623 
6624   unsigned getByteLength() const {
6625     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6626   }
6627 
6628   unsigned getLength() const { return FExpr->getLength() - Offset; }
6629   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6630 
6631   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6632 
6633   QualType getType() const { return FExpr->getType(); }
6634 
6635   bool isAscii() const { return FExpr->isAscii(); }
6636   bool isWide() const { return FExpr->isWide(); }
6637   bool isUTF8() const { return FExpr->isUTF8(); }
6638   bool isUTF16() const { return FExpr->isUTF16(); }
6639   bool isUTF32() const { return FExpr->isUTF32(); }
6640   bool isPascal() const { return FExpr->isPascal(); }
6641 
6642   SourceLocation getLocationOfByte(
6643       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6644       const TargetInfo &Target, unsigned *StartToken = nullptr,
6645       unsigned *StartTokenByteOffset = nullptr) const {
6646     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6647                                     StartToken, StartTokenByteOffset);
6648   }
6649 
6650   SourceLocation getBeginLoc() const LLVM_READONLY {
6651     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6652   }
6653 
6654   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6655 };
6656 
6657 }  // namespace
6658 
6659 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6660                               const Expr *OrigFormatExpr,
6661                               ArrayRef<const Expr *> Args,
6662                               bool HasVAListArg, unsigned format_idx,
6663                               unsigned firstDataArg,
6664                               Sema::FormatStringType Type,
6665                               bool inFunctionCall,
6666                               Sema::VariadicCallType CallType,
6667                               llvm::SmallBitVector &CheckedVarArgs,
6668                               UncoveredArgHandler &UncoveredArg,
6669                               bool IgnoreStringsWithoutSpecifiers);
6670 
6671 // Determine if an expression is a string literal or constant string.
6672 // If this function returns false on the arguments to a function expecting a
6673 // format string, we will usually need to emit a warning.
6674 // True string literals are then checked by CheckFormatString.
6675 static StringLiteralCheckType
6676 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6677                       bool HasVAListArg, unsigned format_idx,
6678                       unsigned firstDataArg, Sema::FormatStringType Type,
6679                       Sema::VariadicCallType CallType, bool InFunctionCall,
6680                       llvm::SmallBitVector &CheckedVarArgs,
6681                       UncoveredArgHandler &UncoveredArg,
6682                       llvm::APSInt Offset,
6683                       bool IgnoreStringsWithoutSpecifiers = false) {
6684   if (S.isConstantEvaluated())
6685     return SLCT_NotALiteral;
6686  tryAgain:
6687   assert(Offset.isSigned() && "invalid offset");
6688 
6689   if (E->isTypeDependent() || E->isValueDependent())
6690     return SLCT_NotALiteral;
6691 
6692   E = E->IgnoreParenCasts();
6693 
6694   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6695     // Technically -Wformat-nonliteral does not warn about this case.
6696     // The behavior of printf and friends in this case is implementation
6697     // dependent.  Ideally if the format string cannot be null then
6698     // it should have a 'nonnull' attribute in the function prototype.
6699     return SLCT_UncheckedLiteral;
6700 
6701   switch (E->getStmtClass()) {
6702   case Stmt::BinaryConditionalOperatorClass:
6703   case Stmt::ConditionalOperatorClass: {
6704     // The expression is a literal if both sub-expressions were, and it was
6705     // completely checked only if both sub-expressions were checked.
6706     const AbstractConditionalOperator *C =
6707         cast<AbstractConditionalOperator>(E);
6708 
6709     // Determine whether it is necessary to check both sub-expressions, for
6710     // example, because the condition expression is a constant that can be
6711     // evaluated at compile time.
6712     bool CheckLeft = true, CheckRight = true;
6713 
6714     bool Cond;
6715     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6716                                                  S.isConstantEvaluated())) {
6717       if (Cond)
6718         CheckRight = false;
6719       else
6720         CheckLeft = false;
6721     }
6722 
6723     // We need to maintain the offsets for the right and the left hand side
6724     // separately to check if every possible indexed expression is a valid
6725     // string literal. They might have different offsets for different string
6726     // literals in the end.
6727     StringLiteralCheckType Left;
6728     if (!CheckLeft)
6729       Left = SLCT_UncheckedLiteral;
6730     else {
6731       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6732                                    HasVAListArg, format_idx, firstDataArg,
6733                                    Type, CallType, InFunctionCall,
6734                                    CheckedVarArgs, UncoveredArg, Offset,
6735                                    IgnoreStringsWithoutSpecifiers);
6736       if (Left == SLCT_NotALiteral || !CheckRight) {
6737         return Left;
6738       }
6739     }
6740 
6741     StringLiteralCheckType Right = checkFormatStringExpr(
6742         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6743         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6744         IgnoreStringsWithoutSpecifiers);
6745 
6746     return (CheckLeft && Left < Right) ? Left : Right;
6747   }
6748 
6749   case Stmt::ImplicitCastExprClass:
6750     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6751     goto tryAgain;
6752 
6753   case Stmt::OpaqueValueExprClass:
6754     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6755       E = src;
6756       goto tryAgain;
6757     }
6758     return SLCT_NotALiteral;
6759 
6760   case Stmt::PredefinedExprClass:
6761     // While __func__, etc., are technically not string literals, they
6762     // cannot contain format specifiers and thus are not a security
6763     // liability.
6764     return SLCT_UncheckedLiteral;
6765 
6766   case Stmt::DeclRefExprClass: {
6767     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6768 
6769     // As an exception, do not flag errors for variables binding to
6770     // const string literals.
6771     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6772       bool isConstant = false;
6773       QualType T = DR->getType();
6774 
6775       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6776         isConstant = AT->getElementType().isConstant(S.Context);
6777       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6778         isConstant = T.isConstant(S.Context) &&
6779                      PT->getPointeeType().isConstant(S.Context);
6780       } else if (T->isObjCObjectPointerType()) {
6781         // In ObjC, there is usually no "const ObjectPointer" type,
6782         // so don't check if the pointee type is constant.
6783         isConstant = T.isConstant(S.Context);
6784       }
6785 
6786       if (isConstant) {
6787         if (const Expr *Init = VD->getAnyInitializer()) {
6788           // Look through initializers like const char c[] = { "foo" }
6789           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6790             if (InitList->isStringLiteralInit())
6791               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6792           }
6793           return checkFormatStringExpr(S, Init, Args,
6794                                        HasVAListArg, format_idx,
6795                                        firstDataArg, Type, CallType,
6796                                        /*InFunctionCall*/ false, CheckedVarArgs,
6797                                        UncoveredArg, Offset);
6798         }
6799       }
6800 
6801       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6802       // special check to see if the format string is a function parameter
6803       // of the function calling the printf function.  If the function
6804       // has an attribute indicating it is a printf-like function, then we
6805       // should suppress warnings concerning non-literals being used in a call
6806       // to a vprintf function.  For example:
6807       //
6808       // void
6809       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6810       //      va_list ap;
6811       //      va_start(ap, fmt);
6812       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6813       //      ...
6814       // }
6815       if (HasVAListArg) {
6816         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6817           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6818             int PVIndex = PV->getFunctionScopeIndex() + 1;
6819             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6820               // adjust for implicit parameter
6821               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6822                 if (MD->isInstance())
6823                   ++PVIndex;
6824               // We also check if the formats are compatible.
6825               // We can't pass a 'scanf' string to a 'printf' function.
6826               if (PVIndex == PVFormat->getFormatIdx() &&
6827                   Type == S.GetFormatStringType(PVFormat))
6828                 return SLCT_UncheckedLiteral;
6829             }
6830           }
6831         }
6832       }
6833     }
6834 
6835     return SLCT_NotALiteral;
6836   }
6837 
6838   case Stmt::CallExprClass:
6839   case Stmt::CXXMemberCallExprClass: {
6840     const CallExpr *CE = cast<CallExpr>(E);
6841     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6842       bool IsFirst = true;
6843       StringLiteralCheckType CommonResult;
6844       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6845         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6846         StringLiteralCheckType Result = checkFormatStringExpr(
6847             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6848             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6849             IgnoreStringsWithoutSpecifiers);
6850         if (IsFirst) {
6851           CommonResult = Result;
6852           IsFirst = false;
6853         }
6854       }
6855       if (!IsFirst)
6856         return CommonResult;
6857 
6858       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6859         unsigned BuiltinID = FD->getBuiltinID();
6860         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6861             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6862           const Expr *Arg = CE->getArg(0);
6863           return checkFormatStringExpr(S, Arg, Args,
6864                                        HasVAListArg, format_idx,
6865                                        firstDataArg, Type, CallType,
6866                                        InFunctionCall, CheckedVarArgs,
6867                                        UncoveredArg, Offset,
6868                                        IgnoreStringsWithoutSpecifiers);
6869         }
6870       }
6871     }
6872 
6873     return SLCT_NotALiteral;
6874   }
6875   case Stmt::ObjCMessageExprClass: {
6876     const auto *ME = cast<ObjCMessageExpr>(E);
6877     if (const auto *MD = ME->getMethodDecl()) {
6878       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6879         // As a special case heuristic, if we're using the method -[NSBundle
6880         // localizedStringForKey:value:table:], ignore any key strings that lack
6881         // format specifiers. The idea is that if the key doesn't have any
6882         // format specifiers then its probably just a key to map to the
6883         // localized strings. If it does have format specifiers though, then its
6884         // likely that the text of the key is the format string in the
6885         // programmer's language, and should be checked.
6886         const ObjCInterfaceDecl *IFace;
6887         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6888             IFace->getIdentifier()->isStr("NSBundle") &&
6889             MD->getSelector().isKeywordSelector(
6890                 {"localizedStringForKey", "value", "table"})) {
6891           IgnoreStringsWithoutSpecifiers = true;
6892         }
6893 
6894         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6895         return checkFormatStringExpr(
6896             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6897             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6898             IgnoreStringsWithoutSpecifiers);
6899       }
6900     }
6901 
6902     return SLCT_NotALiteral;
6903   }
6904   case Stmt::ObjCStringLiteralClass:
6905   case Stmt::StringLiteralClass: {
6906     const StringLiteral *StrE = nullptr;
6907 
6908     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6909       StrE = ObjCFExpr->getString();
6910     else
6911       StrE = cast<StringLiteral>(E);
6912 
6913     if (StrE) {
6914       if (Offset.isNegative() || Offset > StrE->getLength()) {
6915         // TODO: It would be better to have an explicit warning for out of
6916         // bounds literals.
6917         return SLCT_NotALiteral;
6918       }
6919       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6920       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6921                         firstDataArg, Type, InFunctionCall, CallType,
6922                         CheckedVarArgs, UncoveredArg,
6923                         IgnoreStringsWithoutSpecifiers);
6924       return SLCT_CheckedLiteral;
6925     }
6926 
6927     return SLCT_NotALiteral;
6928   }
6929   case Stmt::BinaryOperatorClass: {
6930     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6931 
6932     // A string literal + an int offset is still a string literal.
6933     if (BinOp->isAdditiveOp()) {
6934       Expr::EvalResult LResult, RResult;
6935 
6936       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6937           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6938       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6939           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6940 
6941       if (LIsInt != RIsInt) {
6942         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6943 
6944         if (LIsInt) {
6945           if (BinOpKind == BO_Add) {
6946             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6947             E = BinOp->getRHS();
6948             goto tryAgain;
6949           }
6950         } else {
6951           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6952           E = BinOp->getLHS();
6953           goto tryAgain;
6954         }
6955       }
6956     }
6957 
6958     return SLCT_NotALiteral;
6959   }
6960   case Stmt::UnaryOperatorClass: {
6961     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6962     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6963     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6964       Expr::EvalResult IndexResult;
6965       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6966                                        Expr::SE_NoSideEffects,
6967                                        S.isConstantEvaluated())) {
6968         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6969                    /*RHS is int*/ true);
6970         E = ASE->getBase();
6971         goto tryAgain;
6972       }
6973     }
6974 
6975     return SLCT_NotALiteral;
6976   }
6977 
6978   default:
6979     return SLCT_NotALiteral;
6980   }
6981 }
6982 
6983 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6984   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6985       .Case("scanf", FST_Scanf)
6986       .Cases("printf", "printf0", FST_Printf)
6987       .Cases("NSString", "CFString", FST_NSString)
6988       .Case("strftime", FST_Strftime)
6989       .Case("strfmon", FST_Strfmon)
6990       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6991       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6992       .Case("os_trace", FST_OSLog)
6993       .Case("os_log", FST_OSLog)
6994       .Default(FST_Unknown);
6995 }
6996 
6997 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6998 /// functions) for correct use of format strings.
6999 /// Returns true if a format string has been fully checked.
7000 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7001                                 ArrayRef<const Expr *> Args,
7002                                 bool IsCXXMember,
7003                                 VariadicCallType CallType,
7004                                 SourceLocation Loc, SourceRange Range,
7005                                 llvm::SmallBitVector &CheckedVarArgs) {
7006   FormatStringInfo FSI;
7007   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7008     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7009                                 FSI.FirstDataArg, GetFormatStringType(Format),
7010                                 CallType, Loc, Range, CheckedVarArgs);
7011   return false;
7012 }
7013 
7014 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7015                                 bool HasVAListArg, unsigned format_idx,
7016                                 unsigned firstDataArg, FormatStringType Type,
7017                                 VariadicCallType CallType,
7018                                 SourceLocation Loc, SourceRange Range,
7019                                 llvm::SmallBitVector &CheckedVarArgs) {
7020   // CHECK: printf/scanf-like function is called with no format string.
7021   if (format_idx >= Args.size()) {
7022     Diag(Loc, diag::warn_missing_format_string) << Range;
7023     return false;
7024   }
7025 
7026   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7027 
7028   // CHECK: format string is not a string literal.
7029   //
7030   // Dynamically generated format strings are difficult to
7031   // automatically vet at compile time.  Requiring that format strings
7032   // are string literals: (1) permits the checking of format strings by
7033   // the compiler and thereby (2) can practically remove the source of
7034   // many format string exploits.
7035 
7036   // Format string can be either ObjC string (e.g. @"%d") or
7037   // C string (e.g. "%d")
7038   // ObjC string uses the same format specifiers as C string, so we can use
7039   // the same format string checking logic for both ObjC and C strings.
7040   UncoveredArgHandler UncoveredArg;
7041   StringLiteralCheckType CT =
7042       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7043                             format_idx, firstDataArg, Type, CallType,
7044                             /*IsFunctionCall*/ true, CheckedVarArgs,
7045                             UncoveredArg,
7046                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7047 
7048   // Generate a diagnostic where an uncovered argument is detected.
7049   if (UncoveredArg.hasUncoveredArg()) {
7050     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7051     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7052     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7053   }
7054 
7055   if (CT != SLCT_NotALiteral)
7056     // Literal format string found, check done!
7057     return CT == SLCT_CheckedLiteral;
7058 
7059   // Strftime is particular as it always uses a single 'time' argument,
7060   // so it is safe to pass a non-literal string.
7061   if (Type == FST_Strftime)
7062     return false;
7063 
7064   // Do not emit diag when the string param is a macro expansion and the
7065   // format is either NSString or CFString. This is a hack to prevent
7066   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7067   // which are usually used in place of NS and CF string literals.
7068   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7069   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7070     return false;
7071 
7072   // If there are no arguments specified, warn with -Wformat-security, otherwise
7073   // warn only with -Wformat-nonliteral.
7074   if (Args.size() == firstDataArg) {
7075     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7076       << OrigFormatExpr->getSourceRange();
7077     switch (Type) {
7078     default:
7079       break;
7080     case FST_Kprintf:
7081     case FST_FreeBSDKPrintf:
7082     case FST_Printf:
7083       Diag(FormatLoc, diag::note_format_security_fixit)
7084         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7085       break;
7086     case FST_NSString:
7087       Diag(FormatLoc, diag::note_format_security_fixit)
7088         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7089       break;
7090     }
7091   } else {
7092     Diag(FormatLoc, diag::warn_format_nonliteral)
7093       << OrigFormatExpr->getSourceRange();
7094   }
7095   return false;
7096 }
7097 
7098 namespace {
7099 
7100 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7101 protected:
7102   Sema &S;
7103   const FormatStringLiteral *FExpr;
7104   const Expr *OrigFormatExpr;
7105   const Sema::FormatStringType FSType;
7106   const unsigned FirstDataArg;
7107   const unsigned NumDataArgs;
7108   const char *Beg; // Start of format string.
7109   const bool HasVAListArg;
7110   ArrayRef<const Expr *> Args;
7111   unsigned FormatIdx;
7112   llvm::SmallBitVector CoveredArgs;
7113   bool usesPositionalArgs = false;
7114   bool atFirstArg = true;
7115   bool inFunctionCall;
7116   Sema::VariadicCallType CallType;
7117   llvm::SmallBitVector &CheckedVarArgs;
7118   UncoveredArgHandler &UncoveredArg;
7119 
7120 public:
7121   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7122                      const Expr *origFormatExpr,
7123                      const Sema::FormatStringType type, unsigned firstDataArg,
7124                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7125                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7126                      bool inFunctionCall, Sema::VariadicCallType callType,
7127                      llvm::SmallBitVector &CheckedVarArgs,
7128                      UncoveredArgHandler &UncoveredArg)
7129       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7130         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7131         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7132         inFunctionCall(inFunctionCall), CallType(callType),
7133         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7134     CoveredArgs.resize(numDataArgs);
7135     CoveredArgs.reset();
7136   }
7137 
7138   void DoneProcessing();
7139 
7140   void HandleIncompleteSpecifier(const char *startSpecifier,
7141                                  unsigned specifierLen) override;
7142 
7143   void HandleInvalidLengthModifier(
7144                            const analyze_format_string::FormatSpecifier &FS,
7145                            const analyze_format_string::ConversionSpecifier &CS,
7146                            const char *startSpecifier, unsigned specifierLen,
7147                            unsigned DiagID);
7148 
7149   void HandleNonStandardLengthModifier(
7150                     const analyze_format_string::FormatSpecifier &FS,
7151                     const char *startSpecifier, unsigned specifierLen);
7152 
7153   void HandleNonStandardConversionSpecifier(
7154                     const analyze_format_string::ConversionSpecifier &CS,
7155                     const char *startSpecifier, unsigned specifierLen);
7156 
7157   void HandlePosition(const char *startPos, unsigned posLen) override;
7158 
7159   void HandleInvalidPosition(const char *startSpecifier,
7160                              unsigned specifierLen,
7161                              analyze_format_string::PositionContext p) override;
7162 
7163   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7164 
7165   void HandleNullChar(const char *nullCharacter) override;
7166 
7167   template <typename Range>
7168   static void
7169   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7170                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7171                        bool IsStringLocation, Range StringRange,
7172                        ArrayRef<FixItHint> Fixit = None);
7173 
7174 protected:
7175   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7176                                         const char *startSpec,
7177                                         unsigned specifierLen,
7178                                         const char *csStart, unsigned csLen);
7179 
7180   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7181                                          const char *startSpec,
7182                                          unsigned specifierLen);
7183 
7184   SourceRange getFormatStringRange();
7185   CharSourceRange getSpecifierRange(const char *startSpecifier,
7186                                     unsigned specifierLen);
7187   SourceLocation getLocationOfByte(const char *x);
7188 
7189   const Expr *getDataArg(unsigned i) const;
7190 
7191   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7192                     const analyze_format_string::ConversionSpecifier &CS,
7193                     const char *startSpecifier, unsigned specifierLen,
7194                     unsigned argIndex);
7195 
7196   template <typename Range>
7197   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7198                             bool IsStringLocation, Range StringRange,
7199                             ArrayRef<FixItHint> Fixit = None);
7200 };
7201 
7202 } // namespace
7203 
7204 SourceRange CheckFormatHandler::getFormatStringRange() {
7205   return OrigFormatExpr->getSourceRange();
7206 }
7207 
7208 CharSourceRange CheckFormatHandler::
7209 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7210   SourceLocation Start = getLocationOfByte(startSpecifier);
7211   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7212 
7213   // Advance the end SourceLocation by one due to half-open ranges.
7214   End = End.getLocWithOffset(1);
7215 
7216   return CharSourceRange::getCharRange(Start, End);
7217 }
7218 
7219 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7220   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7221                                   S.getLangOpts(), S.Context.getTargetInfo());
7222 }
7223 
7224 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7225                                                    unsigned specifierLen){
7226   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7227                        getLocationOfByte(startSpecifier),
7228                        /*IsStringLocation*/true,
7229                        getSpecifierRange(startSpecifier, specifierLen));
7230 }
7231 
7232 void CheckFormatHandler::HandleInvalidLengthModifier(
7233     const analyze_format_string::FormatSpecifier &FS,
7234     const analyze_format_string::ConversionSpecifier &CS,
7235     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7236   using namespace analyze_format_string;
7237 
7238   const LengthModifier &LM = FS.getLengthModifier();
7239   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7240 
7241   // See if we know how to fix this length modifier.
7242   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7243   if (FixedLM) {
7244     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7245                          getLocationOfByte(LM.getStart()),
7246                          /*IsStringLocation*/true,
7247                          getSpecifierRange(startSpecifier, specifierLen));
7248 
7249     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7250       << FixedLM->toString()
7251       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7252 
7253   } else {
7254     FixItHint Hint;
7255     if (DiagID == diag::warn_format_nonsensical_length)
7256       Hint = FixItHint::CreateRemoval(LMRange);
7257 
7258     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7259                          getLocationOfByte(LM.getStart()),
7260                          /*IsStringLocation*/true,
7261                          getSpecifierRange(startSpecifier, specifierLen),
7262                          Hint);
7263   }
7264 }
7265 
7266 void CheckFormatHandler::HandleNonStandardLengthModifier(
7267     const analyze_format_string::FormatSpecifier &FS,
7268     const char *startSpecifier, unsigned specifierLen) {
7269   using namespace analyze_format_string;
7270 
7271   const LengthModifier &LM = FS.getLengthModifier();
7272   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7273 
7274   // See if we know how to fix this length modifier.
7275   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7276   if (FixedLM) {
7277     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7278                            << LM.toString() << 0,
7279                          getLocationOfByte(LM.getStart()),
7280                          /*IsStringLocation*/true,
7281                          getSpecifierRange(startSpecifier, specifierLen));
7282 
7283     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7284       << FixedLM->toString()
7285       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7286 
7287   } else {
7288     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7289                            << LM.toString() << 0,
7290                          getLocationOfByte(LM.getStart()),
7291                          /*IsStringLocation*/true,
7292                          getSpecifierRange(startSpecifier, specifierLen));
7293   }
7294 }
7295 
7296 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7297     const analyze_format_string::ConversionSpecifier &CS,
7298     const char *startSpecifier, unsigned specifierLen) {
7299   using namespace analyze_format_string;
7300 
7301   // See if we know how to fix this conversion specifier.
7302   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7303   if (FixedCS) {
7304     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7305                           << CS.toString() << /*conversion specifier*/1,
7306                          getLocationOfByte(CS.getStart()),
7307                          /*IsStringLocation*/true,
7308                          getSpecifierRange(startSpecifier, specifierLen));
7309 
7310     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7311     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7312       << FixedCS->toString()
7313       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7314   } else {
7315     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7316                           << CS.toString() << /*conversion specifier*/1,
7317                          getLocationOfByte(CS.getStart()),
7318                          /*IsStringLocation*/true,
7319                          getSpecifierRange(startSpecifier, specifierLen));
7320   }
7321 }
7322 
7323 void CheckFormatHandler::HandlePosition(const char *startPos,
7324                                         unsigned posLen) {
7325   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7326                                getLocationOfByte(startPos),
7327                                /*IsStringLocation*/true,
7328                                getSpecifierRange(startPos, posLen));
7329 }
7330 
7331 void
7332 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7333                                      analyze_format_string::PositionContext p) {
7334   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7335                          << (unsigned) p,
7336                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7337                        getSpecifierRange(startPos, posLen));
7338 }
7339 
7340 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7341                                             unsigned posLen) {
7342   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7343                                getLocationOfByte(startPos),
7344                                /*IsStringLocation*/true,
7345                                getSpecifierRange(startPos, posLen));
7346 }
7347 
7348 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7349   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7350     // The presence of a null character is likely an error.
7351     EmitFormatDiagnostic(
7352       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7353       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7354       getFormatStringRange());
7355   }
7356 }
7357 
7358 // Note that this may return NULL if there was an error parsing or building
7359 // one of the argument expressions.
7360 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7361   return Args[FirstDataArg + i];
7362 }
7363 
7364 void CheckFormatHandler::DoneProcessing() {
7365   // Does the number of data arguments exceed the number of
7366   // format conversions in the format string?
7367   if (!HasVAListArg) {
7368       // Find any arguments that weren't covered.
7369     CoveredArgs.flip();
7370     signed notCoveredArg = CoveredArgs.find_first();
7371     if (notCoveredArg >= 0) {
7372       assert((unsigned)notCoveredArg < NumDataArgs);
7373       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7374     } else {
7375       UncoveredArg.setAllCovered();
7376     }
7377   }
7378 }
7379 
7380 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7381                                    const Expr *ArgExpr) {
7382   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7383          "Invalid state");
7384 
7385   if (!ArgExpr)
7386     return;
7387 
7388   SourceLocation Loc = ArgExpr->getBeginLoc();
7389 
7390   if (S.getSourceManager().isInSystemMacro(Loc))
7391     return;
7392 
7393   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7394   for (auto E : DiagnosticExprs)
7395     PDiag << E->getSourceRange();
7396 
7397   CheckFormatHandler::EmitFormatDiagnostic(
7398                                   S, IsFunctionCall, DiagnosticExprs[0],
7399                                   PDiag, Loc, /*IsStringLocation*/false,
7400                                   DiagnosticExprs[0]->getSourceRange());
7401 }
7402 
7403 bool
7404 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7405                                                      SourceLocation Loc,
7406                                                      const char *startSpec,
7407                                                      unsigned specifierLen,
7408                                                      const char *csStart,
7409                                                      unsigned csLen) {
7410   bool keepGoing = true;
7411   if (argIndex < NumDataArgs) {
7412     // Consider the argument coverered, even though the specifier doesn't
7413     // make sense.
7414     CoveredArgs.set(argIndex);
7415   }
7416   else {
7417     // If argIndex exceeds the number of data arguments we
7418     // don't issue a warning because that is just a cascade of warnings (and
7419     // they may have intended '%%' anyway). We don't want to continue processing
7420     // the format string after this point, however, as we will like just get
7421     // gibberish when trying to match arguments.
7422     keepGoing = false;
7423   }
7424 
7425   StringRef Specifier(csStart, csLen);
7426 
7427   // If the specifier in non-printable, it could be the first byte of a UTF-8
7428   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7429   // hex value.
7430   std::string CodePointStr;
7431   if (!llvm::sys::locale::isPrint(*csStart)) {
7432     llvm::UTF32 CodePoint;
7433     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7434     const llvm::UTF8 *E =
7435         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7436     llvm::ConversionResult Result =
7437         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7438 
7439     if (Result != llvm::conversionOK) {
7440       unsigned char FirstChar = *csStart;
7441       CodePoint = (llvm::UTF32)FirstChar;
7442     }
7443 
7444     llvm::raw_string_ostream OS(CodePointStr);
7445     if (CodePoint < 256)
7446       OS << "\\x" << llvm::format("%02x", CodePoint);
7447     else if (CodePoint <= 0xFFFF)
7448       OS << "\\u" << llvm::format("%04x", CodePoint);
7449     else
7450       OS << "\\U" << llvm::format("%08x", CodePoint);
7451     OS.flush();
7452     Specifier = CodePointStr;
7453   }
7454 
7455   EmitFormatDiagnostic(
7456       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7457       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7458 
7459   return keepGoing;
7460 }
7461 
7462 void
7463 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7464                                                       const char *startSpec,
7465                                                       unsigned specifierLen) {
7466   EmitFormatDiagnostic(
7467     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7468     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7469 }
7470 
7471 bool
7472 CheckFormatHandler::CheckNumArgs(
7473   const analyze_format_string::FormatSpecifier &FS,
7474   const analyze_format_string::ConversionSpecifier &CS,
7475   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7476 
7477   if (argIndex >= NumDataArgs) {
7478     PartialDiagnostic PDiag = FS.usesPositionalArg()
7479       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7480            << (argIndex+1) << NumDataArgs)
7481       : S.PDiag(diag::warn_printf_insufficient_data_args);
7482     EmitFormatDiagnostic(
7483       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7484       getSpecifierRange(startSpecifier, specifierLen));
7485 
7486     // Since more arguments than conversion tokens are given, by extension
7487     // all arguments are covered, so mark this as so.
7488     UncoveredArg.setAllCovered();
7489     return false;
7490   }
7491   return true;
7492 }
7493 
7494 template<typename Range>
7495 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7496                                               SourceLocation Loc,
7497                                               bool IsStringLocation,
7498                                               Range StringRange,
7499                                               ArrayRef<FixItHint> FixIt) {
7500   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7501                        Loc, IsStringLocation, StringRange, FixIt);
7502 }
7503 
7504 /// If the format string is not within the function call, emit a note
7505 /// so that the function call and string are in diagnostic messages.
7506 ///
7507 /// \param InFunctionCall if true, the format string is within the function
7508 /// call and only one diagnostic message will be produced.  Otherwise, an
7509 /// extra note will be emitted pointing to location of the format string.
7510 ///
7511 /// \param ArgumentExpr the expression that is passed as the format string
7512 /// argument in the function call.  Used for getting locations when two
7513 /// diagnostics are emitted.
7514 ///
7515 /// \param PDiag the callee should already have provided any strings for the
7516 /// diagnostic message.  This function only adds locations and fixits
7517 /// to diagnostics.
7518 ///
7519 /// \param Loc primary location for diagnostic.  If two diagnostics are
7520 /// required, one will be at Loc and a new SourceLocation will be created for
7521 /// the other one.
7522 ///
7523 /// \param IsStringLocation if true, Loc points to the format string should be
7524 /// used for the note.  Otherwise, Loc points to the argument list and will
7525 /// be used with PDiag.
7526 ///
7527 /// \param StringRange some or all of the string to highlight.  This is
7528 /// templated so it can accept either a CharSourceRange or a SourceRange.
7529 ///
7530 /// \param FixIt optional fix it hint for the format string.
7531 template <typename Range>
7532 void CheckFormatHandler::EmitFormatDiagnostic(
7533     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7534     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7535     Range StringRange, ArrayRef<FixItHint> FixIt) {
7536   if (InFunctionCall) {
7537     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7538     D << StringRange;
7539     D << FixIt;
7540   } else {
7541     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7542       << ArgumentExpr->getSourceRange();
7543 
7544     const Sema::SemaDiagnosticBuilder &Note =
7545       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7546              diag::note_format_string_defined);
7547 
7548     Note << StringRange;
7549     Note << FixIt;
7550   }
7551 }
7552 
7553 //===--- CHECK: Printf format string checking ------------------------------===//
7554 
7555 namespace {
7556 
7557 class CheckPrintfHandler : public CheckFormatHandler {
7558 public:
7559   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7560                      const Expr *origFormatExpr,
7561                      const Sema::FormatStringType type, unsigned firstDataArg,
7562                      unsigned numDataArgs, bool isObjC, const char *beg,
7563                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7564                      unsigned formatIdx, bool inFunctionCall,
7565                      Sema::VariadicCallType CallType,
7566                      llvm::SmallBitVector &CheckedVarArgs,
7567                      UncoveredArgHandler &UncoveredArg)
7568       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7569                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7570                            inFunctionCall, CallType, CheckedVarArgs,
7571                            UncoveredArg) {}
7572 
7573   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7574 
7575   /// Returns true if '%@' specifiers are allowed in the format string.
7576   bool allowsObjCArg() const {
7577     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7578            FSType == Sema::FST_OSTrace;
7579   }
7580 
7581   bool HandleInvalidPrintfConversionSpecifier(
7582                                       const analyze_printf::PrintfSpecifier &FS,
7583                                       const char *startSpecifier,
7584                                       unsigned specifierLen) override;
7585 
7586   void handleInvalidMaskType(StringRef MaskType) override;
7587 
7588   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7589                              const char *startSpecifier,
7590                              unsigned specifierLen) override;
7591   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7592                        const char *StartSpecifier,
7593                        unsigned SpecifierLen,
7594                        const Expr *E);
7595 
7596   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7597                     const char *startSpecifier, unsigned specifierLen);
7598   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7599                            const analyze_printf::OptionalAmount &Amt,
7600                            unsigned type,
7601                            const char *startSpecifier, unsigned specifierLen);
7602   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7603                   const analyze_printf::OptionalFlag &flag,
7604                   const char *startSpecifier, unsigned specifierLen);
7605   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7606                          const analyze_printf::OptionalFlag &ignoredFlag,
7607                          const analyze_printf::OptionalFlag &flag,
7608                          const char *startSpecifier, unsigned specifierLen);
7609   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7610                            const Expr *E);
7611 
7612   void HandleEmptyObjCModifierFlag(const char *startFlag,
7613                                    unsigned flagLen) override;
7614 
7615   void HandleInvalidObjCModifierFlag(const char *startFlag,
7616                                             unsigned flagLen) override;
7617 
7618   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7619                                            const char *flagsEnd,
7620                                            const char *conversionPosition)
7621                                              override;
7622 };
7623 
7624 } // namespace
7625 
7626 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7627                                       const analyze_printf::PrintfSpecifier &FS,
7628                                       const char *startSpecifier,
7629                                       unsigned specifierLen) {
7630   const analyze_printf::PrintfConversionSpecifier &CS =
7631     FS.getConversionSpecifier();
7632 
7633   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7634                                           getLocationOfByte(CS.getStart()),
7635                                           startSpecifier, specifierLen,
7636                                           CS.getStart(), CS.getLength());
7637 }
7638 
7639 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7640   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7641 }
7642 
7643 bool CheckPrintfHandler::HandleAmount(
7644                                const analyze_format_string::OptionalAmount &Amt,
7645                                unsigned k, const char *startSpecifier,
7646                                unsigned specifierLen) {
7647   if (Amt.hasDataArgument()) {
7648     if (!HasVAListArg) {
7649       unsigned argIndex = Amt.getArgIndex();
7650       if (argIndex >= NumDataArgs) {
7651         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7652                                << k,
7653                              getLocationOfByte(Amt.getStart()),
7654                              /*IsStringLocation*/true,
7655                              getSpecifierRange(startSpecifier, specifierLen));
7656         // Don't do any more checking.  We will just emit
7657         // spurious errors.
7658         return false;
7659       }
7660 
7661       // Type check the data argument.  It should be an 'int'.
7662       // Although not in conformance with C99, we also allow the argument to be
7663       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7664       // doesn't emit a warning for that case.
7665       CoveredArgs.set(argIndex);
7666       const Expr *Arg = getDataArg(argIndex);
7667       if (!Arg)
7668         return false;
7669 
7670       QualType T = Arg->getType();
7671 
7672       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7673       assert(AT.isValid());
7674 
7675       if (!AT.matchesType(S.Context, T)) {
7676         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7677                                << k << AT.getRepresentativeTypeName(S.Context)
7678                                << T << Arg->getSourceRange(),
7679                              getLocationOfByte(Amt.getStart()),
7680                              /*IsStringLocation*/true,
7681                              getSpecifierRange(startSpecifier, specifierLen));
7682         // Don't do any more checking.  We will just emit
7683         // spurious errors.
7684         return false;
7685       }
7686     }
7687   }
7688   return true;
7689 }
7690 
7691 void CheckPrintfHandler::HandleInvalidAmount(
7692                                       const analyze_printf::PrintfSpecifier &FS,
7693                                       const analyze_printf::OptionalAmount &Amt,
7694                                       unsigned type,
7695                                       const char *startSpecifier,
7696                                       unsigned specifierLen) {
7697   const analyze_printf::PrintfConversionSpecifier &CS =
7698     FS.getConversionSpecifier();
7699 
7700   FixItHint fixit =
7701     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7702       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7703                                  Amt.getConstantLength()))
7704       : FixItHint();
7705 
7706   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7707                          << type << CS.toString(),
7708                        getLocationOfByte(Amt.getStart()),
7709                        /*IsStringLocation*/true,
7710                        getSpecifierRange(startSpecifier, specifierLen),
7711                        fixit);
7712 }
7713 
7714 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7715                                     const analyze_printf::OptionalFlag &flag,
7716                                     const char *startSpecifier,
7717                                     unsigned specifierLen) {
7718   // Warn about pointless flag with a fixit removal.
7719   const analyze_printf::PrintfConversionSpecifier &CS =
7720     FS.getConversionSpecifier();
7721   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7722                          << flag.toString() << CS.toString(),
7723                        getLocationOfByte(flag.getPosition()),
7724                        /*IsStringLocation*/true,
7725                        getSpecifierRange(startSpecifier, specifierLen),
7726                        FixItHint::CreateRemoval(
7727                          getSpecifierRange(flag.getPosition(), 1)));
7728 }
7729 
7730 void CheckPrintfHandler::HandleIgnoredFlag(
7731                                 const analyze_printf::PrintfSpecifier &FS,
7732                                 const analyze_printf::OptionalFlag &ignoredFlag,
7733                                 const analyze_printf::OptionalFlag &flag,
7734                                 const char *startSpecifier,
7735                                 unsigned specifierLen) {
7736   // Warn about ignored flag with a fixit removal.
7737   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7738                          << ignoredFlag.toString() << flag.toString(),
7739                        getLocationOfByte(ignoredFlag.getPosition()),
7740                        /*IsStringLocation*/true,
7741                        getSpecifierRange(startSpecifier, specifierLen),
7742                        FixItHint::CreateRemoval(
7743                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7744 }
7745 
7746 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7747                                                      unsigned flagLen) {
7748   // Warn about an empty flag.
7749   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7750                        getLocationOfByte(startFlag),
7751                        /*IsStringLocation*/true,
7752                        getSpecifierRange(startFlag, flagLen));
7753 }
7754 
7755 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7756                                                        unsigned flagLen) {
7757   // Warn about an invalid flag.
7758   auto Range = getSpecifierRange(startFlag, flagLen);
7759   StringRef flag(startFlag, flagLen);
7760   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7761                       getLocationOfByte(startFlag),
7762                       /*IsStringLocation*/true,
7763                       Range, FixItHint::CreateRemoval(Range));
7764 }
7765 
7766 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7767     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7768     // Warn about using '[...]' without a '@' conversion.
7769     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7770     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7771     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7772                          getLocationOfByte(conversionPosition),
7773                          /*IsStringLocation*/true,
7774                          Range, FixItHint::CreateRemoval(Range));
7775 }
7776 
7777 // Determines if the specified is a C++ class or struct containing
7778 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7779 // "c_str()").
7780 template<typename MemberKind>
7781 static llvm::SmallPtrSet<MemberKind*, 1>
7782 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7783   const RecordType *RT = Ty->getAs<RecordType>();
7784   llvm::SmallPtrSet<MemberKind*, 1> Results;
7785 
7786   if (!RT)
7787     return Results;
7788   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7789   if (!RD || !RD->getDefinition())
7790     return Results;
7791 
7792   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7793                  Sema::LookupMemberName);
7794   R.suppressDiagnostics();
7795 
7796   // We just need to include all members of the right kind turned up by the
7797   // filter, at this point.
7798   if (S.LookupQualifiedName(R, RT->getDecl()))
7799     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7800       NamedDecl *decl = (*I)->getUnderlyingDecl();
7801       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7802         Results.insert(FK);
7803     }
7804   return Results;
7805 }
7806 
7807 /// Check if we could call '.c_str()' on an object.
7808 ///
7809 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7810 /// allow the call, or if it would be ambiguous).
7811 bool Sema::hasCStrMethod(const Expr *E) {
7812   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7813 
7814   MethodSet Results =
7815       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7816   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7817        MI != ME; ++MI)
7818     if ((*MI)->getMinRequiredArguments() == 0)
7819       return true;
7820   return false;
7821 }
7822 
7823 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7824 // better diagnostic if so. AT is assumed to be valid.
7825 // Returns true when a c_str() conversion method is found.
7826 bool CheckPrintfHandler::checkForCStrMembers(
7827     const analyze_printf::ArgType &AT, const Expr *E) {
7828   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7829 
7830   MethodSet Results =
7831       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7832 
7833   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7834        MI != ME; ++MI) {
7835     const CXXMethodDecl *Method = *MI;
7836     if (Method->getMinRequiredArguments() == 0 &&
7837         AT.matchesType(S.Context, Method->getReturnType())) {
7838       // FIXME: Suggest parens if the expression needs them.
7839       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7840       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7841           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7842       return true;
7843     }
7844   }
7845 
7846   return false;
7847 }
7848 
7849 bool
7850 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7851                                             &FS,
7852                                           const char *startSpecifier,
7853                                           unsigned specifierLen) {
7854   using namespace analyze_format_string;
7855   using namespace analyze_printf;
7856 
7857   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7858 
7859   if (FS.consumesDataArgument()) {
7860     if (atFirstArg) {
7861         atFirstArg = false;
7862         usesPositionalArgs = FS.usesPositionalArg();
7863     }
7864     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7865       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7866                                         startSpecifier, specifierLen);
7867       return false;
7868     }
7869   }
7870 
7871   // First check if the field width, precision, and conversion specifier
7872   // have matching data arguments.
7873   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7874                     startSpecifier, specifierLen)) {
7875     return false;
7876   }
7877 
7878   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7879                     startSpecifier, specifierLen)) {
7880     return false;
7881   }
7882 
7883   if (!CS.consumesDataArgument()) {
7884     // FIXME: Technically specifying a precision or field width here
7885     // makes no sense.  Worth issuing a warning at some point.
7886     return true;
7887   }
7888 
7889   // Consume the argument.
7890   unsigned argIndex = FS.getArgIndex();
7891   if (argIndex < NumDataArgs) {
7892     // The check to see if the argIndex is valid will come later.
7893     // We set the bit here because we may exit early from this
7894     // function if we encounter some other error.
7895     CoveredArgs.set(argIndex);
7896   }
7897 
7898   // FreeBSD kernel extensions.
7899   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7900       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7901     // We need at least two arguments.
7902     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7903       return false;
7904 
7905     // Claim the second argument.
7906     CoveredArgs.set(argIndex + 1);
7907 
7908     // Type check the first argument (int for %b, pointer for %D)
7909     const Expr *Ex = getDataArg(argIndex);
7910     const analyze_printf::ArgType &AT =
7911       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7912         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7913     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7914       EmitFormatDiagnostic(
7915           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7916               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7917               << false << Ex->getSourceRange(),
7918           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7919           getSpecifierRange(startSpecifier, specifierLen));
7920 
7921     // Type check the second argument (char * for both %b and %D)
7922     Ex = getDataArg(argIndex + 1);
7923     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7924     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7925       EmitFormatDiagnostic(
7926           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7927               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7928               << false << Ex->getSourceRange(),
7929           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7930           getSpecifierRange(startSpecifier, specifierLen));
7931 
7932      return true;
7933   }
7934 
7935   // Check for using an Objective-C specific conversion specifier
7936   // in a non-ObjC literal.
7937   if (!allowsObjCArg() && CS.isObjCArg()) {
7938     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7939                                                   specifierLen);
7940   }
7941 
7942   // %P can only be used with os_log.
7943   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7944     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7945                                                   specifierLen);
7946   }
7947 
7948   // %n is not allowed with os_log.
7949   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7950     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7951                          getLocationOfByte(CS.getStart()),
7952                          /*IsStringLocation*/ false,
7953                          getSpecifierRange(startSpecifier, specifierLen));
7954 
7955     return true;
7956   }
7957 
7958   // Only scalars are allowed for os_trace.
7959   if (FSType == Sema::FST_OSTrace &&
7960       (CS.getKind() == ConversionSpecifier::PArg ||
7961        CS.getKind() == ConversionSpecifier::sArg ||
7962        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7963     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7964                                                   specifierLen);
7965   }
7966 
7967   // Check for use of public/private annotation outside of os_log().
7968   if (FSType != Sema::FST_OSLog) {
7969     if (FS.isPublic().isSet()) {
7970       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7971                                << "public",
7972                            getLocationOfByte(FS.isPublic().getPosition()),
7973                            /*IsStringLocation*/ false,
7974                            getSpecifierRange(startSpecifier, specifierLen));
7975     }
7976     if (FS.isPrivate().isSet()) {
7977       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7978                                << "private",
7979                            getLocationOfByte(FS.isPrivate().getPosition()),
7980                            /*IsStringLocation*/ false,
7981                            getSpecifierRange(startSpecifier, specifierLen));
7982     }
7983   }
7984 
7985   // Check for invalid use of field width
7986   if (!FS.hasValidFieldWidth()) {
7987     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7988         startSpecifier, specifierLen);
7989   }
7990 
7991   // Check for invalid use of precision
7992   if (!FS.hasValidPrecision()) {
7993     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7994         startSpecifier, specifierLen);
7995   }
7996 
7997   // Precision is mandatory for %P specifier.
7998   if (CS.getKind() == ConversionSpecifier::PArg &&
7999       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8000     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8001                          getLocationOfByte(startSpecifier),
8002                          /*IsStringLocation*/ false,
8003                          getSpecifierRange(startSpecifier, specifierLen));
8004   }
8005 
8006   // Check each flag does not conflict with any other component.
8007   if (!FS.hasValidThousandsGroupingPrefix())
8008     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8009   if (!FS.hasValidLeadingZeros())
8010     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8011   if (!FS.hasValidPlusPrefix())
8012     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8013   if (!FS.hasValidSpacePrefix())
8014     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8015   if (!FS.hasValidAlternativeForm())
8016     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8017   if (!FS.hasValidLeftJustified())
8018     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8019 
8020   // Check that flags are not ignored by another flag
8021   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8022     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8023         startSpecifier, specifierLen);
8024   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8025     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8026             startSpecifier, specifierLen);
8027 
8028   // Check the length modifier is valid with the given conversion specifier.
8029   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8030                                  S.getLangOpts()))
8031     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8032                                 diag::warn_format_nonsensical_length);
8033   else if (!FS.hasStandardLengthModifier())
8034     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8035   else if (!FS.hasStandardLengthConversionCombination())
8036     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8037                                 diag::warn_format_non_standard_conversion_spec);
8038 
8039   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8040     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8041 
8042   // The remaining checks depend on the data arguments.
8043   if (HasVAListArg)
8044     return true;
8045 
8046   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8047     return false;
8048 
8049   const Expr *Arg = getDataArg(argIndex);
8050   if (!Arg)
8051     return true;
8052 
8053   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8054 }
8055 
8056 static bool requiresParensToAddCast(const Expr *E) {
8057   // FIXME: We should have a general way to reason about operator
8058   // precedence and whether parens are actually needed here.
8059   // Take care of a few common cases where they aren't.
8060   const Expr *Inside = E->IgnoreImpCasts();
8061   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8062     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8063 
8064   switch (Inside->getStmtClass()) {
8065   case Stmt::ArraySubscriptExprClass:
8066   case Stmt::CallExprClass:
8067   case Stmt::CharacterLiteralClass:
8068   case Stmt::CXXBoolLiteralExprClass:
8069   case Stmt::DeclRefExprClass:
8070   case Stmt::FloatingLiteralClass:
8071   case Stmt::IntegerLiteralClass:
8072   case Stmt::MemberExprClass:
8073   case Stmt::ObjCArrayLiteralClass:
8074   case Stmt::ObjCBoolLiteralExprClass:
8075   case Stmt::ObjCBoxedExprClass:
8076   case Stmt::ObjCDictionaryLiteralClass:
8077   case Stmt::ObjCEncodeExprClass:
8078   case Stmt::ObjCIvarRefExprClass:
8079   case Stmt::ObjCMessageExprClass:
8080   case Stmt::ObjCPropertyRefExprClass:
8081   case Stmt::ObjCStringLiteralClass:
8082   case Stmt::ObjCSubscriptRefExprClass:
8083   case Stmt::ParenExprClass:
8084   case Stmt::StringLiteralClass:
8085   case Stmt::UnaryOperatorClass:
8086     return false;
8087   default:
8088     return true;
8089   }
8090 }
8091 
8092 static std::pair<QualType, StringRef>
8093 shouldNotPrintDirectly(const ASTContext &Context,
8094                        QualType IntendedTy,
8095                        const Expr *E) {
8096   // Use a 'while' to peel off layers of typedefs.
8097   QualType TyTy = IntendedTy;
8098   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8099     StringRef Name = UserTy->getDecl()->getName();
8100     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8101       .Case("CFIndex", Context.getNSIntegerType())
8102       .Case("NSInteger", Context.getNSIntegerType())
8103       .Case("NSUInteger", Context.getNSUIntegerType())
8104       .Case("SInt32", Context.IntTy)
8105       .Case("UInt32", Context.UnsignedIntTy)
8106       .Default(QualType());
8107 
8108     if (!CastTy.isNull())
8109       return std::make_pair(CastTy, Name);
8110 
8111     TyTy = UserTy->desugar();
8112   }
8113 
8114   // Strip parens if necessary.
8115   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8116     return shouldNotPrintDirectly(Context,
8117                                   PE->getSubExpr()->getType(),
8118                                   PE->getSubExpr());
8119 
8120   // If this is a conditional expression, then its result type is constructed
8121   // via usual arithmetic conversions and thus there might be no necessary
8122   // typedef sugar there.  Recurse to operands to check for NSInteger &
8123   // Co. usage condition.
8124   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8125     QualType TrueTy, FalseTy;
8126     StringRef TrueName, FalseName;
8127 
8128     std::tie(TrueTy, TrueName) =
8129       shouldNotPrintDirectly(Context,
8130                              CO->getTrueExpr()->getType(),
8131                              CO->getTrueExpr());
8132     std::tie(FalseTy, FalseName) =
8133       shouldNotPrintDirectly(Context,
8134                              CO->getFalseExpr()->getType(),
8135                              CO->getFalseExpr());
8136 
8137     if (TrueTy == FalseTy)
8138       return std::make_pair(TrueTy, TrueName);
8139     else if (TrueTy.isNull())
8140       return std::make_pair(FalseTy, FalseName);
8141     else if (FalseTy.isNull())
8142       return std::make_pair(TrueTy, TrueName);
8143   }
8144 
8145   return std::make_pair(QualType(), StringRef());
8146 }
8147 
8148 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8149 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8150 /// type do not count.
8151 static bool
8152 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8153   QualType From = ICE->getSubExpr()->getType();
8154   QualType To = ICE->getType();
8155   // It's an integer promotion if the destination type is the promoted
8156   // source type.
8157   if (ICE->getCastKind() == CK_IntegralCast &&
8158       From->isPromotableIntegerType() &&
8159       S.Context.getPromotedIntegerType(From) == To)
8160     return true;
8161   // Look through vector types, since we do default argument promotion for
8162   // those in OpenCL.
8163   if (const auto *VecTy = From->getAs<ExtVectorType>())
8164     From = VecTy->getElementType();
8165   if (const auto *VecTy = To->getAs<ExtVectorType>())
8166     To = VecTy->getElementType();
8167   // It's a floating promotion if the source type is a lower rank.
8168   return ICE->getCastKind() == CK_FloatingCast &&
8169          S.Context.getFloatingTypeOrder(From, To) < 0;
8170 }
8171 
8172 bool
8173 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8174                                     const char *StartSpecifier,
8175                                     unsigned SpecifierLen,
8176                                     const Expr *E) {
8177   using namespace analyze_format_string;
8178   using namespace analyze_printf;
8179 
8180   // Now type check the data expression that matches the
8181   // format specifier.
8182   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8183   if (!AT.isValid())
8184     return true;
8185 
8186   QualType ExprTy = E->getType();
8187   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8188     ExprTy = TET->getUnderlyingExpr()->getType();
8189   }
8190 
8191   // Diagnose attempts to print a boolean value as a character. Unlike other
8192   // -Wformat diagnostics, this is fine from a type perspective, but it still
8193   // doesn't make sense.
8194   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8195       E->isKnownToHaveBooleanValue()) {
8196     const CharSourceRange &CSR =
8197         getSpecifierRange(StartSpecifier, SpecifierLen);
8198     SmallString<4> FSString;
8199     llvm::raw_svector_ostream os(FSString);
8200     FS.toString(os);
8201     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8202                              << FSString,
8203                          E->getExprLoc(), false, CSR);
8204     return true;
8205   }
8206 
8207   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8208   if (Match == analyze_printf::ArgType::Match)
8209     return true;
8210 
8211   // Look through argument promotions for our error message's reported type.
8212   // This includes the integral and floating promotions, but excludes array
8213   // and function pointer decay (seeing that an argument intended to be a
8214   // string has type 'char [6]' is probably more confusing than 'char *') and
8215   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8216   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8217     if (isArithmeticArgumentPromotion(S, ICE)) {
8218       E = ICE->getSubExpr();
8219       ExprTy = E->getType();
8220 
8221       // Check if we didn't match because of an implicit cast from a 'char'
8222       // or 'short' to an 'int'.  This is done because printf is a varargs
8223       // function.
8224       if (ICE->getType() == S.Context.IntTy ||
8225           ICE->getType() == S.Context.UnsignedIntTy) {
8226         // All further checking is done on the subexpression
8227         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8228             AT.matchesType(S.Context, ExprTy);
8229         if (ImplicitMatch == analyze_printf::ArgType::Match)
8230           return true;
8231         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8232             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8233           Match = ImplicitMatch;
8234       }
8235     }
8236   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8237     // Special case for 'a', which has type 'int' in C.
8238     // Note, however, that we do /not/ want to treat multibyte constants like
8239     // 'MooV' as characters! This form is deprecated but still exists.
8240     if (ExprTy == S.Context.IntTy)
8241       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8242         ExprTy = S.Context.CharTy;
8243   }
8244 
8245   // Look through enums to their underlying type.
8246   bool IsEnum = false;
8247   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8248     ExprTy = EnumTy->getDecl()->getIntegerType();
8249     IsEnum = true;
8250   }
8251 
8252   // %C in an Objective-C context prints a unichar, not a wchar_t.
8253   // If the argument is an integer of some kind, believe the %C and suggest
8254   // a cast instead of changing the conversion specifier.
8255   QualType IntendedTy = ExprTy;
8256   if (isObjCContext() &&
8257       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8258     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8259         !ExprTy->isCharType()) {
8260       // 'unichar' is defined as a typedef of unsigned short, but we should
8261       // prefer using the typedef if it is visible.
8262       IntendedTy = S.Context.UnsignedShortTy;
8263 
8264       // While we are here, check if the value is an IntegerLiteral that happens
8265       // to be within the valid range.
8266       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8267         const llvm::APInt &V = IL->getValue();
8268         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8269           return true;
8270       }
8271 
8272       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8273                           Sema::LookupOrdinaryName);
8274       if (S.LookupName(Result, S.getCurScope())) {
8275         NamedDecl *ND = Result.getFoundDecl();
8276         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8277           if (TD->getUnderlyingType() == IntendedTy)
8278             IntendedTy = S.Context.getTypedefType(TD);
8279       }
8280     }
8281   }
8282 
8283   // Special-case some of Darwin's platform-independence types by suggesting
8284   // casts to primitive types that are known to be large enough.
8285   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8286   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8287     QualType CastTy;
8288     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8289     if (!CastTy.isNull()) {
8290       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8291       // (long in ASTContext). Only complain to pedants.
8292       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8293           (AT.isSizeT() || AT.isPtrdiffT()) &&
8294           AT.matchesType(S.Context, CastTy))
8295         Match = ArgType::NoMatchPedantic;
8296       IntendedTy = CastTy;
8297       ShouldNotPrintDirectly = true;
8298     }
8299   }
8300 
8301   // We may be able to offer a FixItHint if it is a supported type.
8302   PrintfSpecifier fixedFS = FS;
8303   bool Success =
8304       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8305 
8306   if (Success) {
8307     // Get the fix string from the fixed format specifier
8308     SmallString<16> buf;
8309     llvm::raw_svector_ostream os(buf);
8310     fixedFS.toString(os);
8311 
8312     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8313 
8314     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8315       unsigned Diag;
8316       switch (Match) {
8317       case ArgType::Match: llvm_unreachable("expected non-matching");
8318       case ArgType::NoMatchPedantic:
8319         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8320         break;
8321       case ArgType::NoMatchTypeConfusion:
8322         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8323         break;
8324       case ArgType::NoMatch:
8325         Diag = diag::warn_format_conversion_argument_type_mismatch;
8326         break;
8327       }
8328 
8329       // In this case, the specifier is wrong and should be changed to match
8330       // the argument.
8331       EmitFormatDiagnostic(S.PDiag(Diag)
8332                                << AT.getRepresentativeTypeName(S.Context)
8333                                << IntendedTy << IsEnum << E->getSourceRange(),
8334                            E->getBeginLoc(),
8335                            /*IsStringLocation*/ false, SpecRange,
8336                            FixItHint::CreateReplacement(SpecRange, os.str()));
8337     } else {
8338       // The canonical type for formatting this value is different from the
8339       // actual type of the expression. (This occurs, for example, with Darwin's
8340       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8341       // should be printed as 'long' for 64-bit compatibility.)
8342       // Rather than emitting a normal format/argument mismatch, we want to
8343       // add a cast to the recommended type (and correct the format string
8344       // if necessary).
8345       SmallString<16> CastBuf;
8346       llvm::raw_svector_ostream CastFix(CastBuf);
8347       CastFix << "(";
8348       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8349       CastFix << ")";
8350 
8351       SmallVector<FixItHint,4> Hints;
8352       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8353         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8354 
8355       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8356         // If there's already a cast present, just replace it.
8357         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8358         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8359 
8360       } else if (!requiresParensToAddCast(E)) {
8361         // If the expression has high enough precedence,
8362         // just write the C-style cast.
8363         Hints.push_back(
8364             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8365       } else {
8366         // Otherwise, add parens around the expression as well as the cast.
8367         CastFix << "(";
8368         Hints.push_back(
8369             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8370 
8371         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8372         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8373       }
8374 
8375       if (ShouldNotPrintDirectly) {
8376         // The expression has a type that should not be printed directly.
8377         // We extract the name from the typedef because we don't want to show
8378         // the underlying type in the diagnostic.
8379         StringRef Name;
8380         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8381           Name = TypedefTy->getDecl()->getName();
8382         else
8383           Name = CastTyName;
8384         unsigned Diag = Match == ArgType::NoMatchPedantic
8385                             ? diag::warn_format_argument_needs_cast_pedantic
8386                             : diag::warn_format_argument_needs_cast;
8387         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8388                                            << E->getSourceRange(),
8389                              E->getBeginLoc(), /*IsStringLocation=*/false,
8390                              SpecRange, Hints);
8391       } else {
8392         // In this case, the expression could be printed using a different
8393         // specifier, but we've decided that the specifier is probably correct
8394         // and we should cast instead. Just use the normal warning message.
8395         EmitFormatDiagnostic(
8396             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8397                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8398                 << E->getSourceRange(),
8399             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8400       }
8401     }
8402   } else {
8403     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8404                                                    SpecifierLen);
8405     // Since the warning for passing non-POD types to variadic functions
8406     // was deferred until now, we emit a warning for non-POD
8407     // arguments here.
8408     switch (S.isValidVarArgType(ExprTy)) {
8409     case Sema::VAK_Valid:
8410     case Sema::VAK_ValidInCXX11: {
8411       unsigned Diag;
8412       switch (Match) {
8413       case ArgType::Match: llvm_unreachable("expected non-matching");
8414       case ArgType::NoMatchPedantic:
8415         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8416         break;
8417       case ArgType::NoMatchTypeConfusion:
8418         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8419         break;
8420       case ArgType::NoMatch:
8421         Diag = diag::warn_format_conversion_argument_type_mismatch;
8422         break;
8423       }
8424 
8425       EmitFormatDiagnostic(
8426           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8427                         << IsEnum << CSR << E->getSourceRange(),
8428           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8429       break;
8430     }
8431     case Sema::VAK_Undefined:
8432     case Sema::VAK_MSVCUndefined:
8433       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8434                                << S.getLangOpts().CPlusPlus11 << ExprTy
8435                                << CallType
8436                                << AT.getRepresentativeTypeName(S.Context) << CSR
8437                                << E->getSourceRange(),
8438                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8439       checkForCStrMembers(AT, E);
8440       break;
8441 
8442     case Sema::VAK_Invalid:
8443       if (ExprTy->isObjCObjectType())
8444         EmitFormatDiagnostic(
8445             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8446                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8447                 << AT.getRepresentativeTypeName(S.Context) << CSR
8448                 << E->getSourceRange(),
8449             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8450       else
8451         // FIXME: If this is an initializer list, suggest removing the braces
8452         // or inserting a cast to the target type.
8453         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8454             << isa<InitListExpr>(E) << ExprTy << CallType
8455             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8456       break;
8457     }
8458 
8459     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8460            "format string specifier index out of range");
8461     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8462   }
8463 
8464   return true;
8465 }
8466 
8467 //===--- CHECK: Scanf format string checking ------------------------------===//
8468 
8469 namespace {
8470 
8471 class CheckScanfHandler : public CheckFormatHandler {
8472 public:
8473   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8474                     const Expr *origFormatExpr, Sema::FormatStringType type,
8475                     unsigned firstDataArg, unsigned numDataArgs,
8476                     const char *beg, bool hasVAListArg,
8477                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8478                     bool inFunctionCall, Sema::VariadicCallType CallType,
8479                     llvm::SmallBitVector &CheckedVarArgs,
8480                     UncoveredArgHandler &UncoveredArg)
8481       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8482                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8483                            inFunctionCall, CallType, CheckedVarArgs,
8484                            UncoveredArg) {}
8485 
8486   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8487                             const char *startSpecifier,
8488                             unsigned specifierLen) override;
8489 
8490   bool HandleInvalidScanfConversionSpecifier(
8491           const analyze_scanf::ScanfSpecifier &FS,
8492           const char *startSpecifier,
8493           unsigned specifierLen) override;
8494 
8495   void HandleIncompleteScanList(const char *start, const char *end) override;
8496 };
8497 
8498 } // namespace
8499 
8500 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8501                                                  const char *end) {
8502   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8503                        getLocationOfByte(end), /*IsStringLocation*/true,
8504                        getSpecifierRange(start, end - start));
8505 }
8506 
8507 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8508                                         const analyze_scanf::ScanfSpecifier &FS,
8509                                         const char *startSpecifier,
8510                                         unsigned specifierLen) {
8511   const analyze_scanf::ScanfConversionSpecifier &CS =
8512     FS.getConversionSpecifier();
8513 
8514   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8515                                           getLocationOfByte(CS.getStart()),
8516                                           startSpecifier, specifierLen,
8517                                           CS.getStart(), CS.getLength());
8518 }
8519 
8520 bool CheckScanfHandler::HandleScanfSpecifier(
8521                                        const analyze_scanf::ScanfSpecifier &FS,
8522                                        const char *startSpecifier,
8523                                        unsigned specifierLen) {
8524   using namespace analyze_scanf;
8525   using namespace analyze_format_string;
8526 
8527   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8528 
8529   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8530   // be used to decide if we are using positional arguments consistently.
8531   if (FS.consumesDataArgument()) {
8532     if (atFirstArg) {
8533       atFirstArg = false;
8534       usesPositionalArgs = FS.usesPositionalArg();
8535     }
8536     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8537       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8538                                         startSpecifier, specifierLen);
8539       return false;
8540     }
8541   }
8542 
8543   // Check if the field with is non-zero.
8544   const OptionalAmount &Amt = FS.getFieldWidth();
8545   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8546     if (Amt.getConstantAmount() == 0) {
8547       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8548                                                    Amt.getConstantLength());
8549       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8550                            getLocationOfByte(Amt.getStart()),
8551                            /*IsStringLocation*/true, R,
8552                            FixItHint::CreateRemoval(R));
8553     }
8554   }
8555 
8556   if (!FS.consumesDataArgument()) {
8557     // FIXME: Technically specifying a precision or field width here
8558     // makes no sense.  Worth issuing a warning at some point.
8559     return true;
8560   }
8561 
8562   // Consume the argument.
8563   unsigned argIndex = FS.getArgIndex();
8564   if (argIndex < NumDataArgs) {
8565       // The check to see if the argIndex is valid will come later.
8566       // We set the bit here because we may exit early from this
8567       // function if we encounter some other error.
8568     CoveredArgs.set(argIndex);
8569   }
8570 
8571   // Check the length modifier is valid with the given conversion specifier.
8572   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8573                                  S.getLangOpts()))
8574     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8575                                 diag::warn_format_nonsensical_length);
8576   else if (!FS.hasStandardLengthModifier())
8577     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8578   else if (!FS.hasStandardLengthConversionCombination())
8579     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8580                                 diag::warn_format_non_standard_conversion_spec);
8581 
8582   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8583     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8584 
8585   // The remaining checks depend on the data arguments.
8586   if (HasVAListArg)
8587     return true;
8588 
8589   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8590     return false;
8591 
8592   // Check that the argument type matches the format specifier.
8593   const Expr *Ex = getDataArg(argIndex);
8594   if (!Ex)
8595     return true;
8596 
8597   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8598 
8599   if (!AT.isValid()) {
8600     return true;
8601   }
8602 
8603   analyze_format_string::ArgType::MatchKind Match =
8604       AT.matchesType(S.Context, Ex->getType());
8605   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8606   if (Match == analyze_format_string::ArgType::Match)
8607     return true;
8608 
8609   ScanfSpecifier fixedFS = FS;
8610   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8611                                  S.getLangOpts(), S.Context);
8612 
8613   unsigned Diag =
8614       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8615                : diag::warn_format_conversion_argument_type_mismatch;
8616 
8617   if (Success) {
8618     // Get the fix string from the fixed format specifier.
8619     SmallString<128> buf;
8620     llvm::raw_svector_ostream os(buf);
8621     fixedFS.toString(os);
8622 
8623     EmitFormatDiagnostic(
8624         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8625                       << Ex->getType() << false << Ex->getSourceRange(),
8626         Ex->getBeginLoc(),
8627         /*IsStringLocation*/ false,
8628         getSpecifierRange(startSpecifier, specifierLen),
8629         FixItHint::CreateReplacement(
8630             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8631   } else {
8632     EmitFormatDiagnostic(S.PDiag(Diag)
8633                              << AT.getRepresentativeTypeName(S.Context)
8634                              << Ex->getType() << false << Ex->getSourceRange(),
8635                          Ex->getBeginLoc(),
8636                          /*IsStringLocation*/ false,
8637                          getSpecifierRange(startSpecifier, specifierLen));
8638   }
8639 
8640   return true;
8641 }
8642 
8643 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8644                               const Expr *OrigFormatExpr,
8645                               ArrayRef<const Expr *> Args,
8646                               bool HasVAListArg, unsigned format_idx,
8647                               unsigned firstDataArg,
8648                               Sema::FormatStringType Type,
8649                               bool inFunctionCall,
8650                               Sema::VariadicCallType CallType,
8651                               llvm::SmallBitVector &CheckedVarArgs,
8652                               UncoveredArgHandler &UncoveredArg,
8653                               bool IgnoreStringsWithoutSpecifiers) {
8654   // CHECK: is the format string a wide literal?
8655   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8656     CheckFormatHandler::EmitFormatDiagnostic(
8657         S, inFunctionCall, Args[format_idx],
8658         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8659         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8660     return;
8661   }
8662 
8663   // Str - The format string.  NOTE: this is NOT null-terminated!
8664   StringRef StrRef = FExpr->getString();
8665   const char *Str = StrRef.data();
8666   // Account for cases where the string literal is truncated in a declaration.
8667   const ConstantArrayType *T =
8668     S.Context.getAsConstantArrayType(FExpr->getType());
8669   assert(T && "String literal not of constant array type!");
8670   size_t TypeSize = T->getSize().getZExtValue();
8671   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8672   const unsigned numDataArgs = Args.size() - firstDataArg;
8673 
8674   if (IgnoreStringsWithoutSpecifiers &&
8675       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8676           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8677     return;
8678 
8679   // Emit a warning if the string literal is truncated and does not contain an
8680   // embedded null character.
8681   if (TypeSize <= StrRef.size() &&
8682       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8683     CheckFormatHandler::EmitFormatDiagnostic(
8684         S, inFunctionCall, Args[format_idx],
8685         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8686         FExpr->getBeginLoc(),
8687         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8688     return;
8689   }
8690 
8691   // CHECK: empty format string?
8692   if (StrLen == 0 && numDataArgs > 0) {
8693     CheckFormatHandler::EmitFormatDiagnostic(
8694         S, inFunctionCall, Args[format_idx],
8695         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8696         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8697     return;
8698   }
8699 
8700   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8701       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8702       Type == Sema::FST_OSTrace) {
8703     CheckPrintfHandler H(
8704         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8705         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8706         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8707         CheckedVarArgs, UncoveredArg);
8708 
8709     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8710                                                   S.getLangOpts(),
8711                                                   S.Context.getTargetInfo(),
8712                                             Type == Sema::FST_FreeBSDKPrintf))
8713       H.DoneProcessing();
8714   } else if (Type == Sema::FST_Scanf) {
8715     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8716                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8717                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8718 
8719     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8720                                                  S.getLangOpts(),
8721                                                  S.Context.getTargetInfo()))
8722       H.DoneProcessing();
8723   } // TODO: handle other formats
8724 }
8725 
8726 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8727   // Str - The format string.  NOTE: this is NOT null-terminated!
8728   StringRef StrRef = FExpr->getString();
8729   const char *Str = StrRef.data();
8730   // Account for cases where the string literal is truncated in a declaration.
8731   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8732   assert(T && "String literal not of constant array type!");
8733   size_t TypeSize = T->getSize().getZExtValue();
8734   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8735   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8736                                                          getLangOpts(),
8737                                                          Context.getTargetInfo());
8738 }
8739 
8740 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8741 
8742 // Returns the related absolute value function that is larger, of 0 if one
8743 // does not exist.
8744 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8745   switch (AbsFunction) {
8746   default:
8747     return 0;
8748 
8749   case Builtin::BI__builtin_abs:
8750     return Builtin::BI__builtin_labs;
8751   case Builtin::BI__builtin_labs:
8752     return Builtin::BI__builtin_llabs;
8753   case Builtin::BI__builtin_llabs:
8754     return 0;
8755 
8756   case Builtin::BI__builtin_fabsf:
8757     return Builtin::BI__builtin_fabs;
8758   case Builtin::BI__builtin_fabs:
8759     return Builtin::BI__builtin_fabsl;
8760   case Builtin::BI__builtin_fabsl:
8761     return 0;
8762 
8763   case Builtin::BI__builtin_cabsf:
8764     return Builtin::BI__builtin_cabs;
8765   case Builtin::BI__builtin_cabs:
8766     return Builtin::BI__builtin_cabsl;
8767   case Builtin::BI__builtin_cabsl:
8768     return 0;
8769 
8770   case Builtin::BIabs:
8771     return Builtin::BIlabs;
8772   case Builtin::BIlabs:
8773     return Builtin::BIllabs;
8774   case Builtin::BIllabs:
8775     return 0;
8776 
8777   case Builtin::BIfabsf:
8778     return Builtin::BIfabs;
8779   case Builtin::BIfabs:
8780     return Builtin::BIfabsl;
8781   case Builtin::BIfabsl:
8782     return 0;
8783 
8784   case Builtin::BIcabsf:
8785    return Builtin::BIcabs;
8786   case Builtin::BIcabs:
8787     return Builtin::BIcabsl;
8788   case Builtin::BIcabsl:
8789     return 0;
8790   }
8791 }
8792 
8793 // Returns the argument type of the absolute value function.
8794 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8795                                              unsigned AbsType) {
8796   if (AbsType == 0)
8797     return QualType();
8798 
8799   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8800   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8801   if (Error != ASTContext::GE_None)
8802     return QualType();
8803 
8804   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8805   if (!FT)
8806     return QualType();
8807 
8808   if (FT->getNumParams() != 1)
8809     return QualType();
8810 
8811   return FT->getParamType(0);
8812 }
8813 
8814 // Returns the best absolute value function, or zero, based on type and
8815 // current absolute value function.
8816 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8817                                    unsigned AbsFunctionKind) {
8818   unsigned BestKind = 0;
8819   uint64_t ArgSize = Context.getTypeSize(ArgType);
8820   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8821        Kind = getLargerAbsoluteValueFunction(Kind)) {
8822     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8823     if (Context.getTypeSize(ParamType) >= ArgSize) {
8824       if (BestKind == 0)
8825         BestKind = Kind;
8826       else if (Context.hasSameType(ParamType, ArgType)) {
8827         BestKind = Kind;
8828         break;
8829       }
8830     }
8831   }
8832   return BestKind;
8833 }
8834 
8835 enum AbsoluteValueKind {
8836   AVK_Integer,
8837   AVK_Floating,
8838   AVK_Complex
8839 };
8840 
8841 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8842   if (T->isIntegralOrEnumerationType())
8843     return AVK_Integer;
8844   if (T->isRealFloatingType())
8845     return AVK_Floating;
8846   if (T->isAnyComplexType())
8847     return AVK_Complex;
8848 
8849   llvm_unreachable("Type not integer, floating, or complex");
8850 }
8851 
8852 // Changes the absolute value function to a different type.  Preserves whether
8853 // the function is a builtin.
8854 static unsigned changeAbsFunction(unsigned AbsKind,
8855                                   AbsoluteValueKind ValueKind) {
8856   switch (ValueKind) {
8857   case AVK_Integer:
8858     switch (AbsKind) {
8859     default:
8860       return 0;
8861     case Builtin::BI__builtin_fabsf:
8862     case Builtin::BI__builtin_fabs:
8863     case Builtin::BI__builtin_fabsl:
8864     case Builtin::BI__builtin_cabsf:
8865     case Builtin::BI__builtin_cabs:
8866     case Builtin::BI__builtin_cabsl:
8867       return Builtin::BI__builtin_abs;
8868     case Builtin::BIfabsf:
8869     case Builtin::BIfabs:
8870     case Builtin::BIfabsl:
8871     case Builtin::BIcabsf:
8872     case Builtin::BIcabs:
8873     case Builtin::BIcabsl:
8874       return Builtin::BIabs;
8875     }
8876   case AVK_Floating:
8877     switch (AbsKind) {
8878     default:
8879       return 0;
8880     case Builtin::BI__builtin_abs:
8881     case Builtin::BI__builtin_labs:
8882     case Builtin::BI__builtin_llabs:
8883     case Builtin::BI__builtin_cabsf:
8884     case Builtin::BI__builtin_cabs:
8885     case Builtin::BI__builtin_cabsl:
8886       return Builtin::BI__builtin_fabsf;
8887     case Builtin::BIabs:
8888     case Builtin::BIlabs:
8889     case Builtin::BIllabs:
8890     case Builtin::BIcabsf:
8891     case Builtin::BIcabs:
8892     case Builtin::BIcabsl:
8893       return Builtin::BIfabsf;
8894     }
8895   case AVK_Complex:
8896     switch (AbsKind) {
8897     default:
8898       return 0;
8899     case Builtin::BI__builtin_abs:
8900     case Builtin::BI__builtin_labs:
8901     case Builtin::BI__builtin_llabs:
8902     case Builtin::BI__builtin_fabsf:
8903     case Builtin::BI__builtin_fabs:
8904     case Builtin::BI__builtin_fabsl:
8905       return Builtin::BI__builtin_cabsf;
8906     case Builtin::BIabs:
8907     case Builtin::BIlabs:
8908     case Builtin::BIllabs:
8909     case Builtin::BIfabsf:
8910     case Builtin::BIfabs:
8911     case Builtin::BIfabsl:
8912       return Builtin::BIcabsf;
8913     }
8914   }
8915   llvm_unreachable("Unable to convert function");
8916 }
8917 
8918 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8919   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8920   if (!FnInfo)
8921     return 0;
8922 
8923   switch (FDecl->getBuiltinID()) {
8924   default:
8925     return 0;
8926   case Builtin::BI__builtin_abs:
8927   case Builtin::BI__builtin_fabs:
8928   case Builtin::BI__builtin_fabsf:
8929   case Builtin::BI__builtin_fabsl:
8930   case Builtin::BI__builtin_labs:
8931   case Builtin::BI__builtin_llabs:
8932   case Builtin::BI__builtin_cabs:
8933   case Builtin::BI__builtin_cabsf:
8934   case Builtin::BI__builtin_cabsl:
8935   case Builtin::BIabs:
8936   case Builtin::BIlabs:
8937   case Builtin::BIllabs:
8938   case Builtin::BIfabs:
8939   case Builtin::BIfabsf:
8940   case Builtin::BIfabsl:
8941   case Builtin::BIcabs:
8942   case Builtin::BIcabsf:
8943   case Builtin::BIcabsl:
8944     return FDecl->getBuiltinID();
8945   }
8946   llvm_unreachable("Unknown Builtin type");
8947 }
8948 
8949 // If the replacement is valid, emit a note with replacement function.
8950 // Additionally, suggest including the proper header if not already included.
8951 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8952                             unsigned AbsKind, QualType ArgType) {
8953   bool EmitHeaderHint = true;
8954   const char *HeaderName = nullptr;
8955   const char *FunctionName = nullptr;
8956   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8957     FunctionName = "std::abs";
8958     if (ArgType->isIntegralOrEnumerationType()) {
8959       HeaderName = "cstdlib";
8960     } else if (ArgType->isRealFloatingType()) {
8961       HeaderName = "cmath";
8962     } else {
8963       llvm_unreachable("Invalid Type");
8964     }
8965 
8966     // Lookup all std::abs
8967     if (NamespaceDecl *Std = S.getStdNamespace()) {
8968       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8969       R.suppressDiagnostics();
8970       S.LookupQualifiedName(R, Std);
8971 
8972       for (const auto *I : R) {
8973         const FunctionDecl *FDecl = nullptr;
8974         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8975           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8976         } else {
8977           FDecl = dyn_cast<FunctionDecl>(I);
8978         }
8979         if (!FDecl)
8980           continue;
8981 
8982         // Found std::abs(), check that they are the right ones.
8983         if (FDecl->getNumParams() != 1)
8984           continue;
8985 
8986         // Check that the parameter type can handle the argument.
8987         QualType ParamType = FDecl->getParamDecl(0)->getType();
8988         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8989             S.Context.getTypeSize(ArgType) <=
8990                 S.Context.getTypeSize(ParamType)) {
8991           // Found a function, don't need the header hint.
8992           EmitHeaderHint = false;
8993           break;
8994         }
8995       }
8996     }
8997   } else {
8998     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8999     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9000 
9001     if (HeaderName) {
9002       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9003       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9004       R.suppressDiagnostics();
9005       S.LookupName(R, S.getCurScope());
9006 
9007       if (R.isSingleResult()) {
9008         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9009         if (FD && FD->getBuiltinID() == AbsKind) {
9010           EmitHeaderHint = false;
9011         } else {
9012           return;
9013         }
9014       } else if (!R.empty()) {
9015         return;
9016       }
9017     }
9018   }
9019 
9020   S.Diag(Loc, diag::note_replace_abs_function)
9021       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9022 
9023   if (!HeaderName)
9024     return;
9025 
9026   if (!EmitHeaderHint)
9027     return;
9028 
9029   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9030                                                     << FunctionName;
9031 }
9032 
9033 template <std::size_t StrLen>
9034 static bool IsStdFunction(const FunctionDecl *FDecl,
9035                           const char (&Str)[StrLen]) {
9036   if (!FDecl)
9037     return false;
9038   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9039     return false;
9040   if (!FDecl->isInStdNamespace())
9041     return false;
9042 
9043   return true;
9044 }
9045 
9046 // Warn when using the wrong abs() function.
9047 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9048                                       const FunctionDecl *FDecl) {
9049   if (Call->getNumArgs() != 1)
9050     return;
9051 
9052   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9053   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9054   if (AbsKind == 0 && !IsStdAbs)
9055     return;
9056 
9057   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9058   QualType ParamType = Call->getArg(0)->getType();
9059 
9060   // Unsigned types cannot be negative.  Suggest removing the absolute value
9061   // function call.
9062   if (ArgType->isUnsignedIntegerType()) {
9063     const char *FunctionName =
9064         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9065     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9066     Diag(Call->getExprLoc(), diag::note_remove_abs)
9067         << FunctionName
9068         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9069     return;
9070   }
9071 
9072   // Taking the absolute value of a pointer is very suspicious, they probably
9073   // wanted to index into an array, dereference a pointer, call a function, etc.
9074   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9075     unsigned DiagType = 0;
9076     if (ArgType->isFunctionType())
9077       DiagType = 1;
9078     else if (ArgType->isArrayType())
9079       DiagType = 2;
9080 
9081     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9082     return;
9083   }
9084 
9085   // std::abs has overloads which prevent most of the absolute value problems
9086   // from occurring.
9087   if (IsStdAbs)
9088     return;
9089 
9090   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9091   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9092 
9093   // The argument and parameter are the same kind.  Check if they are the right
9094   // size.
9095   if (ArgValueKind == ParamValueKind) {
9096     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9097       return;
9098 
9099     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9100     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9101         << FDecl << ArgType << ParamType;
9102 
9103     if (NewAbsKind == 0)
9104       return;
9105 
9106     emitReplacement(*this, Call->getExprLoc(),
9107                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9108     return;
9109   }
9110 
9111   // ArgValueKind != ParamValueKind
9112   // The wrong type of absolute value function was used.  Attempt to find the
9113   // proper one.
9114   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9115   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9116   if (NewAbsKind == 0)
9117     return;
9118 
9119   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9120       << FDecl << ParamValueKind << ArgValueKind;
9121 
9122   emitReplacement(*this, Call->getExprLoc(),
9123                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9124 }
9125 
9126 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9127 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9128                                 const FunctionDecl *FDecl) {
9129   if (!Call || !FDecl) return;
9130 
9131   // Ignore template specializations and macros.
9132   if (inTemplateInstantiation()) return;
9133   if (Call->getExprLoc().isMacroID()) return;
9134 
9135   // Only care about the one template argument, two function parameter std::max
9136   if (Call->getNumArgs() != 2) return;
9137   if (!IsStdFunction(FDecl, "max")) return;
9138   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9139   if (!ArgList) return;
9140   if (ArgList->size() != 1) return;
9141 
9142   // Check that template type argument is unsigned integer.
9143   const auto& TA = ArgList->get(0);
9144   if (TA.getKind() != TemplateArgument::Type) return;
9145   QualType ArgType = TA.getAsType();
9146   if (!ArgType->isUnsignedIntegerType()) return;
9147 
9148   // See if either argument is a literal zero.
9149   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9150     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9151     if (!MTE) return false;
9152     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9153     if (!Num) return false;
9154     if (Num->getValue() != 0) return false;
9155     return true;
9156   };
9157 
9158   const Expr *FirstArg = Call->getArg(0);
9159   const Expr *SecondArg = Call->getArg(1);
9160   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9161   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9162 
9163   // Only warn when exactly one argument is zero.
9164   if (IsFirstArgZero == IsSecondArgZero) return;
9165 
9166   SourceRange FirstRange = FirstArg->getSourceRange();
9167   SourceRange SecondRange = SecondArg->getSourceRange();
9168 
9169   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9170 
9171   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9172       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9173 
9174   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9175   SourceRange RemovalRange;
9176   if (IsFirstArgZero) {
9177     RemovalRange = SourceRange(FirstRange.getBegin(),
9178                                SecondRange.getBegin().getLocWithOffset(-1));
9179   } else {
9180     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9181                                SecondRange.getEnd());
9182   }
9183 
9184   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9185         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9186         << FixItHint::CreateRemoval(RemovalRange);
9187 }
9188 
9189 //===--- CHECK: Standard memory functions ---------------------------------===//
9190 
9191 /// Takes the expression passed to the size_t parameter of functions
9192 /// such as memcmp, strncat, etc and warns if it's a comparison.
9193 ///
9194 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9195 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9196                                            IdentifierInfo *FnName,
9197                                            SourceLocation FnLoc,
9198                                            SourceLocation RParenLoc) {
9199   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9200   if (!Size)
9201     return false;
9202 
9203   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9204   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9205     return false;
9206 
9207   SourceRange SizeRange = Size->getSourceRange();
9208   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9209       << SizeRange << FnName;
9210   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9211       << FnName
9212       << FixItHint::CreateInsertion(
9213              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9214       << FixItHint::CreateRemoval(RParenLoc);
9215   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9216       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9217       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9218                                     ")");
9219 
9220   return true;
9221 }
9222 
9223 /// Determine whether the given type is or contains a dynamic class type
9224 /// (e.g., whether it has a vtable).
9225 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9226                                                      bool &IsContained) {
9227   // Look through array types while ignoring qualifiers.
9228   const Type *Ty = T->getBaseElementTypeUnsafe();
9229   IsContained = false;
9230 
9231   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9232   RD = RD ? RD->getDefinition() : nullptr;
9233   if (!RD || RD->isInvalidDecl())
9234     return nullptr;
9235 
9236   if (RD->isDynamicClass())
9237     return RD;
9238 
9239   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9240   // It's impossible for a class to transitively contain itself by value, so
9241   // infinite recursion is impossible.
9242   for (auto *FD : RD->fields()) {
9243     bool SubContained;
9244     if (const CXXRecordDecl *ContainedRD =
9245             getContainedDynamicClass(FD->getType(), SubContained)) {
9246       IsContained = true;
9247       return ContainedRD;
9248     }
9249   }
9250 
9251   return nullptr;
9252 }
9253 
9254 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9255   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9256     if (Unary->getKind() == UETT_SizeOf)
9257       return Unary;
9258   return nullptr;
9259 }
9260 
9261 /// If E is a sizeof expression, returns its argument expression,
9262 /// otherwise returns NULL.
9263 static const Expr *getSizeOfExprArg(const Expr *E) {
9264   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9265     if (!SizeOf->isArgumentType())
9266       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9267   return nullptr;
9268 }
9269 
9270 /// If E is a sizeof expression, returns its argument type.
9271 static QualType getSizeOfArgType(const Expr *E) {
9272   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9273     return SizeOf->getTypeOfArgument();
9274   return QualType();
9275 }
9276 
9277 namespace {
9278 
9279 struct SearchNonTrivialToInitializeField
9280     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9281   using Super =
9282       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9283 
9284   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9285 
9286   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9287                      SourceLocation SL) {
9288     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9289       asDerived().visitArray(PDIK, AT, SL);
9290       return;
9291     }
9292 
9293     Super::visitWithKind(PDIK, FT, SL);
9294   }
9295 
9296   void visitARCStrong(QualType FT, SourceLocation SL) {
9297     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9298   }
9299   void visitARCWeak(QualType FT, SourceLocation SL) {
9300     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9301   }
9302   void visitStruct(QualType FT, SourceLocation SL) {
9303     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9304       visit(FD->getType(), FD->getLocation());
9305   }
9306   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9307                   const ArrayType *AT, SourceLocation SL) {
9308     visit(getContext().getBaseElementType(AT), SL);
9309   }
9310   void visitTrivial(QualType FT, SourceLocation SL) {}
9311 
9312   static void diag(QualType RT, const Expr *E, Sema &S) {
9313     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9314   }
9315 
9316   ASTContext &getContext() { return S.getASTContext(); }
9317 
9318   const Expr *E;
9319   Sema &S;
9320 };
9321 
9322 struct SearchNonTrivialToCopyField
9323     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9324   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9325 
9326   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9327 
9328   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9329                      SourceLocation SL) {
9330     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9331       asDerived().visitArray(PCK, AT, SL);
9332       return;
9333     }
9334 
9335     Super::visitWithKind(PCK, FT, SL);
9336   }
9337 
9338   void visitARCStrong(QualType FT, SourceLocation SL) {
9339     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9340   }
9341   void visitARCWeak(QualType FT, SourceLocation SL) {
9342     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9343   }
9344   void visitStruct(QualType FT, SourceLocation SL) {
9345     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9346       visit(FD->getType(), FD->getLocation());
9347   }
9348   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9349                   SourceLocation SL) {
9350     visit(getContext().getBaseElementType(AT), SL);
9351   }
9352   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9353                 SourceLocation SL) {}
9354   void visitTrivial(QualType FT, SourceLocation SL) {}
9355   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9356 
9357   static void diag(QualType RT, const Expr *E, Sema &S) {
9358     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9359   }
9360 
9361   ASTContext &getContext() { return S.getASTContext(); }
9362 
9363   const Expr *E;
9364   Sema &S;
9365 };
9366 
9367 }
9368 
9369 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9370 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9371   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9372 
9373   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9374     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9375       return false;
9376 
9377     return doesExprLikelyComputeSize(BO->getLHS()) ||
9378            doesExprLikelyComputeSize(BO->getRHS());
9379   }
9380 
9381   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9382 }
9383 
9384 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9385 ///
9386 /// \code
9387 ///   #define MACRO 0
9388 ///   foo(MACRO);
9389 ///   foo(0);
9390 /// \endcode
9391 ///
9392 /// This should return true for the first call to foo, but not for the second
9393 /// (regardless of whether foo is a macro or function).
9394 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9395                                         SourceLocation CallLoc,
9396                                         SourceLocation ArgLoc) {
9397   if (!CallLoc.isMacroID())
9398     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9399 
9400   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9401          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9402 }
9403 
9404 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9405 /// last two arguments transposed.
9406 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9407   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9408     return;
9409 
9410   const Expr *SizeArg =
9411     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9412 
9413   auto isLiteralZero = [](const Expr *E) {
9414     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9415   };
9416 
9417   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9418   SourceLocation CallLoc = Call->getRParenLoc();
9419   SourceManager &SM = S.getSourceManager();
9420   if (isLiteralZero(SizeArg) &&
9421       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9422 
9423     SourceLocation DiagLoc = SizeArg->getExprLoc();
9424 
9425     // Some platforms #define bzero to __builtin_memset. See if this is the
9426     // case, and if so, emit a better diagnostic.
9427     if (BId == Builtin::BIbzero ||
9428         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9429                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9430       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9431       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9432     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9433       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9434       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9435     }
9436     return;
9437   }
9438 
9439   // If the second argument to a memset is a sizeof expression and the third
9440   // isn't, this is also likely an error. This should catch
9441   // 'memset(buf, sizeof(buf), 0xff)'.
9442   if (BId == Builtin::BImemset &&
9443       doesExprLikelyComputeSize(Call->getArg(1)) &&
9444       !doesExprLikelyComputeSize(Call->getArg(2))) {
9445     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9446     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9447     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9448     return;
9449   }
9450 }
9451 
9452 /// Check for dangerous or invalid arguments to memset().
9453 ///
9454 /// This issues warnings on known problematic, dangerous or unspecified
9455 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9456 /// function calls.
9457 ///
9458 /// \param Call The call expression to diagnose.
9459 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9460                                    unsigned BId,
9461                                    IdentifierInfo *FnName) {
9462   assert(BId != 0);
9463 
9464   // It is possible to have a non-standard definition of memset.  Validate
9465   // we have enough arguments, and if not, abort further checking.
9466   unsigned ExpectedNumArgs =
9467       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9468   if (Call->getNumArgs() < ExpectedNumArgs)
9469     return;
9470 
9471   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9472                       BId == Builtin::BIstrndup ? 1 : 2);
9473   unsigned LenArg =
9474       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9475   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9476 
9477   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9478                                      Call->getBeginLoc(), Call->getRParenLoc()))
9479     return;
9480 
9481   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9482   CheckMemaccessSize(*this, BId, Call);
9483 
9484   // We have special checking when the length is a sizeof expression.
9485   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9486   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9487   llvm::FoldingSetNodeID SizeOfArgID;
9488 
9489   // Although widely used, 'bzero' is not a standard function. Be more strict
9490   // with the argument types before allowing diagnostics and only allow the
9491   // form bzero(ptr, sizeof(...)).
9492   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9493   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9494     return;
9495 
9496   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9497     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9498     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9499 
9500     QualType DestTy = Dest->getType();
9501     QualType PointeeTy;
9502     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9503       PointeeTy = DestPtrTy->getPointeeType();
9504 
9505       // Never warn about void type pointers. This can be used to suppress
9506       // false positives.
9507       if (PointeeTy->isVoidType())
9508         continue;
9509 
9510       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9511       // actually comparing the expressions for equality. Because computing the
9512       // expression IDs can be expensive, we only do this if the diagnostic is
9513       // enabled.
9514       if (SizeOfArg &&
9515           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9516                            SizeOfArg->getExprLoc())) {
9517         // We only compute IDs for expressions if the warning is enabled, and
9518         // cache the sizeof arg's ID.
9519         if (SizeOfArgID == llvm::FoldingSetNodeID())
9520           SizeOfArg->Profile(SizeOfArgID, Context, true);
9521         llvm::FoldingSetNodeID DestID;
9522         Dest->Profile(DestID, Context, true);
9523         if (DestID == SizeOfArgID) {
9524           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9525           //       over sizeof(src) as well.
9526           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9527           StringRef ReadableName = FnName->getName();
9528 
9529           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9530             if (UnaryOp->getOpcode() == UO_AddrOf)
9531               ActionIdx = 1; // If its an address-of operator, just remove it.
9532           if (!PointeeTy->isIncompleteType() &&
9533               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9534             ActionIdx = 2; // If the pointee's size is sizeof(char),
9535                            // suggest an explicit length.
9536 
9537           // If the function is defined as a builtin macro, do not show macro
9538           // expansion.
9539           SourceLocation SL = SizeOfArg->getExprLoc();
9540           SourceRange DSR = Dest->getSourceRange();
9541           SourceRange SSR = SizeOfArg->getSourceRange();
9542           SourceManager &SM = getSourceManager();
9543 
9544           if (SM.isMacroArgExpansion(SL)) {
9545             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9546             SL = SM.getSpellingLoc(SL);
9547             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9548                              SM.getSpellingLoc(DSR.getEnd()));
9549             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9550                              SM.getSpellingLoc(SSR.getEnd()));
9551           }
9552 
9553           DiagRuntimeBehavior(SL, SizeOfArg,
9554                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9555                                 << ReadableName
9556                                 << PointeeTy
9557                                 << DestTy
9558                                 << DSR
9559                                 << SSR);
9560           DiagRuntimeBehavior(SL, SizeOfArg,
9561                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9562                                 << ActionIdx
9563                                 << SSR);
9564 
9565           break;
9566         }
9567       }
9568 
9569       // Also check for cases where the sizeof argument is the exact same
9570       // type as the memory argument, and where it points to a user-defined
9571       // record type.
9572       if (SizeOfArgTy != QualType()) {
9573         if (PointeeTy->isRecordType() &&
9574             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9575           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9576                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9577                                 << FnName << SizeOfArgTy << ArgIdx
9578                                 << PointeeTy << Dest->getSourceRange()
9579                                 << LenExpr->getSourceRange());
9580           break;
9581         }
9582       }
9583     } else if (DestTy->isArrayType()) {
9584       PointeeTy = DestTy;
9585     }
9586 
9587     if (PointeeTy == QualType())
9588       continue;
9589 
9590     // Always complain about dynamic classes.
9591     bool IsContained;
9592     if (const CXXRecordDecl *ContainedRD =
9593             getContainedDynamicClass(PointeeTy, IsContained)) {
9594 
9595       unsigned OperationType = 0;
9596       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9597       // "overwritten" if we're warning about the destination for any call
9598       // but memcmp; otherwise a verb appropriate to the call.
9599       if (ArgIdx != 0 || IsCmp) {
9600         if (BId == Builtin::BImemcpy)
9601           OperationType = 1;
9602         else if(BId == Builtin::BImemmove)
9603           OperationType = 2;
9604         else if (IsCmp)
9605           OperationType = 3;
9606       }
9607 
9608       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9609                           PDiag(diag::warn_dyn_class_memaccess)
9610                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9611                               << IsContained << ContainedRD << OperationType
9612                               << Call->getCallee()->getSourceRange());
9613     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9614              BId != Builtin::BImemset)
9615       DiagRuntimeBehavior(
9616         Dest->getExprLoc(), Dest,
9617         PDiag(diag::warn_arc_object_memaccess)
9618           << ArgIdx << FnName << PointeeTy
9619           << Call->getCallee()->getSourceRange());
9620     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9621       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9622           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9623         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9624                             PDiag(diag::warn_cstruct_memaccess)
9625                                 << ArgIdx << FnName << PointeeTy << 0);
9626         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9627       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9628                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9629         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9630                             PDiag(diag::warn_cstruct_memaccess)
9631                                 << ArgIdx << FnName << PointeeTy << 1);
9632         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9633       } else {
9634         continue;
9635       }
9636     } else
9637       continue;
9638 
9639     DiagRuntimeBehavior(
9640       Dest->getExprLoc(), Dest,
9641       PDiag(diag::note_bad_memaccess_silence)
9642         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9643     break;
9644   }
9645 }
9646 
9647 // A little helper routine: ignore addition and subtraction of integer literals.
9648 // This intentionally does not ignore all integer constant expressions because
9649 // we don't want to remove sizeof().
9650 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9651   Ex = Ex->IgnoreParenCasts();
9652 
9653   while (true) {
9654     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9655     if (!BO || !BO->isAdditiveOp())
9656       break;
9657 
9658     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9659     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9660 
9661     if (isa<IntegerLiteral>(RHS))
9662       Ex = LHS;
9663     else if (isa<IntegerLiteral>(LHS))
9664       Ex = RHS;
9665     else
9666       break;
9667   }
9668 
9669   return Ex;
9670 }
9671 
9672 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9673                                                       ASTContext &Context) {
9674   // Only handle constant-sized or VLAs, but not flexible members.
9675   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9676     // Only issue the FIXIT for arrays of size > 1.
9677     if (CAT->getSize().getSExtValue() <= 1)
9678       return false;
9679   } else if (!Ty->isVariableArrayType()) {
9680     return false;
9681   }
9682   return true;
9683 }
9684 
9685 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9686 // be the size of the source, instead of the destination.
9687 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9688                                     IdentifierInfo *FnName) {
9689 
9690   // Don't crash if the user has the wrong number of arguments
9691   unsigned NumArgs = Call->getNumArgs();
9692   if ((NumArgs != 3) && (NumArgs != 4))
9693     return;
9694 
9695   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9696   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9697   const Expr *CompareWithSrc = nullptr;
9698 
9699   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9700                                      Call->getBeginLoc(), Call->getRParenLoc()))
9701     return;
9702 
9703   // Look for 'strlcpy(dst, x, sizeof(x))'
9704   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9705     CompareWithSrc = Ex;
9706   else {
9707     // Look for 'strlcpy(dst, x, strlen(x))'
9708     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9709       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9710           SizeCall->getNumArgs() == 1)
9711         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9712     }
9713   }
9714 
9715   if (!CompareWithSrc)
9716     return;
9717 
9718   // Determine if the argument to sizeof/strlen is equal to the source
9719   // argument.  In principle there's all kinds of things you could do
9720   // here, for instance creating an == expression and evaluating it with
9721   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9722   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9723   if (!SrcArgDRE)
9724     return;
9725 
9726   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9727   if (!CompareWithSrcDRE ||
9728       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9729     return;
9730 
9731   const Expr *OriginalSizeArg = Call->getArg(2);
9732   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9733       << OriginalSizeArg->getSourceRange() << FnName;
9734 
9735   // Output a FIXIT hint if the destination is an array (rather than a
9736   // pointer to an array).  This could be enhanced to handle some
9737   // pointers if we know the actual size, like if DstArg is 'array+2'
9738   // we could say 'sizeof(array)-2'.
9739   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9740   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9741     return;
9742 
9743   SmallString<128> sizeString;
9744   llvm::raw_svector_ostream OS(sizeString);
9745   OS << "sizeof(";
9746   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9747   OS << ")";
9748 
9749   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9750       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9751                                       OS.str());
9752 }
9753 
9754 /// Check if two expressions refer to the same declaration.
9755 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9756   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9757     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9758       return D1->getDecl() == D2->getDecl();
9759   return false;
9760 }
9761 
9762 static const Expr *getStrlenExprArg(const Expr *E) {
9763   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9764     const FunctionDecl *FD = CE->getDirectCallee();
9765     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9766       return nullptr;
9767     return CE->getArg(0)->IgnoreParenCasts();
9768   }
9769   return nullptr;
9770 }
9771 
9772 // Warn on anti-patterns as the 'size' argument to strncat.
9773 // The correct size argument should look like following:
9774 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9775 void Sema::CheckStrncatArguments(const CallExpr *CE,
9776                                  IdentifierInfo *FnName) {
9777   // Don't crash if the user has the wrong number of arguments.
9778   if (CE->getNumArgs() < 3)
9779     return;
9780   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9781   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9782   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9783 
9784   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9785                                      CE->getRParenLoc()))
9786     return;
9787 
9788   // Identify common expressions, which are wrongly used as the size argument
9789   // to strncat and may lead to buffer overflows.
9790   unsigned PatternType = 0;
9791   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9792     // - sizeof(dst)
9793     if (referToTheSameDecl(SizeOfArg, DstArg))
9794       PatternType = 1;
9795     // - sizeof(src)
9796     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9797       PatternType = 2;
9798   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9799     if (BE->getOpcode() == BO_Sub) {
9800       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9801       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9802       // - sizeof(dst) - strlen(dst)
9803       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9804           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9805         PatternType = 1;
9806       // - sizeof(src) - (anything)
9807       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9808         PatternType = 2;
9809     }
9810   }
9811 
9812   if (PatternType == 0)
9813     return;
9814 
9815   // Generate the diagnostic.
9816   SourceLocation SL = LenArg->getBeginLoc();
9817   SourceRange SR = LenArg->getSourceRange();
9818   SourceManager &SM = getSourceManager();
9819 
9820   // If the function is defined as a builtin macro, do not show macro expansion.
9821   if (SM.isMacroArgExpansion(SL)) {
9822     SL = SM.getSpellingLoc(SL);
9823     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9824                      SM.getSpellingLoc(SR.getEnd()));
9825   }
9826 
9827   // Check if the destination is an array (rather than a pointer to an array).
9828   QualType DstTy = DstArg->getType();
9829   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9830                                                                     Context);
9831   if (!isKnownSizeArray) {
9832     if (PatternType == 1)
9833       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9834     else
9835       Diag(SL, diag::warn_strncat_src_size) << SR;
9836     return;
9837   }
9838 
9839   if (PatternType == 1)
9840     Diag(SL, diag::warn_strncat_large_size) << SR;
9841   else
9842     Diag(SL, diag::warn_strncat_src_size) << SR;
9843 
9844   SmallString<128> sizeString;
9845   llvm::raw_svector_ostream OS(sizeString);
9846   OS << "sizeof(";
9847   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9848   OS << ") - ";
9849   OS << "strlen(";
9850   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9851   OS << ") - 1";
9852 
9853   Diag(SL, diag::note_strncat_wrong_size)
9854     << FixItHint::CreateReplacement(SR, OS.str());
9855 }
9856 
9857 void
9858 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9859                          SourceLocation ReturnLoc,
9860                          bool isObjCMethod,
9861                          const AttrVec *Attrs,
9862                          const FunctionDecl *FD) {
9863   // Check if the return value is null but should not be.
9864   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9865        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9866       CheckNonNullExpr(*this, RetValExp))
9867     Diag(ReturnLoc, diag::warn_null_ret)
9868       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9869 
9870   // C++11 [basic.stc.dynamic.allocation]p4:
9871   //   If an allocation function declared with a non-throwing
9872   //   exception-specification fails to allocate storage, it shall return
9873   //   a null pointer. Any other allocation function that fails to allocate
9874   //   storage shall indicate failure only by throwing an exception [...]
9875   if (FD) {
9876     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9877     if (Op == OO_New || Op == OO_Array_New) {
9878       const FunctionProtoType *Proto
9879         = FD->getType()->castAs<FunctionProtoType>();
9880       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9881           CheckNonNullExpr(*this, RetValExp))
9882         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9883           << FD << getLangOpts().CPlusPlus11;
9884     }
9885   }
9886 }
9887 
9888 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9889 
9890 /// Check for comparisons of floating point operands using != and ==.
9891 /// Issue a warning if these are no self-comparisons, as they are not likely
9892 /// to do what the programmer intended.
9893 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9894   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9895   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9896 
9897   // Special case: check for x == x (which is OK).
9898   // Do not emit warnings for such cases.
9899   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9900     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9901       if (DRL->getDecl() == DRR->getDecl())
9902         return;
9903 
9904   // Special case: check for comparisons against literals that can be exactly
9905   //  represented by APFloat.  In such cases, do not emit a warning.  This
9906   //  is a heuristic: often comparison against such literals are used to
9907   //  detect if a value in a variable has not changed.  This clearly can
9908   //  lead to false negatives.
9909   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9910     if (FLL->isExact())
9911       return;
9912   } else
9913     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9914       if (FLR->isExact())
9915         return;
9916 
9917   // Check for comparisons with builtin types.
9918   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9919     if (CL->getBuiltinCallee())
9920       return;
9921 
9922   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9923     if (CR->getBuiltinCallee())
9924       return;
9925 
9926   // Emit the diagnostic.
9927   Diag(Loc, diag::warn_floatingpoint_eq)
9928     << LHS->getSourceRange() << RHS->getSourceRange();
9929 }
9930 
9931 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9932 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9933 
9934 namespace {
9935 
9936 /// Structure recording the 'active' range of an integer-valued
9937 /// expression.
9938 struct IntRange {
9939   /// The number of bits active in the int.
9940   unsigned Width;
9941 
9942   /// True if the int is known not to have negative values.
9943   bool NonNegative;
9944 
9945   IntRange(unsigned Width, bool NonNegative)
9946       : Width(Width), NonNegative(NonNegative) {}
9947 
9948   /// Returns the range of the bool type.
9949   static IntRange forBoolType() {
9950     return IntRange(1, true);
9951   }
9952 
9953   /// Returns the range of an opaque value of the given integral type.
9954   static IntRange forValueOfType(ASTContext &C, QualType T) {
9955     return forValueOfCanonicalType(C,
9956                           T->getCanonicalTypeInternal().getTypePtr());
9957   }
9958 
9959   /// Returns the range of an opaque value of a canonical integral type.
9960   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9961     assert(T->isCanonicalUnqualified());
9962 
9963     if (const VectorType *VT = dyn_cast<VectorType>(T))
9964       T = VT->getElementType().getTypePtr();
9965     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9966       T = CT->getElementType().getTypePtr();
9967     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9968       T = AT->getValueType().getTypePtr();
9969 
9970     if (!C.getLangOpts().CPlusPlus) {
9971       // For enum types in C code, use the underlying datatype.
9972       if (const EnumType *ET = dyn_cast<EnumType>(T))
9973         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9974     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9975       // For enum types in C++, use the known bit width of the enumerators.
9976       EnumDecl *Enum = ET->getDecl();
9977       // In C++11, enums can have a fixed underlying type. Use this type to
9978       // compute the range.
9979       if (Enum->isFixed()) {
9980         return IntRange(C.getIntWidth(QualType(T, 0)),
9981                         !ET->isSignedIntegerOrEnumerationType());
9982       }
9983 
9984       unsigned NumPositive = Enum->getNumPositiveBits();
9985       unsigned NumNegative = Enum->getNumNegativeBits();
9986 
9987       if (NumNegative == 0)
9988         return IntRange(NumPositive, true/*NonNegative*/);
9989       else
9990         return IntRange(std::max(NumPositive + 1, NumNegative),
9991                         false/*NonNegative*/);
9992     }
9993 
9994     if (const auto *EIT = dyn_cast<ExtIntType>(T))
9995       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9996 
9997     const BuiltinType *BT = cast<BuiltinType>(T);
9998     assert(BT->isInteger());
9999 
10000     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10001   }
10002 
10003   /// Returns the "target" range of a canonical integral type, i.e.
10004   /// the range of values expressible in the type.
10005   ///
10006   /// This matches forValueOfCanonicalType except that enums have the
10007   /// full range of their type, not the range of their enumerators.
10008   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10009     assert(T->isCanonicalUnqualified());
10010 
10011     if (const VectorType *VT = dyn_cast<VectorType>(T))
10012       T = VT->getElementType().getTypePtr();
10013     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10014       T = CT->getElementType().getTypePtr();
10015     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10016       T = AT->getValueType().getTypePtr();
10017     if (const EnumType *ET = dyn_cast<EnumType>(T))
10018       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10019 
10020     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10021       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10022 
10023     const BuiltinType *BT = cast<BuiltinType>(T);
10024     assert(BT->isInteger());
10025 
10026     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10027   }
10028 
10029   /// Returns the supremum of two ranges: i.e. their conservative merge.
10030   static IntRange join(IntRange L, IntRange R) {
10031     return IntRange(std::max(L.Width, R.Width),
10032                     L.NonNegative && R.NonNegative);
10033   }
10034 
10035   /// Returns the infinum of two ranges: i.e. their aggressive merge.
10036   static IntRange meet(IntRange L, IntRange R) {
10037     return IntRange(std::min(L.Width, R.Width),
10038                     L.NonNegative || R.NonNegative);
10039   }
10040 };
10041 
10042 } // namespace
10043 
10044 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10045                               unsigned MaxWidth) {
10046   if (value.isSigned() && value.isNegative())
10047     return IntRange(value.getMinSignedBits(), false);
10048 
10049   if (value.getBitWidth() > MaxWidth)
10050     value = value.trunc(MaxWidth);
10051 
10052   // isNonNegative() just checks the sign bit without considering
10053   // signedness.
10054   return IntRange(value.getActiveBits(), true);
10055 }
10056 
10057 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10058                               unsigned MaxWidth) {
10059   if (result.isInt())
10060     return GetValueRange(C, result.getInt(), MaxWidth);
10061 
10062   if (result.isVector()) {
10063     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10064     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10065       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10066       R = IntRange::join(R, El);
10067     }
10068     return R;
10069   }
10070 
10071   if (result.isComplexInt()) {
10072     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10073     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10074     return IntRange::join(R, I);
10075   }
10076 
10077   // This can happen with lossless casts to intptr_t of "based" lvalues.
10078   // Assume it might use arbitrary bits.
10079   // FIXME: The only reason we need to pass the type in here is to get
10080   // the sign right on this one case.  It would be nice if APValue
10081   // preserved this.
10082   assert(result.isLValue() || result.isAddrLabelDiff());
10083   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10084 }
10085 
10086 static QualType GetExprType(const Expr *E) {
10087   QualType Ty = E->getType();
10088   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10089     Ty = AtomicRHS->getValueType();
10090   return Ty;
10091 }
10092 
10093 /// Pseudo-evaluate the given integer expression, estimating the
10094 /// range of values it might take.
10095 ///
10096 /// \param MaxWidth - the width to which the value will be truncated
10097 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10098                              bool InConstantContext) {
10099   E = E->IgnoreParens();
10100 
10101   // Try a full evaluation first.
10102   Expr::EvalResult result;
10103   if (E->EvaluateAsRValue(result, C, InConstantContext))
10104     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10105 
10106   // I think we only want to look through implicit casts here; if the
10107   // user has an explicit widening cast, we should treat the value as
10108   // being of the new, wider type.
10109   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10110     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10111       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10112 
10113     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10114 
10115     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10116                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10117 
10118     // Assume that non-integer casts can span the full range of the type.
10119     if (!isIntegerCast)
10120       return OutputTypeRange;
10121 
10122     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10123                                      std::min(MaxWidth, OutputTypeRange.Width),
10124                                      InConstantContext);
10125 
10126     // Bail out if the subexpr's range is as wide as the cast type.
10127     if (SubRange.Width >= OutputTypeRange.Width)
10128       return OutputTypeRange;
10129 
10130     // Otherwise, we take the smaller width, and we're non-negative if
10131     // either the output type or the subexpr is.
10132     return IntRange(SubRange.Width,
10133                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10134   }
10135 
10136   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10137     // If we can fold the condition, just take that operand.
10138     bool CondResult;
10139     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10140       return GetExprRange(C,
10141                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10142                           MaxWidth, InConstantContext);
10143 
10144     // Otherwise, conservatively merge.
10145     IntRange L =
10146         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10147     IntRange R =
10148         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10149     return IntRange::join(L, R);
10150   }
10151 
10152   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10153     switch (BO->getOpcode()) {
10154     case BO_Cmp:
10155       llvm_unreachable("builtin <=> should have class type");
10156 
10157     // Boolean-valued operations are single-bit and positive.
10158     case BO_LAnd:
10159     case BO_LOr:
10160     case BO_LT:
10161     case BO_GT:
10162     case BO_LE:
10163     case BO_GE:
10164     case BO_EQ:
10165     case BO_NE:
10166       return IntRange::forBoolType();
10167 
10168     // The type of the assignments is the type of the LHS, so the RHS
10169     // is not necessarily the same type.
10170     case BO_MulAssign:
10171     case BO_DivAssign:
10172     case BO_RemAssign:
10173     case BO_AddAssign:
10174     case BO_SubAssign:
10175     case BO_XorAssign:
10176     case BO_OrAssign:
10177       // TODO: bitfields?
10178       return IntRange::forValueOfType(C, GetExprType(E));
10179 
10180     // Simple assignments just pass through the RHS, which will have
10181     // been coerced to the LHS type.
10182     case BO_Assign:
10183       // TODO: bitfields?
10184       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10185 
10186     // Operations with opaque sources are black-listed.
10187     case BO_PtrMemD:
10188     case BO_PtrMemI:
10189       return IntRange::forValueOfType(C, GetExprType(E));
10190 
10191     // Bitwise-and uses the *infinum* of the two source ranges.
10192     case BO_And:
10193     case BO_AndAssign:
10194       return IntRange::meet(
10195           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10196           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10197 
10198     // Left shift gets black-listed based on a judgement call.
10199     case BO_Shl:
10200       // ...except that we want to treat '1 << (blah)' as logically
10201       // positive.  It's an important idiom.
10202       if (IntegerLiteral *I
10203             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10204         if (I->getValue() == 1) {
10205           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10206           return IntRange(R.Width, /*NonNegative*/ true);
10207         }
10208       }
10209       LLVM_FALLTHROUGH;
10210 
10211     case BO_ShlAssign:
10212       return IntRange::forValueOfType(C, GetExprType(E));
10213 
10214     // Right shift by a constant can narrow its left argument.
10215     case BO_Shr:
10216     case BO_ShrAssign: {
10217       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10218 
10219       // If the shift amount is a positive constant, drop the width by
10220       // that much.
10221       llvm::APSInt shift;
10222       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10223           shift.isNonNegative()) {
10224         unsigned zext = shift.getZExtValue();
10225         if (zext >= L.Width)
10226           L.Width = (L.NonNegative ? 0 : 1);
10227         else
10228           L.Width -= zext;
10229       }
10230 
10231       return L;
10232     }
10233 
10234     // Comma acts as its right operand.
10235     case BO_Comma:
10236       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10237 
10238     // Black-list pointer subtractions.
10239     case BO_Sub:
10240       if (BO->getLHS()->getType()->isPointerType())
10241         return IntRange::forValueOfType(C, GetExprType(E));
10242       break;
10243 
10244     // The width of a division result is mostly determined by the size
10245     // of the LHS.
10246     case BO_Div: {
10247       // Don't 'pre-truncate' the operands.
10248       unsigned opWidth = C.getIntWidth(GetExprType(E));
10249       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10250 
10251       // If the divisor is constant, use that.
10252       llvm::APSInt divisor;
10253       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10254         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10255         if (log2 >= L.Width)
10256           L.Width = (L.NonNegative ? 0 : 1);
10257         else
10258           L.Width = std::min(L.Width - log2, MaxWidth);
10259         return L;
10260       }
10261 
10262       // Otherwise, just use the LHS's width.
10263       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10264       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10265     }
10266 
10267     // The result of a remainder can't be larger than the result of
10268     // either side.
10269     case BO_Rem: {
10270       // Don't 'pre-truncate' the operands.
10271       unsigned opWidth = C.getIntWidth(GetExprType(E));
10272       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10273       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10274 
10275       IntRange meet = IntRange::meet(L, R);
10276       meet.Width = std::min(meet.Width, MaxWidth);
10277       return meet;
10278     }
10279 
10280     // The default behavior is okay for these.
10281     case BO_Mul:
10282     case BO_Add:
10283     case BO_Xor:
10284     case BO_Or:
10285       break;
10286     }
10287 
10288     // The default case is to treat the operation as if it were closed
10289     // on the narrowest type that encompasses both operands.
10290     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10291     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10292     return IntRange::join(L, R);
10293   }
10294 
10295   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10296     switch (UO->getOpcode()) {
10297     // Boolean-valued operations are white-listed.
10298     case UO_LNot:
10299       return IntRange::forBoolType();
10300 
10301     // Operations with opaque sources are black-listed.
10302     case UO_Deref:
10303     case UO_AddrOf: // should be impossible
10304       return IntRange::forValueOfType(C, GetExprType(E));
10305 
10306     default:
10307       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10308     }
10309   }
10310 
10311   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10312     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10313 
10314   if (const auto *BitField = E->getSourceBitField())
10315     return IntRange(BitField->getBitWidthValue(C),
10316                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10317 
10318   return IntRange::forValueOfType(C, GetExprType(E));
10319 }
10320 
10321 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10322                              bool InConstantContext) {
10323   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10324 }
10325 
10326 /// Checks whether the given value, which currently has the given
10327 /// source semantics, has the same value when coerced through the
10328 /// target semantics.
10329 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10330                                  const llvm::fltSemantics &Src,
10331                                  const llvm::fltSemantics &Tgt) {
10332   llvm::APFloat truncated = value;
10333 
10334   bool ignored;
10335   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10336   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10337 
10338   return truncated.bitwiseIsEqual(value);
10339 }
10340 
10341 /// Checks whether the given value, which currently has the given
10342 /// source semantics, has the same value when coerced through the
10343 /// target semantics.
10344 ///
10345 /// The value might be a vector of floats (or a complex number).
10346 static bool IsSameFloatAfterCast(const APValue &value,
10347                                  const llvm::fltSemantics &Src,
10348                                  const llvm::fltSemantics &Tgt) {
10349   if (value.isFloat())
10350     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10351 
10352   if (value.isVector()) {
10353     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10354       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10355         return false;
10356     return true;
10357   }
10358 
10359   assert(value.isComplexFloat());
10360   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10361           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10362 }
10363 
10364 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10365                                        bool IsListInit = false);
10366 
10367 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10368   // Suppress cases where we are comparing against an enum constant.
10369   if (const DeclRefExpr *DR =
10370       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10371     if (isa<EnumConstantDecl>(DR->getDecl()))
10372       return true;
10373 
10374   // Suppress cases where the value is expanded from a macro, unless that macro
10375   // is how a language represents a boolean literal. This is the case in both C
10376   // and Objective-C.
10377   SourceLocation BeginLoc = E->getBeginLoc();
10378   if (BeginLoc.isMacroID()) {
10379     StringRef MacroName = Lexer::getImmediateMacroName(
10380         BeginLoc, S.getSourceManager(), S.getLangOpts());
10381     return MacroName != "YES" && MacroName != "NO" &&
10382            MacroName != "true" && MacroName != "false";
10383   }
10384 
10385   return false;
10386 }
10387 
10388 static bool isKnownToHaveUnsignedValue(Expr *E) {
10389   return E->getType()->isIntegerType() &&
10390          (!E->getType()->isSignedIntegerType() ||
10391           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10392 }
10393 
10394 namespace {
10395 /// The promoted range of values of a type. In general this has the
10396 /// following structure:
10397 ///
10398 ///     |-----------| . . . |-----------|
10399 ///     ^           ^       ^           ^
10400 ///    Min       HoleMin  HoleMax      Max
10401 ///
10402 /// ... where there is only a hole if a signed type is promoted to unsigned
10403 /// (in which case Min and Max are the smallest and largest representable
10404 /// values).
10405 struct PromotedRange {
10406   // Min, or HoleMax if there is a hole.
10407   llvm::APSInt PromotedMin;
10408   // Max, or HoleMin if there is a hole.
10409   llvm::APSInt PromotedMax;
10410 
10411   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10412     if (R.Width == 0)
10413       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10414     else if (R.Width >= BitWidth && !Unsigned) {
10415       // Promotion made the type *narrower*. This happens when promoting
10416       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10417       // Treat all values of 'signed int' as being in range for now.
10418       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10419       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10420     } else {
10421       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10422                         .extOrTrunc(BitWidth);
10423       PromotedMin.setIsUnsigned(Unsigned);
10424 
10425       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10426                         .extOrTrunc(BitWidth);
10427       PromotedMax.setIsUnsigned(Unsigned);
10428     }
10429   }
10430 
10431   // Determine whether this range is contiguous (has no hole).
10432   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10433 
10434   // Where a constant value is within the range.
10435   enum ComparisonResult {
10436     LT = 0x1,
10437     LE = 0x2,
10438     GT = 0x4,
10439     GE = 0x8,
10440     EQ = 0x10,
10441     NE = 0x20,
10442     InRangeFlag = 0x40,
10443 
10444     Less = LE | LT | NE,
10445     Min = LE | InRangeFlag,
10446     InRange = InRangeFlag,
10447     Max = GE | InRangeFlag,
10448     Greater = GE | GT | NE,
10449 
10450     OnlyValue = LE | GE | EQ | InRangeFlag,
10451     InHole = NE
10452   };
10453 
10454   ComparisonResult compare(const llvm::APSInt &Value) const {
10455     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10456            Value.isUnsigned() == PromotedMin.isUnsigned());
10457     if (!isContiguous()) {
10458       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10459       if (Value.isMinValue()) return Min;
10460       if (Value.isMaxValue()) return Max;
10461       if (Value >= PromotedMin) return InRange;
10462       if (Value <= PromotedMax) return InRange;
10463       return InHole;
10464     }
10465 
10466     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10467     case -1: return Less;
10468     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10469     case 1:
10470       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10471       case -1: return InRange;
10472       case 0: return Max;
10473       case 1: return Greater;
10474       }
10475     }
10476 
10477     llvm_unreachable("impossible compare result");
10478   }
10479 
10480   static llvm::Optional<StringRef>
10481   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10482     if (Op == BO_Cmp) {
10483       ComparisonResult LTFlag = LT, GTFlag = GT;
10484       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10485 
10486       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10487       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10488       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10489       return llvm::None;
10490     }
10491 
10492     ComparisonResult TrueFlag, FalseFlag;
10493     if (Op == BO_EQ) {
10494       TrueFlag = EQ;
10495       FalseFlag = NE;
10496     } else if (Op == BO_NE) {
10497       TrueFlag = NE;
10498       FalseFlag = EQ;
10499     } else {
10500       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10501         TrueFlag = LT;
10502         FalseFlag = GE;
10503       } else {
10504         TrueFlag = GT;
10505         FalseFlag = LE;
10506       }
10507       if (Op == BO_GE || Op == BO_LE)
10508         std::swap(TrueFlag, FalseFlag);
10509     }
10510     if (R & TrueFlag)
10511       return StringRef("true");
10512     if (R & FalseFlag)
10513       return StringRef("false");
10514     return llvm::None;
10515   }
10516 };
10517 }
10518 
10519 static bool HasEnumType(Expr *E) {
10520   // Strip off implicit integral promotions.
10521   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10522     if (ICE->getCastKind() != CK_IntegralCast &&
10523         ICE->getCastKind() != CK_NoOp)
10524       break;
10525     E = ICE->getSubExpr();
10526   }
10527 
10528   return E->getType()->isEnumeralType();
10529 }
10530 
10531 static int classifyConstantValue(Expr *Constant) {
10532   // The values of this enumeration are used in the diagnostics
10533   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10534   enum ConstantValueKind {
10535     Miscellaneous = 0,
10536     LiteralTrue,
10537     LiteralFalse
10538   };
10539   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10540     return BL->getValue() ? ConstantValueKind::LiteralTrue
10541                           : ConstantValueKind::LiteralFalse;
10542   return ConstantValueKind::Miscellaneous;
10543 }
10544 
10545 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10546                                         Expr *Constant, Expr *Other,
10547                                         const llvm::APSInt &Value,
10548                                         bool RhsConstant) {
10549   if (S.inTemplateInstantiation())
10550     return false;
10551 
10552   Expr *OriginalOther = Other;
10553 
10554   Constant = Constant->IgnoreParenImpCasts();
10555   Other = Other->IgnoreParenImpCasts();
10556 
10557   // Suppress warnings on tautological comparisons between values of the same
10558   // enumeration type. There are only two ways we could warn on this:
10559   //  - If the constant is outside the range of representable values of
10560   //    the enumeration. In such a case, we should warn about the cast
10561   //    to enumeration type, not about the comparison.
10562   //  - If the constant is the maximum / minimum in-range value. For an
10563   //    enumeratin type, such comparisons can be meaningful and useful.
10564   if (Constant->getType()->isEnumeralType() &&
10565       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10566     return false;
10567 
10568   // TODO: Investigate using GetExprRange() to get tighter bounds
10569   // on the bit ranges.
10570   QualType OtherT = Other->getType();
10571   if (const auto *AT = OtherT->getAs<AtomicType>())
10572     OtherT = AT->getValueType();
10573   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10574 
10575   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10576   // (Namely, macOS).
10577   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10578                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10579                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10580 
10581   // Whether we're treating Other as being a bool because of the form of
10582   // expression despite it having another type (typically 'int' in C).
10583   bool OtherIsBooleanDespiteType =
10584       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10585   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10586     OtherRange = IntRange::forBoolType();
10587 
10588   // Determine the promoted range of the other type and see if a comparison of
10589   // the constant against that range is tautological.
10590   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10591                                    Value.isUnsigned());
10592   auto Cmp = OtherPromotedRange.compare(Value);
10593   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10594   if (!Result)
10595     return false;
10596 
10597   // Suppress the diagnostic for an in-range comparison if the constant comes
10598   // from a macro or enumerator. We don't want to diagnose
10599   //
10600   //   some_long_value <= INT_MAX
10601   //
10602   // when sizeof(int) == sizeof(long).
10603   bool InRange = Cmp & PromotedRange::InRangeFlag;
10604   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10605     return false;
10606 
10607   // If this is a comparison to an enum constant, include that
10608   // constant in the diagnostic.
10609   const EnumConstantDecl *ED = nullptr;
10610   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10611     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10612 
10613   // Should be enough for uint128 (39 decimal digits)
10614   SmallString<64> PrettySourceValue;
10615   llvm::raw_svector_ostream OS(PrettySourceValue);
10616   if (ED) {
10617     OS << '\'' << *ED << "' (" << Value << ")";
10618   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10619                Constant->IgnoreParenImpCasts())) {
10620     OS << (BL->getValue() ? "YES" : "NO");
10621   } else {
10622     OS << Value;
10623   }
10624 
10625   if (IsObjCSignedCharBool) {
10626     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10627                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10628                               << OS.str() << *Result);
10629     return true;
10630   }
10631 
10632   // FIXME: We use a somewhat different formatting for the in-range cases and
10633   // cases involving boolean values for historical reasons. We should pick a
10634   // consistent way of presenting these diagnostics.
10635   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10636 
10637     S.DiagRuntimeBehavior(
10638         E->getOperatorLoc(), E,
10639         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10640                          : diag::warn_tautological_bool_compare)
10641             << OS.str() << classifyConstantValue(Constant) << OtherT
10642             << OtherIsBooleanDespiteType << *Result
10643             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10644   } else {
10645     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10646                         ? (HasEnumType(OriginalOther)
10647                                ? diag::warn_unsigned_enum_always_true_comparison
10648                                : diag::warn_unsigned_always_true_comparison)
10649                         : diag::warn_tautological_constant_compare;
10650 
10651     S.Diag(E->getOperatorLoc(), Diag)
10652         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10653         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10654   }
10655 
10656   return true;
10657 }
10658 
10659 /// Analyze the operands of the given comparison.  Implements the
10660 /// fallback case from AnalyzeComparison.
10661 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10662   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10663   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10664 }
10665 
10666 /// Implements -Wsign-compare.
10667 ///
10668 /// \param E the binary operator to check for warnings
10669 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10670   // The type the comparison is being performed in.
10671   QualType T = E->getLHS()->getType();
10672 
10673   // Only analyze comparison operators where both sides have been converted to
10674   // the same type.
10675   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10676     return AnalyzeImpConvsInComparison(S, E);
10677 
10678   // Don't analyze value-dependent comparisons directly.
10679   if (E->isValueDependent())
10680     return AnalyzeImpConvsInComparison(S, E);
10681 
10682   Expr *LHS = E->getLHS();
10683   Expr *RHS = E->getRHS();
10684 
10685   if (T->isIntegralType(S.Context)) {
10686     llvm::APSInt RHSValue;
10687     llvm::APSInt LHSValue;
10688 
10689     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10690     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10691 
10692     // We don't care about expressions whose result is a constant.
10693     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10694       return AnalyzeImpConvsInComparison(S, E);
10695 
10696     // We only care about expressions where just one side is literal
10697     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10698       // Is the constant on the RHS or LHS?
10699       const bool RhsConstant = IsRHSIntegralLiteral;
10700       Expr *Const = RhsConstant ? RHS : LHS;
10701       Expr *Other = RhsConstant ? LHS : RHS;
10702       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10703 
10704       // Check whether an integer constant comparison results in a value
10705       // of 'true' or 'false'.
10706       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10707         return AnalyzeImpConvsInComparison(S, E);
10708     }
10709   }
10710 
10711   if (!T->hasUnsignedIntegerRepresentation()) {
10712     // We don't do anything special if this isn't an unsigned integral
10713     // comparison:  we're only interested in integral comparisons, and
10714     // signed comparisons only happen in cases we don't care to warn about.
10715     return AnalyzeImpConvsInComparison(S, E);
10716   }
10717 
10718   LHS = LHS->IgnoreParenImpCasts();
10719   RHS = RHS->IgnoreParenImpCasts();
10720 
10721   if (!S.getLangOpts().CPlusPlus) {
10722     // Avoid warning about comparison of integers with different signs when
10723     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10724     // the type of `E`.
10725     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10726       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10727     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10728       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10729   }
10730 
10731   // Check to see if one of the (unmodified) operands is of different
10732   // signedness.
10733   Expr *signedOperand, *unsignedOperand;
10734   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10735     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10736            "unsigned comparison between two signed integer expressions?");
10737     signedOperand = LHS;
10738     unsignedOperand = RHS;
10739   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10740     signedOperand = RHS;
10741     unsignedOperand = LHS;
10742   } else {
10743     return AnalyzeImpConvsInComparison(S, E);
10744   }
10745 
10746   // Otherwise, calculate the effective range of the signed operand.
10747   IntRange signedRange =
10748       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10749 
10750   // Go ahead and analyze implicit conversions in the operands.  Note
10751   // that we skip the implicit conversions on both sides.
10752   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10753   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10754 
10755   // If the signed range is non-negative, -Wsign-compare won't fire.
10756   if (signedRange.NonNegative)
10757     return;
10758 
10759   // For (in)equality comparisons, if the unsigned operand is a
10760   // constant which cannot collide with a overflowed signed operand,
10761   // then reinterpreting the signed operand as unsigned will not
10762   // change the result of the comparison.
10763   if (E->isEqualityOp()) {
10764     unsigned comparisonWidth = S.Context.getIntWidth(T);
10765     IntRange unsignedRange =
10766         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10767 
10768     // We should never be unable to prove that the unsigned operand is
10769     // non-negative.
10770     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10771 
10772     if (unsignedRange.Width < comparisonWidth)
10773       return;
10774   }
10775 
10776   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10777                         S.PDiag(diag::warn_mixed_sign_comparison)
10778                             << LHS->getType() << RHS->getType()
10779                             << LHS->getSourceRange() << RHS->getSourceRange());
10780 }
10781 
10782 /// Analyzes an attempt to assign the given value to a bitfield.
10783 ///
10784 /// Returns true if there was something fishy about the attempt.
10785 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10786                                       SourceLocation InitLoc) {
10787   assert(Bitfield->isBitField());
10788   if (Bitfield->isInvalidDecl())
10789     return false;
10790 
10791   // White-list bool bitfields.
10792   QualType BitfieldType = Bitfield->getType();
10793   if (BitfieldType->isBooleanType())
10794      return false;
10795 
10796   if (BitfieldType->isEnumeralType()) {
10797     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10798     // If the underlying enum type was not explicitly specified as an unsigned
10799     // type and the enum contain only positive values, MSVC++ will cause an
10800     // inconsistency by storing this as a signed type.
10801     if (S.getLangOpts().CPlusPlus11 &&
10802         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10803         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10804         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10805       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10806         << BitfieldEnumDecl->getNameAsString();
10807     }
10808   }
10809 
10810   if (Bitfield->getType()->isBooleanType())
10811     return false;
10812 
10813   // Ignore value- or type-dependent expressions.
10814   if (Bitfield->getBitWidth()->isValueDependent() ||
10815       Bitfield->getBitWidth()->isTypeDependent() ||
10816       Init->isValueDependent() ||
10817       Init->isTypeDependent())
10818     return false;
10819 
10820   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10821   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10822 
10823   Expr::EvalResult Result;
10824   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10825                                    Expr::SE_AllowSideEffects)) {
10826     // The RHS is not constant.  If the RHS has an enum type, make sure the
10827     // bitfield is wide enough to hold all the values of the enum without
10828     // truncation.
10829     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10830       EnumDecl *ED = EnumTy->getDecl();
10831       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10832 
10833       // Enum types are implicitly signed on Windows, so check if there are any
10834       // negative enumerators to see if the enum was intended to be signed or
10835       // not.
10836       bool SignedEnum = ED->getNumNegativeBits() > 0;
10837 
10838       // Check for surprising sign changes when assigning enum values to a
10839       // bitfield of different signedness.  If the bitfield is signed and we
10840       // have exactly the right number of bits to store this unsigned enum,
10841       // suggest changing the enum to an unsigned type. This typically happens
10842       // on Windows where unfixed enums always use an underlying type of 'int'.
10843       unsigned DiagID = 0;
10844       if (SignedEnum && !SignedBitfield) {
10845         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10846       } else if (SignedBitfield && !SignedEnum &&
10847                  ED->getNumPositiveBits() == FieldWidth) {
10848         DiagID = diag::warn_signed_bitfield_enum_conversion;
10849       }
10850 
10851       if (DiagID) {
10852         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10853         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10854         SourceRange TypeRange =
10855             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10856         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10857             << SignedEnum << TypeRange;
10858       }
10859 
10860       // Compute the required bitwidth. If the enum has negative values, we need
10861       // one more bit than the normal number of positive bits to represent the
10862       // sign bit.
10863       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10864                                                   ED->getNumNegativeBits())
10865                                        : ED->getNumPositiveBits();
10866 
10867       // Check the bitwidth.
10868       if (BitsNeeded > FieldWidth) {
10869         Expr *WidthExpr = Bitfield->getBitWidth();
10870         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10871             << Bitfield << ED;
10872         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10873             << BitsNeeded << ED << WidthExpr->getSourceRange();
10874       }
10875     }
10876 
10877     return false;
10878   }
10879 
10880   llvm::APSInt Value = Result.Val.getInt();
10881 
10882   unsigned OriginalWidth = Value.getBitWidth();
10883 
10884   if (!Value.isSigned() || Value.isNegative())
10885     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10886       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10887         OriginalWidth = Value.getMinSignedBits();
10888 
10889   if (OriginalWidth <= FieldWidth)
10890     return false;
10891 
10892   // Compute the value which the bitfield will contain.
10893   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10894   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10895 
10896   // Check whether the stored value is equal to the original value.
10897   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10898   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10899     return false;
10900 
10901   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10902   // therefore don't strictly fit into a signed bitfield of width 1.
10903   if (FieldWidth == 1 && Value == 1)
10904     return false;
10905 
10906   std::string PrettyValue = Value.toString(10);
10907   std::string PrettyTrunc = TruncatedValue.toString(10);
10908 
10909   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10910     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10911     << Init->getSourceRange();
10912 
10913   return true;
10914 }
10915 
10916 /// Analyze the given simple or compound assignment for warning-worthy
10917 /// operations.
10918 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10919   // Just recurse on the LHS.
10920   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10921 
10922   // We want to recurse on the RHS as normal unless we're assigning to
10923   // a bitfield.
10924   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10925     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10926                                   E->getOperatorLoc())) {
10927       // Recurse, ignoring any implicit conversions on the RHS.
10928       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10929                                         E->getOperatorLoc());
10930     }
10931   }
10932 
10933   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10934 
10935   // Diagnose implicitly sequentially-consistent atomic assignment.
10936   if (E->getLHS()->getType()->isAtomicType())
10937     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10938 }
10939 
10940 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10941 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10942                             SourceLocation CContext, unsigned diag,
10943                             bool pruneControlFlow = false) {
10944   if (pruneControlFlow) {
10945     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10946                           S.PDiag(diag)
10947                               << SourceType << T << E->getSourceRange()
10948                               << SourceRange(CContext));
10949     return;
10950   }
10951   S.Diag(E->getExprLoc(), diag)
10952     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10953 }
10954 
10955 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10956 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10957                             SourceLocation CContext,
10958                             unsigned diag, bool pruneControlFlow = false) {
10959   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10960 }
10961 
10962 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10963   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10964       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10965 }
10966 
10967 static void adornObjCBoolConversionDiagWithTernaryFixit(
10968     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10969   Expr *Ignored = SourceExpr->IgnoreImplicit();
10970   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10971     Ignored = OVE->getSourceExpr();
10972   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10973                      isa<BinaryOperator>(Ignored) ||
10974                      isa<CXXOperatorCallExpr>(Ignored);
10975   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10976   if (NeedsParens)
10977     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10978             << FixItHint::CreateInsertion(EndLoc, ")");
10979   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10980 }
10981 
10982 /// Diagnose an implicit cast from a floating point value to an integer value.
10983 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10984                                     SourceLocation CContext) {
10985   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10986   const bool PruneWarnings = S.inTemplateInstantiation();
10987 
10988   Expr *InnerE = E->IgnoreParenImpCasts();
10989   // We also want to warn on, e.g., "int i = -1.234"
10990   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10991     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10992       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10993 
10994   const bool IsLiteral =
10995       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10996 
10997   llvm::APFloat Value(0.0);
10998   bool IsConstant =
10999     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11000   if (!IsConstant) {
11001     if (isObjCSignedCharBool(S, T)) {
11002       return adornObjCBoolConversionDiagWithTernaryFixit(
11003           S, E,
11004           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11005               << E->getType());
11006     }
11007 
11008     return DiagnoseImpCast(S, E, T, CContext,
11009                            diag::warn_impcast_float_integer, PruneWarnings);
11010   }
11011 
11012   bool isExact = false;
11013 
11014   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11015                             T->hasUnsignedIntegerRepresentation());
11016   llvm::APFloat::opStatus Result = Value.convertToInteger(
11017       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11018 
11019   // FIXME: Force the precision of the source value down so we don't print
11020   // digits which are usually useless (we don't really care here if we
11021   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11022   // would automatically print the shortest representation, but it's a bit
11023   // tricky to implement.
11024   SmallString<16> PrettySourceValue;
11025   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11026   precision = (precision * 59 + 195) / 196;
11027   Value.toString(PrettySourceValue, precision);
11028 
11029   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11030     return adornObjCBoolConversionDiagWithTernaryFixit(
11031         S, E,
11032         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11033             << PrettySourceValue);
11034   }
11035 
11036   if (Result == llvm::APFloat::opOK && isExact) {
11037     if (IsLiteral) return;
11038     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11039                            PruneWarnings);
11040   }
11041 
11042   // Conversion of a floating-point value to a non-bool integer where the
11043   // integral part cannot be represented by the integer type is undefined.
11044   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11045     return DiagnoseImpCast(
11046         S, E, T, CContext,
11047         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11048                   : diag::warn_impcast_float_to_integer_out_of_range,
11049         PruneWarnings);
11050 
11051   unsigned DiagID = 0;
11052   if (IsLiteral) {
11053     // Warn on floating point literal to integer.
11054     DiagID = diag::warn_impcast_literal_float_to_integer;
11055   } else if (IntegerValue == 0) {
11056     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11057       return DiagnoseImpCast(S, E, T, CContext,
11058                              diag::warn_impcast_float_integer, PruneWarnings);
11059     }
11060     // Warn on non-zero to zero conversion.
11061     DiagID = diag::warn_impcast_float_to_integer_zero;
11062   } else {
11063     if (IntegerValue.isUnsigned()) {
11064       if (!IntegerValue.isMaxValue()) {
11065         return DiagnoseImpCast(S, E, T, CContext,
11066                                diag::warn_impcast_float_integer, PruneWarnings);
11067       }
11068     } else {  // IntegerValue.isSigned()
11069       if (!IntegerValue.isMaxSignedValue() &&
11070           !IntegerValue.isMinSignedValue()) {
11071         return DiagnoseImpCast(S, E, T, CContext,
11072                                diag::warn_impcast_float_integer, PruneWarnings);
11073       }
11074     }
11075     // Warn on evaluatable floating point expression to integer conversion.
11076     DiagID = diag::warn_impcast_float_to_integer;
11077   }
11078 
11079   SmallString<16> PrettyTargetValue;
11080   if (IsBool)
11081     PrettyTargetValue = Value.isZero() ? "false" : "true";
11082   else
11083     IntegerValue.toString(PrettyTargetValue);
11084 
11085   if (PruneWarnings) {
11086     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11087                           S.PDiag(DiagID)
11088                               << E->getType() << T.getUnqualifiedType()
11089                               << PrettySourceValue << PrettyTargetValue
11090                               << E->getSourceRange() << SourceRange(CContext));
11091   } else {
11092     S.Diag(E->getExprLoc(), DiagID)
11093         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11094         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11095   }
11096 }
11097 
11098 /// Analyze the given compound assignment for the possible losing of
11099 /// floating-point precision.
11100 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11101   assert(isa<CompoundAssignOperator>(E) &&
11102          "Must be compound assignment operation");
11103   // Recurse on the LHS and RHS in here
11104   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11105   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11106 
11107   if (E->getLHS()->getType()->isAtomicType())
11108     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11109 
11110   // Now check the outermost expression
11111   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11112   const auto *RBT = cast<CompoundAssignOperator>(E)
11113                         ->getComputationResultType()
11114                         ->getAs<BuiltinType>();
11115 
11116   // The below checks assume source is floating point.
11117   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11118 
11119   // If source is floating point but target is an integer.
11120   if (ResultBT->isInteger())
11121     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11122                            E->getExprLoc(), diag::warn_impcast_float_integer);
11123 
11124   if (!ResultBT->isFloatingPoint())
11125     return;
11126 
11127   // If both source and target are floating points, warn about losing precision.
11128   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11129       QualType(ResultBT, 0), QualType(RBT, 0));
11130   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11131     // warn about dropping FP rank.
11132     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11133                     diag::warn_impcast_float_result_precision);
11134 }
11135 
11136 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11137                                       IntRange Range) {
11138   if (!Range.Width) return "0";
11139 
11140   llvm::APSInt ValueInRange = Value;
11141   ValueInRange.setIsSigned(!Range.NonNegative);
11142   ValueInRange = ValueInRange.trunc(Range.Width);
11143   return ValueInRange.toString(10);
11144 }
11145 
11146 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11147   if (!isa<ImplicitCastExpr>(Ex))
11148     return false;
11149 
11150   Expr *InnerE = Ex->IgnoreParenImpCasts();
11151   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11152   const Type *Source =
11153     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11154   if (Target->isDependentType())
11155     return false;
11156 
11157   const BuiltinType *FloatCandidateBT =
11158     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11159   const Type *BoolCandidateType = ToBool ? Target : Source;
11160 
11161   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11162           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11163 }
11164 
11165 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11166                                              SourceLocation CC) {
11167   unsigned NumArgs = TheCall->getNumArgs();
11168   for (unsigned i = 0; i < NumArgs; ++i) {
11169     Expr *CurrA = TheCall->getArg(i);
11170     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11171       continue;
11172 
11173     bool IsSwapped = ((i > 0) &&
11174         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11175     IsSwapped |= ((i < (NumArgs - 1)) &&
11176         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11177     if (IsSwapped) {
11178       // Warn on this floating-point to bool conversion.
11179       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11180                       CurrA->getType(), CC,
11181                       diag::warn_impcast_floating_point_to_bool);
11182     }
11183   }
11184 }
11185 
11186 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11187                                    SourceLocation CC) {
11188   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11189                         E->getExprLoc()))
11190     return;
11191 
11192   // Don't warn on functions which have return type nullptr_t.
11193   if (isa<CallExpr>(E))
11194     return;
11195 
11196   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11197   const Expr::NullPointerConstantKind NullKind =
11198       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11199   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11200     return;
11201 
11202   // Return if target type is a safe conversion.
11203   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11204       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11205     return;
11206 
11207   SourceLocation Loc = E->getSourceRange().getBegin();
11208 
11209   // Venture through the macro stacks to get to the source of macro arguments.
11210   // The new location is a better location than the complete location that was
11211   // passed in.
11212   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11213   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11214 
11215   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11216   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11217     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11218         Loc, S.SourceMgr, S.getLangOpts());
11219     if (MacroName == "NULL")
11220       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11221   }
11222 
11223   // Only warn if the null and context location are in the same macro expansion.
11224   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11225     return;
11226 
11227   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11228       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11229       << FixItHint::CreateReplacement(Loc,
11230                                       S.getFixItZeroLiteralForType(T, Loc));
11231 }
11232 
11233 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11234                                   ObjCArrayLiteral *ArrayLiteral);
11235 
11236 static void
11237 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11238                            ObjCDictionaryLiteral *DictionaryLiteral);
11239 
11240 /// Check a single element within a collection literal against the
11241 /// target element type.
11242 static void checkObjCCollectionLiteralElement(Sema &S,
11243                                               QualType TargetElementType,
11244                                               Expr *Element,
11245                                               unsigned ElementKind) {
11246   // Skip a bitcast to 'id' or qualified 'id'.
11247   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11248     if (ICE->getCastKind() == CK_BitCast &&
11249         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11250       Element = ICE->getSubExpr();
11251   }
11252 
11253   QualType ElementType = Element->getType();
11254   ExprResult ElementResult(Element);
11255   if (ElementType->getAs<ObjCObjectPointerType>() &&
11256       S.CheckSingleAssignmentConstraints(TargetElementType,
11257                                          ElementResult,
11258                                          false, false)
11259         != Sema::Compatible) {
11260     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11261         << ElementType << ElementKind << TargetElementType
11262         << Element->getSourceRange();
11263   }
11264 
11265   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11266     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11267   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11268     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11269 }
11270 
11271 /// Check an Objective-C array literal being converted to the given
11272 /// target type.
11273 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11274                                   ObjCArrayLiteral *ArrayLiteral) {
11275   if (!S.NSArrayDecl)
11276     return;
11277 
11278   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11279   if (!TargetObjCPtr)
11280     return;
11281 
11282   if (TargetObjCPtr->isUnspecialized() ||
11283       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11284         != S.NSArrayDecl->getCanonicalDecl())
11285     return;
11286 
11287   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11288   if (TypeArgs.size() != 1)
11289     return;
11290 
11291   QualType TargetElementType = TypeArgs[0];
11292   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11293     checkObjCCollectionLiteralElement(S, TargetElementType,
11294                                       ArrayLiteral->getElement(I),
11295                                       0);
11296   }
11297 }
11298 
11299 /// Check an Objective-C dictionary literal being converted to the given
11300 /// target type.
11301 static void
11302 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11303                            ObjCDictionaryLiteral *DictionaryLiteral) {
11304   if (!S.NSDictionaryDecl)
11305     return;
11306 
11307   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11308   if (!TargetObjCPtr)
11309     return;
11310 
11311   if (TargetObjCPtr->isUnspecialized() ||
11312       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11313         != S.NSDictionaryDecl->getCanonicalDecl())
11314     return;
11315 
11316   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11317   if (TypeArgs.size() != 2)
11318     return;
11319 
11320   QualType TargetKeyType = TypeArgs[0];
11321   QualType TargetObjectType = TypeArgs[1];
11322   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11323     auto Element = DictionaryLiteral->getKeyValueElement(I);
11324     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11325     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11326   }
11327 }
11328 
11329 // Helper function to filter out cases for constant width constant conversion.
11330 // Don't warn on char array initialization or for non-decimal values.
11331 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11332                                           SourceLocation CC) {
11333   // If initializing from a constant, and the constant starts with '0',
11334   // then it is a binary, octal, or hexadecimal.  Allow these constants
11335   // to fill all the bits, even if there is a sign change.
11336   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11337     const char FirstLiteralCharacter =
11338         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11339     if (FirstLiteralCharacter == '0')
11340       return false;
11341   }
11342 
11343   // If the CC location points to a '{', and the type is char, then assume
11344   // assume it is an array initialization.
11345   if (CC.isValid() && T->isCharType()) {
11346     const char FirstContextCharacter =
11347         S.getSourceManager().getCharacterData(CC)[0];
11348     if (FirstContextCharacter == '{')
11349       return false;
11350   }
11351 
11352   return true;
11353 }
11354 
11355 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11356   const auto *IL = dyn_cast<IntegerLiteral>(E);
11357   if (!IL) {
11358     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11359       if (UO->getOpcode() == UO_Minus)
11360         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11361     }
11362   }
11363 
11364   return IL;
11365 }
11366 
11367 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11368   E = E->IgnoreParenImpCasts();
11369   SourceLocation ExprLoc = E->getExprLoc();
11370 
11371   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11372     BinaryOperator::Opcode Opc = BO->getOpcode();
11373     Expr::EvalResult Result;
11374     // Do not diagnose unsigned shifts.
11375     if (Opc == BO_Shl) {
11376       const auto *LHS = getIntegerLiteral(BO->getLHS());
11377       const auto *RHS = getIntegerLiteral(BO->getRHS());
11378       if (LHS && LHS->getValue() == 0)
11379         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11380       else if (!E->isValueDependent() && LHS && RHS &&
11381                RHS->getValue().isNonNegative() &&
11382                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11383         S.Diag(ExprLoc, diag::warn_left_shift_always)
11384             << (Result.Val.getInt() != 0);
11385       else if (E->getType()->isSignedIntegerType())
11386         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11387     }
11388   }
11389 
11390   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11391     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11392     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11393     if (!LHS || !RHS)
11394       return;
11395     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11396         (RHS->getValue() == 0 || RHS->getValue() == 1))
11397       // Do not diagnose common idioms.
11398       return;
11399     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11400       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11401   }
11402 }
11403 
11404 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11405                                     SourceLocation CC,
11406                                     bool *ICContext = nullptr,
11407                                     bool IsListInit = false) {
11408   if (E->isTypeDependent() || E->isValueDependent()) return;
11409 
11410   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11411   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11412   if (Source == Target) return;
11413   if (Target->isDependentType()) return;
11414 
11415   // If the conversion context location is invalid don't complain. We also
11416   // don't want to emit a warning if the issue occurs from the expansion of
11417   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11418   // delay this check as long as possible. Once we detect we are in that
11419   // scenario, we just return.
11420   if (CC.isInvalid())
11421     return;
11422 
11423   if (Source->isAtomicType())
11424     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11425 
11426   // Diagnose implicit casts to bool.
11427   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11428     if (isa<StringLiteral>(E))
11429       // Warn on string literal to bool.  Checks for string literals in logical
11430       // and expressions, for instance, assert(0 && "error here"), are
11431       // prevented by a check in AnalyzeImplicitConversions().
11432       return DiagnoseImpCast(S, E, T, CC,
11433                              diag::warn_impcast_string_literal_to_bool);
11434     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11435         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11436       // This covers the literal expressions that evaluate to Objective-C
11437       // objects.
11438       return DiagnoseImpCast(S, E, T, CC,
11439                              diag::warn_impcast_objective_c_literal_to_bool);
11440     }
11441     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11442       // Warn on pointer to bool conversion that is always true.
11443       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11444                                      SourceRange(CC));
11445     }
11446   }
11447 
11448   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11449   // is a typedef for signed char (macOS), then that constant value has to be 1
11450   // or 0.
11451   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11452     Expr::EvalResult Result;
11453     if (E->EvaluateAsInt(Result, S.getASTContext(),
11454                          Expr::SE_AllowSideEffects)) {
11455       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11456         adornObjCBoolConversionDiagWithTernaryFixit(
11457             S, E,
11458             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11459                 << Result.Val.getInt().toString(10));
11460       }
11461       return;
11462     }
11463   }
11464 
11465   // Check implicit casts from Objective-C collection literals to specialized
11466   // collection types, e.g., NSArray<NSString *> *.
11467   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11468     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11469   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11470     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11471 
11472   // Strip vector types.
11473   if (isa<VectorType>(Source)) {
11474     if (!isa<VectorType>(Target)) {
11475       if (S.SourceMgr.isInSystemMacro(CC))
11476         return;
11477       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11478     }
11479 
11480     // If the vector cast is cast between two vectors of the same size, it is
11481     // a bitcast, not a conversion.
11482     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11483       return;
11484 
11485     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11486     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11487   }
11488   if (auto VecTy = dyn_cast<VectorType>(Target))
11489     Target = VecTy->getElementType().getTypePtr();
11490 
11491   // Strip complex types.
11492   if (isa<ComplexType>(Source)) {
11493     if (!isa<ComplexType>(Target)) {
11494       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11495         return;
11496 
11497       return DiagnoseImpCast(S, E, T, CC,
11498                              S.getLangOpts().CPlusPlus
11499                                  ? diag::err_impcast_complex_scalar
11500                                  : diag::warn_impcast_complex_scalar);
11501     }
11502 
11503     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11504     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11505   }
11506 
11507   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11508   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11509 
11510   // If the source is floating point...
11511   if (SourceBT && SourceBT->isFloatingPoint()) {
11512     // ...and the target is floating point...
11513     if (TargetBT && TargetBT->isFloatingPoint()) {
11514       // ...then warn if we're dropping FP rank.
11515 
11516       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11517           QualType(SourceBT, 0), QualType(TargetBT, 0));
11518       if (Order > 0) {
11519         // Don't warn about float constants that are precisely
11520         // representable in the target type.
11521         Expr::EvalResult result;
11522         if (E->EvaluateAsRValue(result, S.Context)) {
11523           // Value might be a float, a float vector, or a float complex.
11524           if (IsSameFloatAfterCast(result.Val,
11525                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11526                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11527             return;
11528         }
11529 
11530         if (S.SourceMgr.isInSystemMacro(CC))
11531           return;
11532 
11533         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11534       }
11535       // ... or possibly if we're increasing rank, too
11536       else if (Order < 0) {
11537         if (S.SourceMgr.isInSystemMacro(CC))
11538           return;
11539 
11540         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11541       }
11542       return;
11543     }
11544 
11545     // If the target is integral, always warn.
11546     if (TargetBT && TargetBT->isInteger()) {
11547       if (S.SourceMgr.isInSystemMacro(CC))
11548         return;
11549 
11550       DiagnoseFloatingImpCast(S, E, T, CC);
11551     }
11552 
11553     // Detect the case where a call result is converted from floating-point to
11554     // to bool, and the final argument to the call is converted from bool, to
11555     // discover this typo:
11556     //
11557     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11558     //
11559     // FIXME: This is an incredibly special case; is there some more general
11560     // way to detect this class of misplaced-parentheses bug?
11561     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11562       // Check last argument of function call to see if it is an
11563       // implicit cast from a type matching the type the result
11564       // is being cast to.
11565       CallExpr *CEx = cast<CallExpr>(E);
11566       if (unsigned NumArgs = CEx->getNumArgs()) {
11567         Expr *LastA = CEx->getArg(NumArgs - 1);
11568         Expr *InnerE = LastA->IgnoreParenImpCasts();
11569         if (isa<ImplicitCastExpr>(LastA) &&
11570             InnerE->getType()->isBooleanType()) {
11571           // Warn on this floating-point to bool conversion
11572           DiagnoseImpCast(S, E, T, CC,
11573                           diag::warn_impcast_floating_point_to_bool);
11574         }
11575       }
11576     }
11577     return;
11578   }
11579 
11580   // Valid casts involving fixed point types should be accounted for here.
11581   if (Source->isFixedPointType()) {
11582     if (Target->isUnsaturatedFixedPointType()) {
11583       Expr::EvalResult Result;
11584       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11585                                   S.isConstantEvaluated())) {
11586         APFixedPoint Value = Result.Val.getFixedPoint();
11587         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11588         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11589         if (Value > MaxVal || Value < MinVal) {
11590           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11591                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11592                                     << Value.toString() << T
11593                                     << E->getSourceRange()
11594                                     << clang::SourceRange(CC));
11595           return;
11596         }
11597       }
11598     } else if (Target->isIntegerType()) {
11599       Expr::EvalResult Result;
11600       if (!S.isConstantEvaluated() &&
11601           E->EvaluateAsFixedPoint(Result, S.Context,
11602                                   Expr::SE_AllowSideEffects)) {
11603         APFixedPoint FXResult = Result.Val.getFixedPoint();
11604 
11605         bool Overflowed;
11606         llvm::APSInt IntResult = FXResult.convertToInt(
11607             S.Context.getIntWidth(T),
11608             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11609 
11610         if (Overflowed) {
11611           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11612                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11613                                     << FXResult.toString() << T
11614                                     << E->getSourceRange()
11615                                     << clang::SourceRange(CC));
11616           return;
11617         }
11618       }
11619     }
11620   } else if (Target->isUnsaturatedFixedPointType()) {
11621     if (Source->isIntegerType()) {
11622       Expr::EvalResult Result;
11623       if (!S.isConstantEvaluated() &&
11624           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11625         llvm::APSInt Value = Result.Val.getInt();
11626 
11627         bool Overflowed;
11628         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11629             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11630 
11631         if (Overflowed) {
11632           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11633                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11634                                     << Value.toString(/*Radix=*/10) << T
11635                                     << E->getSourceRange()
11636                                     << clang::SourceRange(CC));
11637           return;
11638         }
11639       }
11640     }
11641   }
11642 
11643   // If we are casting an integer type to a floating point type without
11644   // initialization-list syntax, we might lose accuracy if the floating
11645   // point type has a narrower significand than the integer type.
11646   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11647       TargetBT->isFloatingType() && !IsListInit) {
11648     // Determine the number of precision bits in the source integer type.
11649     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11650     unsigned int SourcePrecision = SourceRange.Width;
11651 
11652     // Determine the number of precision bits in the
11653     // target floating point type.
11654     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11655         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11656 
11657     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11658         SourcePrecision > TargetPrecision) {
11659 
11660       llvm::APSInt SourceInt;
11661       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11662         // If the source integer is a constant, convert it to the target
11663         // floating point type. Issue a warning if the value changes
11664         // during the whole conversion.
11665         llvm::APFloat TargetFloatValue(
11666             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11667         llvm::APFloat::opStatus ConversionStatus =
11668             TargetFloatValue.convertFromAPInt(
11669                 SourceInt, SourceBT->isSignedInteger(),
11670                 llvm::APFloat::rmNearestTiesToEven);
11671 
11672         if (ConversionStatus != llvm::APFloat::opOK) {
11673           std::string PrettySourceValue = SourceInt.toString(10);
11674           SmallString<32> PrettyTargetValue;
11675           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11676 
11677           S.DiagRuntimeBehavior(
11678               E->getExprLoc(), E,
11679               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11680                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11681                   << E->getSourceRange() << clang::SourceRange(CC));
11682         }
11683       } else {
11684         // Otherwise, the implicit conversion may lose precision.
11685         DiagnoseImpCast(S, E, T, CC,
11686                         diag::warn_impcast_integer_float_precision);
11687       }
11688     }
11689   }
11690 
11691   DiagnoseNullConversion(S, E, T, CC);
11692 
11693   S.DiscardMisalignedMemberAddress(Target, E);
11694 
11695   if (Target->isBooleanType())
11696     DiagnoseIntInBoolContext(S, E);
11697 
11698   if (!Source->isIntegerType() || !Target->isIntegerType())
11699     return;
11700 
11701   // TODO: remove this early return once the false positives for constant->bool
11702   // in templates, macros, etc, are reduced or removed.
11703   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11704     return;
11705 
11706   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11707       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11708     return adornObjCBoolConversionDiagWithTernaryFixit(
11709         S, E,
11710         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11711             << E->getType());
11712   }
11713 
11714   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11715   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11716 
11717   if (SourceRange.Width > TargetRange.Width) {
11718     // If the source is a constant, use a default-on diagnostic.
11719     // TODO: this should happen for bitfield stores, too.
11720     Expr::EvalResult Result;
11721     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11722                          S.isConstantEvaluated())) {
11723       llvm::APSInt Value(32);
11724       Value = Result.Val.getInt();
11725 
11726       if (S.SourceMgr.isInSystemMacro(CC))
11727         return;
11728 
11729       std::string PrettySourceValue = Value.toString(10);
11730       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11731 
11732       S.DiagRuntimeBehavior(
11733           E->getExprLoc(), E,
11734           S.PDiag(diag::warn_impcast_integer_precision_constant)
11735               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11736               << E->getSourceRange() << clang::SourceRange(CC));
11737       return;
11738     }
11739 
11740     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11741     if (S.SourceMgr.isInSystemMacro(CC))
11742       return;
11743 
11744     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11745       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11746                              /* pruneControlFlow */ true);
11747     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11748   }
11749 
11750   if (TargetRange.Width > SourceRange.Width) {
11751     if (auto *UO = dyn_cast<UnaryOperator>(E))
11752       if (UO->getOpcode() == UO_Minus)
11753         if (Source->isUnsignedIntegerType()) {
11754           if (Target->isUnsignedIntegerType())
11755             return DiagnoseImpCast(S, E, T, CC,
11756                                    diag::warn_impcast_high_order_zero_bits);
11757           if (Target->isSignedIntegerType())
11758             return DiagnoseImpCast(S, E, T, CC,
11759                                    diag::warn_impcast_nonnegative_result);
11760         }
11761   }
11762 
11763   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11764       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11765     // Warn when doing a signed to signed conversion, warn if the positive
11766     // source value is exactly the width of the target type, which will
11767     // cause a negative value to be stored.
11768 
11769     Expr::EvalResult Result;
11770     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11771         !S.SourceMgr.isInSystemMacro(CC)) {
11772       llvm::APSInt Value = Result.Val.getInt();
11773       if (isSameWidthConstantConversion(S, E, T, CC)) {
11774         std::string PrettySourceValue = Value.toString(10);
11775         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11776 
11777         S.DiagRuntimeBehavior(
11778             E->getExprLoc(), E,
11779             S.PDiag(diag::warn_impcast_integer_precision_constant)
11780                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11781                 << E->getSourceRange() << clang::SourceRange(CC));
11782         return;
11783       }
11784     }
11785 
11786     // Fall through for non-constants to give a sign conversion warning.
11787   }
11788 
11789   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11790       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11791        SourceRange.Width == TargetRange.Width)) {
11792     if (S.SourceMgr.isInSystemMacro(CC))
11793       return;
11794 
11795     unsigned DiagID = diag::warn_impcast_integer_sign;
11796 
11797     // Traditionally, gcc has warned about this under -Wsign-compare.
11798     // We also want to warn about it in -Wconversion.
11799     // So if -Wconversion is off, use a completely identical diagnostic
11800     // in the sign-compare group.
11801     // The conditional-checking code will
11802     if (ICContext) {
11803       DiagID = diag::warn_impcast_integer_sign_conditional;
11804       *ICContext = true;
11805     }
11806 
11807     return DiagnoseImpCast(S, E, T, CC, DiagID);
11808   }
11809 
11810   // Diagnose conversions between different enumeration types.
11811   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11812   // type, to give us better diagnostics.
11813   QualType SourceType = E->getType();
11814   if (!S.getLangOpts().CPlusPlus) {
11815     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11816       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11817         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11818         SourceType = S.Context.getTypeDeclType(Enum);
11819         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11820       }
11821   }
11822 
11823   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11824     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11825       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11826           TargetEnum->getDecl()->hasNameForLinkage() &&
11827           SourceEnum != TargetEnum) {
11828         if (S.SourceMgr.isInSystemMacro(CC))
11829           return;
11830 
11831         return DiagnoseImpCast(S, E, SourceType, T, CC,
11832                                diag::warn_impcast_different_enum_types);
11833       }
11834 }
11835 
11836 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11837                                      SourceLocation CC, QualType T);
11838 
11839 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11840                                     SourceLocation CC, bool &ICContext) {
11841   E = E->IgnoreParenImpCasts();
11842 
11843   if (isa<ConditionalOperator>(E))
11844     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11845 
11846   AnalyzeImplicitConversions(S, E, CC);
11847   if (E->getType() != T)
11848     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11849 }
11850 
11851 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11852                                      SourceLocation CC, QualType T) {
11853   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11854 
11855   bool Suspicious = false;
11856   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11857   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11858 
11859   if (T->isBooleanType())
11860     DiagnoseIntInBoolContext(S, E);
11861 
11862   // If -Wconversion would have warned about either of the candidates
11863   // for a signedness conversion to the context type...
11864   if (!Suspicious) return;
11865 
11866   // ...but it's currently ignored...
11867   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11868     return;
11869 
11870   // ...then check whether it would have warned about either of the
11871   // candidates for a signedness conversion to the condition type.
11872   if (E->getType() == T) return;
11873 
11874   Suspicious = false;
11875   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11876                           E->getType(), CC, &Suspicious);
11877   if (!Suspicious)
11878     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11879                             E->getType(), CC, &Suspicious);
11880 }
11881 
11882 /// Check conversion of given expression to boolean.
11883 /// Input argument E is a logical expression.
11884 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11885   if (S.getLangOpts().Bool)
11886     return;
11887   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11888     return;
11889   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11890 }
11891 
11892 namespace {
11893 struct AnalyzeImplicitConversionsWorkItem {
11894   Expr *E;
11895   SourceLocation CC;
11896   bool IsListInit;
11897 };
11898 }
11899 
11900 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
11901 /// that should be visited are added to WorkList.
11902 static void AnalyzeImplicitConversions(
11903     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
11904     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
11905   Expr *OrigE = Item.E;
11906   SourceLocation CC = Item.CC;
11907 
11908   QualType T = OrigE->getType();
11909   Expr *E = OrigE->IgnoreParenImpCasts();
11910 
11911   // Propagate whether we are in a C++ list initialization expression.
11912   // If so, we do not issue warnings for implicit int-float conversion
11913   // precision loss, because C++11 narrowing already handles it.
11914   bool IsListInit = Item.IsListInit ||
11915                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11916 
11917   if (E->isTypeDependent() || E->isValueDependent())
11918     return;
11919 
11920   Expr *SourceExpr = E;
11921   // Examine, but don't traverse into the source expression of an
11922   // OpaqueValueExpr, since it may have multiple parents and we don't want to
11923   // emit duplicate diagnostics. Its fine to examine the form or attempt to
11924   // evaluate it in the context of checking the specific conversion to T though.
11925   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11926     if (auto *Src = OVE->getSourceExpr())
11927       SourceExpr = Src;
11928 
11929   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
11930     if (UO->getOpcode() == UO_Not &&
11931         UO->getSubExpr()->isKnownToHaveBooleanValue())
11932       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11933           << OrigE->getSourceRange() << T->isBooleanType()
11934           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11935 
11936   // For conditional operators, we analyze the arguments as if they
11937   // were being fed directly into the output.
11938   if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) {
11939     CheckConditionalOperator(S, CO, CC, T);
11940     return;
11941   }
11942 
11943   // Check implicit argument conversions for function calls.
11944   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
11945     CheckImplicitArgumentConversions(S, Call, CC);
11946 
11947   // Go ahead and check any implicit conversions we might have skipped.
11948   // The non-canonical typecheck is just an optimization;
11949   // CheckImplicitConversion will filter out dead implicit conversions.
11950   if (SourceExpr->getType() != T)
11951     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
11952 
11953   // Now continue drilling into this expression.
11954 
11955   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11956     // The bound subexpressions in a PseudoObjectExpr are not reachable
11957     // as transitive children.
11958     // FIXME: Use a more uniform representation for this.
11959     for (auto *SE : POE->semantics())
11960       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11961         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
11962   }
11963 
11964   // Skip past explicit casts.
11965   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11966     E = CE->getSubExpr()->IgnoreParenImpCasts();
11967     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11968       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11969     WorkList.push_back({E, CC, IsListInit});
11970     return;
11971   }
11972 
11973   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11974     // Do a somewhat different check with comparison operators.
11975     if (BO->isComparisonOp())
11976       return AnalyzeComparison(S, BO);
11977 
11978     // And with simple assignments.
11979     if (BO->getOpcode() == BO_Assign)
11980       return AnalyzeAssignment(S, BO);
11981     // And with compound assignments.
11982     if (BO->isAssignmentOp())
11983       return AnalyzeCompoundAssignment(S, BO);
11984   }
11985 
11986   // These break the otherwise-useful invariant below.  Fortunately,
11987   // we don't really need to recurse into them, because any internal
11988   // expressions should have been analyzed already when they were
11989   // built into statements.
11990   if (isa<StmtExpr>(E)) return;
11991 
11992   // Don't descend into unevaluated contexts.
11993   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11994 
11995   // Now just recurse over the expression's children.
11996   CC = E->getExprLoc();
11997   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11998   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11999   for (Stmt *SubStmt : E->children()) {
12000     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12001     if (!ChildExpr)
12002       continue;
12003 
12004     if (IsLogicalAndOperator &&
12005         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12006       // Ignore checking string literals that are in logical and operators.
12007       // This is a common pattern for asserts.
12008       continue;
12009     WorkList.push_back({ChildExpr, CC, IsListInit});
12010   }
12011 
12012   if (BO && BO->isLogicalOp()) {
12013     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12014     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12015       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12016 
12017     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12018     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12019       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12020   }
12021 
12022   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12023     if (U->getOpcode() == UO_LNot) {
12024       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12025     } else if (U->getOpcode() != UO_AddrOf) {
12026       if (U->getSubExpr()->getType()->isAtomicType())
12027         S.Diag(U->getSubExpr()->getBeginLoc(),
12028                diag::warn_atomic_implicit_seq_cst);
12029     }
12030   }
12031 }
12032 
12033 /// AnalyzeImplicitConversions - Find and report any interesting
12034 /// implicit conversions in the given expression.  There are a couple
12035 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12036 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12037                                        bool IsListInit/*= false*/) {
12038   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12039   WorkList.push_back({OrigE, CC, IsListInit});
12040   while (!WorkList.empty())
12041     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12042 }
12043 
12044 /// Diagnose integer type and any valid implicit conversion to it.
12045 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12046   // Taking into account implicit conversions,
12047   // allow any integer.
12048   if (!E->getType()->isIntegerType()) {
12049     S.Diag(E->getBeginLoc(),
12050            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12051     return true;
12052   }
12053   // Potentially emit standard warnings for implicit conversions if enabled
12054   // using -Wconversion.
12055   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12056   return false;
12057 }
12058 
12059 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12060 // Returns true when emitting a warning about taking the address of a reference.
12061 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12062                               const PartialDiagnostic &PD) {
12063   E = E->IgnoreParenImpCasts();
12064 
12065   const FunctionDecl *FD = nullptr;
12066 
12067   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12068     if (!DRE->getDecl()->getType()->isReferenceType())
12069       return false;
12070   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12071     if (!M->getMemberDecl()->getType()->isReferenceType())
12072       return false;
12073   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12074     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12075       return false;
12076     FD = Call->getDirectCallee();
12077   } else {
12078     return false;
12079   }
12080 
12081   SemaRef.Diag(E->getExprLoc(), PD);
12082 
12083   // If possible, point to location of function.
12084   if (FD) {
12085     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12086   }
12087 
12088   return true;
12089 }
12090 
12091 // Returns true if the SourceLocation is expanded from any macro body.
12092 // Returns false if the SourceLocation is invalid, is from not in a macro
12093 // expansion, or is from expanded from a top-level macro argument.
12094 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12095   if (Loc.isInvalid())
12096     return false;
12097 
12098   while (Loc.isMacroID()) {
12099     if (SM.isMacroBodyExpansion(Loc))
12100       return true;
12101     Loc = SM.getImmediateMacroCallerLoc(Loc);
12102   }
12103 
12104   return false;
12105 }
12106 
12107 /// Diagnose pointers that are always non-null.
12108 /// \param E the expression containing the pointer
12109 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12110 /// compared to a null pointer
12111 /// \param IsEqual True when the comparison is equal to a null pointer
12112 /// \param Range Extra SourceRange to highlight in the diagnostic
12113 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12114                                         Expr::NullPointerConstantKind NullKind,
12115                                         bool IsEqual, SourceRange Range) {
12116   if (!E)
12117     return;
12118 
12119   // Don't warn inside macros.
12120   if (E->getExprLoc().isMacroID()) {
12121     const SourceManager &SM = getSourceManager();
12122     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12123         IsInAnyMacroBody(SM, Range.getBegin()))
12124       return;
12125   }
12126   E = E->IgnoreImpCasts();
12127 
12128   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12129 
12130   if (isa<CXXThisExpr>(E)) {
12131     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12132                                 : diag::warn_this_bool_conversion;
12133     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12134     return;
12135   }
12136 
12137   bool IsAddressOf = false;
12138 
12139   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12140     if (UO->getOpcode() != UO_AddrOf)
12141       return;
12142     IsAddressOf = true;
12143     E = UO->getSubExpr();
12144   }
12145 
12146   if (IsAddressOf) {
12147     unsigned DiagID = IsCompare
12148                           ? diag::warn_address_of_reference_null_compare
12149                           : diag::warn_address_of_reference_bool_conversion;
12150     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12151                                          << IsEqual;
12152     if (CheckForReference(*this, E, PD)) {
12153       return;
12154     }
12155   }
12156 
12157   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12158     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12159     std::string Str;
12160     llvm::raw_string_ostream S(Str);
12161     E->printPretty(S, nullptr, getPrintingPolicy());
12162     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12163                                 : diag::warn_cast_nonnull_to_bool;
12164     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12165       << E->getSourceRange() << Range << IsEqual;
12166     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12167   };
12168 
12169   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12170   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12171     if (auto *Callee = Call->getDirectCallee()) {
12172       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12173         ComplainAboutNonnullParamOrCall(A);
12174         return;
12175       }
12176     }
12177   }
12178 
12179   // Expect to find a single Decl.  Skip anything more complicated.
12180   ValueDecl *D = nullptr;
12181   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12182     D = R->getDecl();
12183   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12184     D = M->getMemberDecl();
12185   }
12186 
12187   // Weak Decls can be null.
12188   if (!D || D->isWeak())
12189     return;
12190 
12191   // Check for parameter decl with nonnull attribute
12192   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12193     if (getCurFunction() &&
12194         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12195       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12196         ComplainAboutNonnullParamOrCall(A);
12197         return;
12198       }
12199 
12200       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12201         // Skip function template not specialized yet.
12202         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12203           return;
12204         auto ParamIter = llvm::find(FD->parameters(), PV);
12205         assert(ParamIter != FD->param_end());
12206         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12207 
12208         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12209           if (!NonNull->args_size()) {
12210               ComplainAboutNonnullParamOrCall(NonNull);
12211               return;
12212           }
12213 
12214           for (const ParamIdx &ArgNo : NonNull->args()) {
12215             if (ArgNo.getASTIndex() == ParamNo) {
12216               ComplainAboutNonnullParamOrCall(NonNull);
12217               return;
12218             }
12219           }
12220         }
12221       }
12222     }
12223   }
12224 
12225   QualType T = D->getType();
12226   const bool IsArray = T->isArrayType();
12227   const bool IsFunction = T->isFunctionType();
12228 
12229   // Address of function is used to silence the function warning.
12230   if (IsAddressOf && IsFunction) {
12231     return;
12232   }
12233 
12234   // Found nothing.
12235   if (!IsAddressOf && !IsFunction && !IsArray)
12236     return;
12237 
12238   // Pretty print the expression for the diagnostic.
12239   std::string Str;
12240   llvm::raw_string_ostream S(Str);
12241   E->printPretty(S, nullptr, getPrintingPolicy());
12242 
12243   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12244                               : diag::warn_impcast_pointer_to_bool;
12245   enum {
12246     AddressOf,
12247     FunctionPointer,
12248     ArrayPointer
12249   } DiagType;
12250   if (IsAddressOf)
12251     DiagType = AddressOf;
12252   else if (IsFunction)
12253     DiagType = FunctionPointer;
12254   else if (IsArray)
12255     DiagType = ArrayPointer;
12256   else
12257     llvm_unreachable("Could not determine diagnostic.");
12258   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12259                                 << Range << IsEqual;
12260 
12261   if (!IsFunction)
12262     return;
12263 
12264   // Suggest '&' to silence the function warning.
12265   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12266       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12267 
12268   // Check to see if '()' fixit should be emitted.
12269   QualType ReturnType;
12270   UnresolvedSet<4> NonTemplateOverloads;
12271   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12272   if (ReturnType.isNull())
12273     return;
12274 
12275   if (IsCompare) {
12276     // There are two cases here.  If there is null constant, the only suggest
12277     // for a pointer return type.  If the null is 0, then suggest if the return
12278     // type is a pointer or an integer type.
12279     if (!ReturnType->isPointerType()) {
12280       if (NullKind == Expr::NPCK_ZeroExpression ||
12281           NullKind == Expr::NPCK_ZeroLiteral) {
12282         if (!ReturnType->isIntegerType())
12283           return;
12284       } else {
12285         return;
12286       }
12287     }
12288   } else { // !IsCompare
12289     // For function to bool, only suggest if the function pointer has bool
12290     // return type.
12291     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12292       return;
12293   }
12294   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12295       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12296 }
12297 
12298 /// Diagnoses "dangerous" implicit conversions within the given
12299 /// expression (which is a full expression).  Implements -Wconversion
12300 /// and -Wsign-compare.
12301 ///
12302 /// \param CC the "context" location of the implicit conversion, i.e.
12303 ///   the most location of the syntactic entity requiring the implicit
12304 ///   conversion
12305 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12306   // Don't diagnose in unevaluated contexts.
12307   if (isUnevaluatedContext())
12308     return;
12309 
12310   // Don't diagnose for value- or type-dependent expressions.
12311   if (E->isTypeDependent() || E->isValueDependent())
12312     return;
12313 
12314   // Check for array bounds violations in cases where the check isn't triggered
12315   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12316   // ArraySubscriptExpr is on the RHS of a variable initialization.
12317   CheckArrayAccess(E);
12318 
12319   // This is not the right CC for (e.g.) a variable initialization.
12320   AnalyzeImplicitConversions(*this, E, CC);
12321 }
12322 
12323 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12324 /// Input argument E is a logical expression.
12325 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12326   ::CheckBoolLikeConversion(*this, E, CC);
12327 }
12328 
12329 /// Diagnose when expression is an integer constant expression and its evaluation
12330 /// results in integer overflow
12331 void Sema::CheckForIntOverflow (Expr *E) {
12332   // Use a work list to deal with nested struct initializers.
12333   SmallVector<Expr *, 2> Exprs(1, E);
12334 
12335   do {
12336     Expr *OriginalE = Exprs.pop_back_val();
12337     Expr *E = OriginalE->IgnoreParenCasts();
12338 
12339     if (isa<BinaryOperator>(E)) {
12340       E->EvaluateForOverflow(Context);
12341       continue;
12342     }
12343 
12344     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12345       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12346     else if (isa<ObjCBoxedExpr>(OriginalE))
12347       E->EvaluateForOverflow(Context);
12348     else if (auto Call = dyn_cast<CallExpr>(E))
12349       Exprs.append(Call->arg_begin(), Call->arg_end());
12350     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12351       Exprs.append(Message->arg_begin(), Message->arg_end());
12352   } while (!Exprs.empty());
12353 }
12354 
12355 namespace {
12356 
12357 /// Visitor for expressions which looks for unsequenced operations on the
12358 /// same object.
12359 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12360   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12361 
12362   /// A tree of sequenced regions within an expression. Two regions are
12363   /// unsequenced if one is an ancestor or a descendent of the other. When we
12364   /// finish processing an expression with sequencing, such as a comma
12365   /// expression, we fold its tree nodes into its parent, since they are
12366   /// unsequenced with respect to nodes we will visit later.
12367   class SequenceTree {
12368     struct Value {
12369       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12370       unsigned Parent : 31;
12371       unsigned Merged : 1;
12372     };
12373     SmallVector<Value, 8> Values;
12374 
12375   public:
12376     /// A region within an expression which may be sequenced with respect
12377     /// to some other region.
12378     class Seq {
12379       friend class SequenceTree;
12380 
12381       unsigned Index;
12382 
12383       explicit Seq(unsigned N) : Index(N) {}
12384 
12385     public:
12386       Seq() : Index(0) {}
12387     };
12388 
12389     SequenceTree() { Values.push_back(Value(0)); }
12390     Seq root() const { return Seq(0); }
12391 
12392     /// Create a new sequence of operations, which is an unsequenced
12393     /// subset of \p Parent. This sequence of operations is sequenced with
12394     /// respect to other children of \p Parent.
12395     Seq allocate(Seq Parent) {
12396       Values.push_back(Value(Parent.Index));
12397       return Seq(Values.size() - 1);
12398     }
12399 
12400     /// Merge a sequence of operations into its parent.
12401     void merge(Seq S) {
12402       Values[S.Index].Merged = true;
12403     }
12404 
12405     /// Determine whether two operations are unsequenced. This operation
12406     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12407     /// should have been merged into its parent as appropriate.
12408     bool isUnsequenced(Seq Cur, Seq Old) {
12409       unsigned C = representative(Cur.Index);
12410       unsigned Target = representative(Old.Index);
12411       while (C >= Target) {
12412         if (C == Target)
12413           return true;
12414         C = Values[C].Parent;
12415       }
12416       return false;
12417     }
12418 
12419   private:
12420     /// Pick a representative for a sequence.
12421     unsigned representative(unsigned K) {
12422       if (Values[K].Merged)
12423         // Perform path compression as we go.
12424         return Values[K].Parent = representative(Values[K].Parent);
12425       return K;
12426     }
12427   };
12428 
12429   /// An object for which we can track unsequenced uses.
12430   using Object = const NamedDecl *;
12431 
12432   /// Different flavors of object usage which we track. We only track the
12433   /// least-sequenced usage of each kind.
12434   enum UsageKind {
12435     /// A read of an object. Multiple unsequenced reads are OK.
12436     UK_Use,
12437 
12438     /// A modification of an object which is sequenced before the value
12439     /// computation of the expression, such as ++n in C++.
12440     UK_ModAsValue,
12441 
12442     /// A modification of an object which is not sequenced before the value
12443     /// computation of the expression, such as n++.
12444     UK_ModAsSideEffect,
12445 
12446     UK_Count = UK_ModAsSideEffect + 1
12447   };
12448 
12449   /// Bundle together a sequencing region and the expression corresponding
12450   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12451   struct Usage {
12452     const Expr *UsageExpr;
12453     SequenceTree::Seq Seq;
12454 
12455     Usage() : UsageExpr(nullptr), Seq() {}
12456   };
12457 
12458   struct UsageInfo {
12459     Usage Uses[UK_Count];
12460 
12461     /// Have we issued a diagnostic for this object already?
12462     bool Diagnosed;
12463 
12464     UsageInfo() : Uses(), Diagnosed(false) {}
12465   };
12466   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12467 
12468   Sema &SemaRef;
12469 
12470   /// Sequenced regions within the expression.
12471   SequenceTree Tree;
12472 
12473   /// Declaration modifications and references which we have seen.
12474   UsageInfoMap UsageMap;
12475 
12476   /// The region we are currently within.
12477   SequenceTree::Seq Region;
12478 
12479   /// Filled in with declarations which were modified as a side-effect
12480   /// (that is, post-increment operations).
12481   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12482 
12483   /// Expressions to check later. We defer checking these to reduce
12484   /// stack usage.
12485   SmallVectorImpl<const Expr *> &WorkList;
12486 
12487   /// RAII object wrapping the visitation of a sequenced subexpression of an
12488   /// expression. At the end of this process, the side-effects of the evaluation
12489   /// become sequenced with respect to the value computation of the result, so
12490   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12491   /// UK_ModAsValue.
12492   struct SequencedSubexpression {
12493     SequencedSubexpression(SequenceChecker &Self)
12494       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12495       Self.ModAsSideEffect = &ModAsSideEffect;
12496     }
12497 
12498     ~SequencedSubexpression() {
12499       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12500         // Add a new usage with usage kind UK_ModAsValue, and then restore
12501         // the previous usage with UK_ModAsSideEffect (thus clearing it if
12502         // the previous one was empty).
12503         UsageInfo &UI = Self.UsageMap[M.first];
12504         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12505         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12506         SideEffectUsage = M.second;
12507       }
12508       Self.ModAsSideEffect = OldModAsSideEffect;
12509     }
12510 
12511     SequenceChecker &Self;
12512     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12513     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12514   };
12515 
12516   /// RAII object wrapping the visitation of a subexpression which we might
12517   /// choose to evaluate as a constant. If any subexpression is evaluated and
12518   /// found to be non-constant, this allows us to suppress the evaluation of
12519   /// the outer expression.
12520   class EvaluationTracker {
12521   public:
12522     EvaluationTracker(SequenceChecker &Self)
12523         : Self(Self), Prev(Self.EvalTracker) {
12524       Self.EvalTracker = this;
12525     }
12526 
12527     ~EvaluationTracker() {
12528       Self.EvalTracker = Prev;
12529       if (Prev)
12530         Prev->EvalOK &= EvalOK;
12531     }
12532 
12533     bool evaluate(const Expr *E, bool &Result) {
12534       if (!EvalOK || E->isValueDependent())
12535         return false;
12536       EvalOK = E->EvaluateAsBooleanCondition(
12537           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12538       return EvalOK;
12539     }
12540 
12541   private:
12542     SequenceChecker &Self;
12543     EvaluationTracker *Prev;
12544     bool EvalOK = true;
12545   } *EvalTracker = nullptr;
12546 
12547   /// Find the object which is produced by the specified expression,
12548   /// if any.
12549   Object getObject(const Expr *E, bool Mod) const {
12550     E = E->IgnoreParenCasts();
12551     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12552       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12553         return getObject(UO->getSubExpr(), Mod);
12554     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12555       if (BO->getOpcode() == BO_Comma)
12556         return getObject(BO->getRHS(), Mod);
12557       if (Mod && BO->isAssignmentOp())
12558         return getObject(BO->getLHS(), Mod);
12559     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12560       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12561       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12562         return ME->getMemberDecl();
12563     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12564       // FIXME: If this is a reference, map through to its value.
12565       return DRE->getDecl();
12566     return nullptr;
12567   }
12568 
12569   /// Note that an object \p O was modified or used by an expression
12570   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12571   /// the object \p O as obtained via the \p UsageMap.
12572   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12573     // Get the old usage for the given object and usage kind.
12574     Usage &U = UI.Uses[UK];
12575     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12576       // If we have a modification as side effect and are in a sequenced
12577       // subexpression, save the old Usage so that we can restore it later
12578       // in SequencedSubexpression::~SequencedSubexpression.
12579       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12580         ModAsSideEffect->push_back(std::make_pair(O, U));
12581       // Then record the new usage with the current sequencing region.
12582       U.UsageExpr = UsageExpr;
12583       U.Seq = Region;
12584     }
12585   }
12586 
12587   /// Check whether a modification or use of an object \p O in an expression
12588   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12589   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12590   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12591   /// usage and false we are checking for a mod-use unsequenced usage.
12592   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12593                   UsageKind OtherKind, bool IsModMod) {
12594     if (UI.Diagnosed)
12595       return;
12596 
12597     const Usage &U = UI.Uses[OtherKind];
12598     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12599       return;
12600 
12601     const Expr *Mod = U.UsageExpr;
12602     const Expr *ModOrUse = UsageExpr;
12603     if (OtherKind == UK_Use)
12604       std::swap(Mod, ModOrUse);
12605 
12606     SemaRef.DiagRuntimeBehavior(
12607         Mod->getExprLoc(), {Mod, ModOrUse},
12608         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12609                                : diag::warn_unsequenced_mod_use)
12610             << O << SourceRange(ModOrUse->getExprLoc()));
12611     UI.Diagnosed = true;
12612   }
12613 
12614   // A note on note{Pre, Post}{Use, Mod}:
12615   //
12616   // (It helps to follow the algorithm with an expression such as
12617   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12618   //  operations before C++17 and both are well-defined in C++17).
12619   //
12620   // When visiting a node which uses/modify an object we first call notePreUse
12621   // or notePreMod before visiting its sub-expression(s). At this point the
12622   // children of the current node have not yet been visited and so the eventual
12623   // uses/modifications resulting from the children of the current node have not
12624   // been recorded yet.
12625   //
12626   // We then visit the children of the current node. After that notePostUse or
12627   // notePostMod is called. These will 1) detect an unsequenced modification
12628   // as side effect (as in "k++ + k") and 2) add a new usage with the
12629   // appropriate usage kind.
12630   //
12631   // We also have to be careful that some operation sequences modification as
12632   // side effect as well (for example: || or ,). To account for this we wrap
12633   // the visitation of such a sub-expression (for example: the LHS of || or ,)
12634   // with SequencedSubexpression. SequencedSubexpression is an RAII object
12635   // which record usages which are modifications as side effect, and then
12636   // downgrade them (or more accurately restore the previous usage which was a
12637   // modification as side effect) when exiting the scope of the sequenced
12638   // subexpression.
12639 
12640   void notePreUse(Object O, const Expr *UseExpr) {
12641     UsageInfo &UI = UsageMap[O];
12642     // Uses conflict with other modifications.
12643     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12644   }
12645 
12646   void notePostUse(Object O, const Expr *UseExpr) {
12647     UsageInfo &UI = UsageMap[O];
12648     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12649                /*IsModMod=*/false);
12650     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12651   }
12652 
12653   void notePreMod(Object O, const Expr *ModExpr) {
12654     UsageInfo &UI = UsageMap[O];
12655     // Modifications conflict with other modifications and with uses.
12656     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12657     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12658   }
12659 
12660   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12661     UsageInfo &UI = UsageMap[O];
12662     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12663                /*IsModMod=*/true);
12664     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12665   }
12666 
12667 public:
12668   SequenceChecker(Sema &S, const Expr *E,
12669                   SmallVectorImpl<const Expr *> &WorkList)
12670       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12671     Visit(E);
12672     // Silence a -Wunused-private-field since WorkList is now unused.
12673     // TODO: Evaluate if it can be used, and if not remove it.
12674     (void)this->WorkList;
12675   }
12676 
12677   void VisitStmt(const Stmt *S) {
12678     // Skip all statements which aren't expressions for now.
12679   }
12680 
12681   void VisitExpr(const Expr *E) {
12682     // By default, just recurse to evaluated subexpressions.
12683     Base::VisitStmt(E);
12684   }
12685 
12686   void VisitCastExpr(const CastExpr *E) {
12687     Object O = Object();
12688     if (E->getCastKind() == CK_LValueToRValue)
12689       O = getObject(E->getSubExpr(), false);
12690 
12691     if (O)
12692       notePreUse(O, E);
12693     VisitExpr(E);
12694     if (O)
12695       notePostUse(O, E);
12696   }
12697 
12698   void VisitSequencedExpressions(const Expr *SequencedBefore,
12699                                  const Expr *SequencedAfter) {
12700     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12701     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12702     SequenceTree::Seq OldRegion = Region;
12703 
12704     {
12705       SequencedSubexpression SeqBefore(*this);
12706       Region = BeforeRegion;
12707       Visit(SequencedBefore);
12708     }
12709 
12710     Region = AfterRegion;
12711     Visit(SequencedAfter);
12712 
12713     Region = OldRegion;
12714 
12715     Tree.merge(BeforeRegion);
12716     Tree.merge(AfterRegion);
12717   }
12718 
12719   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12720     // C++17 [expr.sub]p1:
12721     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12722     //   expression E1 is sequenced before the expression E2.
12723     if (SemaRef.getLangOpts().CPlusPlus17)
12724       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12725     else {
12726       Visit(ASE->getLHS());
12727       Visit(ASE->getRHS());
12728     }
12729   }
12730 
12731   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12732   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12733   void VisitBinPtrMem(const BinaryOperator *BO) {
12734     // C++17 [expr.mptr.oper]p4:
12735     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12736     //  the expression E1 is sequenced before the expression E2.
12737     if (SemaRef.getLangOpts().CPlusPlus17)
12738       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12739     else {
12740       Visit(BO->getLHS());
12741       Visit(BO->getRHS());
12742     }
12743   }
12744 
12745   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12746   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12747   void VisitBinShlShr(const BinaryOperator *BO) {
12748     // C++17 [expr.shift]p4:
12749     //  The expression E1 is sequenced before the expression E2.
12750     if (SemaRef.getLangOpts().CPlusPlus17)
12751       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12752     else {
12753       Visit(BO->getLHS());
12754       Visit(BO->getRHS());
12755     }
12756   }
12757 
12758   void VisitBinComma(const BinaryOperator *BO) {
12759     // C++11 [expr.comma]p1:
12760     //   Every value computation and side effect associated with the left
12761     //   expression is sequenced before every value computation and side
12762     //   effect associated with the right expression.
12763     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12764   }
12765 
12766   void VisitBinAssign(const BinaryOperator *BO) {
12767     SequenceTree::Seq RHSRegion;
12768     SequenceTree::Seq LHSRegion;
12769     if (SemaRef.getLangOpts().CPlusPlus17) {
12770       RHSRegion = Tree.allocate(Region);
12771       LHSRegion = Tree.allocate(Region);
12772     } else {
12773       RHSRegion = Region;
12774       LHSRegion = Region;
12775     }
12776     SequenceTree::Seq OldRegion = Region;
12777 
12778     // C++11 [expr.ass]p1:
12779     //  [...] the assignment is sequenced after the value computation
12780     //  of the right and left operands, [...]
12781     //
12782     // so check it before inspecting the operands and update the
12783     // map afterwards.
12784     Object O = getObject(BO->getLHS(), /*Mod=*/true);
12785     if (O)
12786       notePreMod(O, BO);
12787 
12788     if (SemaRef.getLangOpts().CPlusPlus17) {
12789       // C++17 [expr.ass]p1:
12790       //  [...] The right operand is sequenced before the left operand. [...]
12791       {
12792         SequencedSubexpression SeqBefore(*this);
12793         Region = RHSRegion;
12794         Visit(BO->getRHS());
12795       }
12796 
12797       Region = LHSRegion;
12798       Visit(BO->getLHS());
12799 
12800       if (O && isa<CompoundAssignOperator>(BO))
12801         notePostUse(O, BO);
12802 
12803     } else {
12804       // C++11 does not specify any sequencing between the LHS and RHS.
12805       Region = LHSRegion;
12806       Visit(BO->getLHS());
12807 
12808       if (O && isa<CompoundAssignOperator>(BO))
12809         notePostUse(O, BO);
12810 
12811       Region = RHSRegion;
12812       Visit(BO->getRHS());
12813     }
12814 
12815     // C++11 [expr.ass]p1:
12816     //  the assignment is sequenced [...] before the value computation of the
12817     //  assignment expression.
12818     // C11 6.5.16/3 has no such rule.
12819     Region = OldRegion;
12820     if (O)
12821       notePostMod(O, BO,
12822                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12823                                                   : UK_ModAsSideEffect);
12824     if (SemaRef.getLangOpts().CPlusPlus17) {
12825       Tree.merge(RHSRegion);
12826       Tree.merge(LHSRegion);
12827     }
12828   }
12829 
12830   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12831     VisitBinAssign(CAO);
12832   }
12833 
12834   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12835   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12836   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12837     Object O = getObject(UO->getSubExpr(), true);
12838     if (!O)
12839       return VisitExpr(UO);
12840 
12841     notePreMod(O, UO);
12842     Visit(UO->getSubExpr());
12843     // C++11 [expr.pre.incr]p1:
12844     //   the expression ++x is equivalent to x+=1
12845     notePostMod(O, UO,
12846                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12847                                                 : UK_ModAsSideEffect);
12848   }
12849 
12850   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12851   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12852   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12853     Object O = getObject(UO->getSubExpr(), true);
12854     if (!O)
12855       return VisitExpr(UO);
12856 
12857     notePreMod(O, UO);
12858     Visit(UO->getSubExpr());
12859     notePostMod(O, UO, UK_ModAsSideEffect);
12860   }
12861 
12862   void VisitBinLOr(const BinaryOperator *BO) {
12863     // C++11 [expr.log.or]p2:
12864     //  If the second expression is evaluated, every value computation and
12865     //  side effect associated with the first expression is sequenced before
12866     //  every value computation and side effect associated with the
12867     //  second expression.
12868     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12869     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12870     SequenceTree::Seq OldRegion = Region;
12871 
12872     EvaluationTracker Eval(*this);
12873     {
12874       SequencedSubexpression Sequenced(*this);
12875       Region = LHSRegion;
12876       Visit(BO->getLHS());
12877     }
12878 
12879     // C++11 [expr.log.or]p1:
12880     //  [...] the second operand is not evaluated if the first operand
12881     //  evaluates to true.
12882     bool EvalResult = false;
12883     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12884     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
12885     if (ShouldVisitRHS) {
12886       Region = RHSRegion;
12887       Visit(BO->getRHS());
12888     }
12889 
12890     Region = OldRegion;
12891     Tree.merge(LHSRegion);
12892     Tree.merge(RHSRegion);
12893   }
12894 
12895   void VisitBinLAnd(const BinaryOperator *BO) {
12896     // C++11 [expr.log.and]p2:
12897     //  If the second expression is evaluated, every value computation and
12898     //  side effect associated with the first expression is sequenced before
12899     //  every value computation and side effect associated with the
12900     //  second expression.
12901     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12902     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12903     SequenceTree::Seq OldRegion = Region;
12904 
12905     EvaluationTracker Eval(*this);
12906     {
12907       SequencedSubexpression Sequenced(*this);
12908       Region = LHSRegion;
12909       Visit(BO->getLHS());
12910     }
12911 
12912     // C++11 [expr.log.and]p1:
12913     //  [...] the second operand is not evaluated if the first operand is false.
12914     bool EvalResult = false;
12915     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12916     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
12917     if (ShouldVisitRHS) {
12918       Region = RHSRegion;
12919       Visit(BO->getRHS());
12920     }
12921 
12922     Region = OldRegion;
12923     Tree.merge(LHSRegion);
12924     Tree.merge(RHSRegion);
12925   }
12926 
12927   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12928     // C++11 [expr.cond]p1:
12929     //  [...] Every value computation and side effect associated with the first
12930     //  expression is sequenced before every value computation and side effect
12931     //  associated with the second or third expression.
12932     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12933 
12934     // No sequencing is specified between the true and false expression.
12935     // However since exactly one of both is going to be evaluated we can
12936     // consider them to be sequenced. This is needed to avoid warning on
12937     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12938     // both the true and false expressions because we can't evaluate x.
12939     // This will still allow us to detect an expression like (pre C++17)
12940     // "(x ? y += 1 : y += 2) = y".
12941     //
12942     // We don't wrap the visitation of the true and false expression with
12943     // SequencedSubexpression because we don't want to downgrade modifications
12944     // as side effect in the true and false expressions after the visition
12945     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12946     // not warn between the two "y++", but we should warn between the "y++"
12947     // and the "y".
12948     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12949     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12950     SequenceTree::Seq OldRegion = Region;
12951 
12952     EvaluationTracker Eval(*this);
12953     {
12954       SequencedSubexpression Sequenced(*this);
12955       Region = ConditionRegion;
12956       Visit(CO->getCond());
12957     }
12958 
12959     // C++11 [expr.cond]p1:
12960     // [...] The first expression is contextually converted to bool (Clause 4).
12961     // It is evaluated and if it is true, the result of the conditional
12962     // expression is the value of the second expression, otherwise that of the
12963     // third expression. Only one of the second and third expressions is
12964     // evaluated. [...]
12965     bool EvalResult = false;
12966     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12967     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
12968     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
12969     if (ShouldVisitTrueExpr) {
12970       Region = TrueRegion;
12971       Visit(CO->getTrueExpr());
12972     }
12973     if (ShouldVisitFalseExpr) {
12974       Region = FalseRegion;
12975       Visit(CO->getFalseExpr());
12976     }
12977 
12978     Region = OldRegion;
12979     Tree.merge(ConditionRegion);
12980     Tree.merge(TrueRegion);
12981     Tree.merge(FalseRegion);
12982   }
12983 
12984   void VisitCallExpr(const CallExpr *CE) {
12985     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12986 
12987     if (CE->isUnevaluatedBuiltinCall(Context))
12988       return;
12989 
12990     // C++11 [intro.execution]p15:
12991     //   When calling a function [...], every value computation and side effect
12992     //   associated with any argument expression, or with the postfix expression
12993     //   designating the called function, is sequenced before execution of every
12994     //   expression or statement in the body of the function [and thus before
12995     //   the value computation of its result].
12996     SequencedSubexpression Sequenced(*this);
12997     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
12998       // C++17 [expr.call]p5
12999       //   The postfix-expression is sequenced before each expression in the
13000       //   expression-list and any default argument. [...]
13001       SequenceTree::Seq CalleeRegion;
13002       SequenceTree::Seq OtherRegion;
13003       if (SemaRef.getLangOpts().CPlusPlus17) {
13004         CalleeRegion = Tree.allocate(Region);
13005         OtherRegion = Tree.allocate(Region);
13006       } else {
13007         CalleeRegion = Region;
13008         OtherRegion = Region;
13009       }
13010       SequenceTree::Seq OldRegion = Region;
13011 
13012       // Visit the callee expression first.
13013       Region = CalleeRegion;
13014       if (SemaRef.getLangOpts().CPlusPlus17) {
13015         SequencedSubexpression Sequenced(*this);
13016         Visit(CE->getCallee());
13017       } else {
13018         Visit(CE->getCallee());
13019       }
13020 
13021       // Then visit the argument expressions.
13022       Region = OtherRegion;
13023       for (const Expr *Argument : CE->arguments())
13024         Visit(Argument);
13025 
13026       Region = OldRegion;
13027       if (SemaRef.getLangOpts().CPlusPlus17) {
13028         Tree.merge(CalleeRegion);
13029         Tree.merge(OtherRegion);
13030       }
13031     });
13032   }
13033 
13034   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13035     // C++17 [over.match.oper]p2:
13036     //   [...] the operator notation is first transformed to the equivalent
13037     //   function-call notation as summarized in Table 12 (where @ denotes one
13038     //   of the operators covered in the specified subclause). However, the
13039     //   operands are sequenced in the order prescribed for the built-in
13040     //   operator (Clause 8).
13041     //
13042     // From the above only overloaded binary operators and overloaded call
13043     // operators have sequencing rules in C++17 that we need to handle
13044     // separately.
13045     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13046         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13047       return VisitCallExpr(CXXOCE);
13048 
13049     enum {
13050       NoSequencing,
13051       LHSBeforeRHS,
13052       RHSBeforeLHS,
13053       LHSBeforeRest
13054     } SequencingKind;
13055     switch (CXXOCE->getOperator()) {
13056     case OO_Equal:
13057     case OO_PlusEqual:
13058     case OO_MinusEqual:
13059     case OO_StarEqual:
13060     case OO_SlashEqual:
13061     case OO_PercentEqual:
13062     case OO_CaretEqual:
13063     case OO_AmpEqual:
13064     case OO_PipeEqual:
13065     case OO_LessLessEqual:
13066     case OO_GreaterGreaterEqual:
13067       SequencingKind = RHSBeforeLHS;
13068       break;
13069 
13070     case OO_LessLess:
13071     case OO_GreaterGreater:
13072     case OO_AmpAmp:
13073     case OO_PipePipe:
13074     case OO_Comma:
13075     case OO_ArrowStar:
13076     case OO_Subscript:
13077       SequencingKind = LHSBeforeRHS;
13078       break;
13079 
13080     case OO_Call:
13081       SequencingKind = LHSBeforeRest;
13082       break;
13083 
13084     default:
13085       SequencingKind = NoSequencing;
13086       break;
13087     }
13088 
13089     if (SequencingKind == NoSequencing)
13090       return VisitCallExpr(CXXOCE);
13091 
13092     // This is a call, so all subexpressions are sequenced before the result.
13093     SequencedSubexpression Sequenced(*this);
13094 
13095     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13096       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13097              "Should only get there with C++17 and above!");
13098       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13099              "Should only get there with an overloaded binary operator"
13100              " or an overloaded call operator!");
13101 
13102       if (SequencingKind == LHSBeforeRest) {
13103         assert(CXXOCE->getOperator() == OO_Call &&
13104                "We should only have an overloaded call operator here!");
13105 
13106         // This is very similar to VisitCallExpr, except that we only have the
13107         // C++17 case. The postfix-expression is the first argument of the
13108         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13109         // are in the following arguments.
13110         //
13111         // Note that we intentionally do not visit the callee expression since
13112         // it is just a decayed reference to a function.
13113         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13114         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13115         SequenceTree::Seq OldRegion = Region;
13116 
13117         assert(CXXOCE->getNumArgs() >= 1 &&
13118                "An overloaded call operator must have at least one argument"
13119                " for the postfix-expression!");
13120         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13121         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13122                                           CXXOCE->getNumArgs() - 1);
13123 
13124         // Visit the postfix-expression first.
13125         {
13126           Region = PostfixExprRegion;
13127           SequencedSubexpression Sequenced(*this);
13128           Visit(PostfixExpr);
13129         }
13130 
13131         // Then visit the argument expressions.
13132         Region = ArgsRegion;
13133         for (const Expr *Arg : Args)
13134           Visit(Arg);
13135 
13136         Region = OldRegion;
13137         Tree.merge(PostfixExprRegion);
13138         Tree.merge(ArgsRegion);
13139       } else {
13140         assert(CXXOCE->getNumArgs() == 2 &&
13141                "Should only have two arguments here!");
13142         assert((SequencingKind == LHSBeforeRHS ||
13143                 SequencingKind == RHSBeforeLHS) &&
13144                "Unexpected sequencing kind!");
13145 
13146         // We do not visit the callee expression since it is just a decayed
13147         // reference to a function.
13148         const Expr *E1 = CXXOCE->getArg(0);
13149         const Expr *E2 = CXXOCE->getArg(1);
13150         if (SequencingKind == RHSBeforeLHS)
13151           std::swap(E1, E2);
13152 
13153         return VisitSequencedExpressions(E1, E2);
13154       }
13155     });
13156   }
13157 
13158   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13159     // This is a call, so all subexpressions are sequenced before the result.
13160     SequencedSubexpression Sequenced(*this);
13161 
13162     if (!CCE->isListInitialization())
13163       return VisitExpr(CCE);
13164 
13165     // In C++11, list initializations are sequenced.
13166     SmallVector<SequenceTree::Seq, 32> Elts;
13167     SequenceTree::Seq Parent = Region;
13168     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13169                                               E = CCE->arg_end();
13170          I != E; ++I) {
13171       Region = Tree.allocate(Parent);
13172       Elts.push_back(Region);
13173       Visit(*I);
13174     }
13175 
13176     // Forget that the initializers are sequenced.
13177     Region = Parent;
13178     for (unsigned I = 0; I < Elts.size(); ++I)
13179       Tree.merge(Elts[I]);
13180   }
13181 
13182   void VisitInitListExpr(const InitListExpr *ILE) {
13183     if (!SemaRef.getLangOpts().CPlusPlus11)
13184       return VisitExpr(ILE);
13185 
13186     // In C++11, list initializations are sequenced.
13187     SmallVector<SequenceTree::Seq, 32> Elts;
13188     SequenceTree::Seq Parent = Region;
13189     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13190       const Expr *E = ILE->getInit(I);
13191       if (!E)
13192         continue;
13193       Region = Tree.allocate(Parent);
13194       Elts.push_back(Region);
13195       Visit(E);
13196     }
13197 
13198     // Forget that the initializers are sequenced.
13199     Region = Parent;
13200     for (unsigned I = 0; I < Elts.size(); ++I)
13201       Tree.merge(Elts[I]);
13202   }
13203 };
13204 
13205 } // namespace
13206 
13207 void Sema::CheckUnsequencedOperations(const Expr *E) {
13208   SmallVector<const Expr *, 8> WorkList;
13209   WorkList.push_back(E);
13210   while (!WorkList.empty()) {
13211     const Expr *Item = WorkList.pop_back_val();
13212     SequenceChecker(*this, Item, WorkList);
13213   }
13214 }
13215 
13216 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13217                               bool IsConstexpr) {
13218   llvm::SaveAndRestore<bool> ConstantContext(
13219       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13220   CheckImplicitConversions(E, CheckLoc);
13221   if (!E->isInstantiationDependent())
13222     CheckUnsequencedOperations(E);
13223   if (!IsConstexpr && !E->isValueDependent())
13224     CheckForIntOverflow(E);
13225   DiagnoseMisalignedMembers();
13226 }
13227 
13228 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13229                                        FieldDecl *BitField,
13230                                        Expr *Init) {
13231   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13232 }
13233 
13234 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13235                                          SourceLocation Loc) {
13236   if (!PType->isVariablyModifiedType())
13237     return;
13238   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13239     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13240     return;
13241   }
13242   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13243     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13244     return;
13245   }
13246   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13247     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13248     return;
13249   }
13250 
13251   const ArrayType *AT = S.Context.getAsArrayType(PType);
13252   if (!AT)
13253     return;
13254 
13255   if (AT->getSizeModifier() != ArrayType::Star) {
13256     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13257     return;
13258   }
13259 
13260   S.Diag(Loc, diag::err_array_star_in_function_definition);
13261 }
13262 
13263 /// CheckParmsForFunctionDef - Check that the parameters of the given
13264 /// function are appropriate for the definition of a function. This
13265 /// takes care of any checks that cannot be performed on the
13266 /// declaration itself, e.g., that the types of each of the function
13267 /// parameters are complete.
13268 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13269                                     bool CheckParameterNames) {
13270   bool HasInvalidParm = false;
13271   for (ParmVarDecl *Param : Parameters) {
13272     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13273     // function declarator that is part of a function definition of
13274     // that function shall not have incomplete type.
13275     //
13276     // This is also C++ [dcl.fct]p6.
13277     if (!Param->isInvalidDecl() &&
13278         RequireCompleteType(Param->getLocation(), Param->getType(),
13279                             diag::err_typecheck_decl_incomplete_type)) {
13280       Param->setInvalidDecl();
13281       HasInvalidParm = true;
13282     }
13283 
13284     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13285     // declaration of each parameter shall include an identifier.
13286     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13287         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13288       // Diagnose this as an extension in C17 and earlier.
13289       if (!getLangOpts().C2x)
13290         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13291     }
13292 
13293     // C99 6.7.5.3p12:
13294     //   If the function declarator is not part of a definition of that
13295     //   function, parameters may have incomplete type and may use the [*]
13296     //   notation in their sequences of declarator specifiers to specify
13297     //   variable length array types.
13298     QualType PType = Param->getOriginalType();
13299     // FIXME: This diagnostic should point the '[*]' if source-location
13300     // information is added for it.
13301     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13302 
13303     // If the parameter is a c++ class type and it has to be destructed in the
13304     // callee function, declare the destructor so that it can be called by the
13305     // callee function. Do not perform any direct access check on the dtor here.
13306     if (!Param->isInvalidDecl()) {
13307       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13308         if (!ClassDecl->isInvalidDecl() &&
13309             !ClassDecl->hasIrrelevantDestructor() &&
13310             !ClassDecl->isDependentContext() &&
13311             ClassDecl->isParamDestroyedInCallee()) {
13312           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13313           MarkFunctionReferenced(Param->getLocation(), Destructor);
13314           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13315         }
13316       }
13317     }
13318 
13319     // Parameters with the pass_object_size attribute only need to be marked
13320     // constant at function definitions. Because we lack information about
13321     // whether we're on a declaration or definition when we're instantiating the
13322     // attribute, we need to check for constness here.
13323     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13324       if (!Param->getType().isConstQualified())
13325         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13326             << Attr->getSpelling() << 1;
13327 
13328     // Check for parameter names shadowing fields from the class.
13329     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13330       // The owning context for the parameter should be the function, but we
13331       // want to see if this function's declaration context is a record.
13332       DeclContext *DC = Param->getDeclContext();
13333       if (DC && DC->isFunctionOrMethod()) {
13334         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13335           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13336                                      RD, /*DeclIsField*/ false);
13337       }
13338     }
13339   }
13340 
13341   return HasInvalidParm;
13342 }
13343 
13344 Optional<std::pair<CharUnits, CharUnits>>
13345 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13346 
13347 /// Compute the alignment and offset of the base class object given the
13348 /// derived-to-base cast expression and the alignment and offset of the derived
13349 /// class object.
13350 static std::pair<CharUnits, CharUnits>
13351 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13352                                    CharUnits BaseAlignment, CharUnits Offset,
13353                                    ASTContext &Ctx) {
13354   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13355        ++PathI) {
13356     const CXXBaseSpecifier *Base = *PathI;
13357     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13358     if (Base->isVirtual()) {
13359       // The complete object may have a lower alignment than the non-virtual
13360       // alignment of the base, in which case the base may be misaligned. Choose
13361       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13362       // conservative lower bound of the complete object alignment.
13363       CharUnits NonVirtualAlignment =
13364           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13365       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13366       Offset = CharUnits::Zero();
13367     } else {
13368       const ASTRecordLayout &RL =
13369           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13370       Offset += RL.getBaseClassOffset(BaseDecl);
13371     }
13372     DerivedType = Base->getType();
13373   }
13374 
13375   return std::make_pair(BaseAlignment, Offset);
13376 }
13377 
13378 /// Compute the alignment and offset of a binary additive operator.
13379 static Optional<std::pair<CharUnits, CharUnits>>
13380 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13381                                      bool IsSub, ASTContext &Ctx) {
13382   QualType PointeeType = PtrE->getType()->getPointeeType();
13383 
13384   if (!PointeeType->isConstantSizeType())
13385     return llvm::None;
13386 
13387   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13388 
13389   if (!P)
13390     return llvm::None;
13391 
13392   llvm::APSInt IdxRes;
13393   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13394   if (IntE->isIntegerConstantExpr(IdxRes, Ctx)) {
13395     CharUnits Offset = EltSize * IdxRes.getExtValue();
13396     if (IsSub)
13397       Offset = -Offset;
13398     return std::make_pair(P->first, P->second + Offset);
13399   }
13400 
13401   // If the integer expression isn't a constant expression, compute the lower
13402   // bound of the alignment using the alignment and offset of the pointer
13403   // expression and the element size.
13404   return std::make_pair(
13405       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13406       CharUnits::Zero());
13407 }
13408 
13409 /// This helper function takes an lvalue expression and returns the alignment of
13410 /// a VarDecl and a constant offset from the VarDecl.
13411 Optional<std::pair<CharUnits, CharUnits>>
13412 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
13413   E = E->IgnoreParens();
13414   switch (E->getStmtClass()) {
13415   default:
13416     break;
13417   case Stmt::CStyleCastExprClass:
13418   case Stmt::CXXStaticCastExprClass:
13419   case Stmt::ImplicitCastExprClass: {
13420     auto *CE = cast<CastExpr>(E);
13421     const Expr *From = CE->getSubExpr();
13422     switch (CE->getCastKind()) {
13423     default:
13424       break;
13425     case CK_NoOp:
13426       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13427     case CK_UncheckedDerivedToBase:
13428     case CK_DerivedToBase: {
13429       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13430       if (!P)
13431         break;
13432       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13433                                                 P->second, Ctx);
13434     }
13435     }
13436     break;
13437   }
13438   case Stmt::ArraySubscriptExprClass: {
13439     auto *ASE = cast<ArraySubscriptExpr>(E);
13440     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
13441                                                 false, Ctx);
13442   }
13443   case Stmt::DeclRefExprClass: {
13444     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
13445       // FIXME: If VD is captured by copy or is an escaping __block variable,
13446       // use the alignment of VD's type.
13447       if (!VD->getType()->isReferenceType())
13448         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
13449       if (VD->hasInit())
13450         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
13451     }
13452     break;
13453   }
13454   case Stmt::MemberExprClass: {
13455     auto *ME = cast<MemberExpr>(E);
13456     if (ME->isArrow())
13457       break;
13458     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13459     if (!FD || FD->getType()->isReferenceType())
13460       break;
13461     auto P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
13462     if (!P)
13463       break;
13464     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
13465     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
13466     return std::make_pair(P->first,
13467                           P->second + CharUnits::fromQuantity(Offset));
13468   }
13469   case Stmt::UnaryOperatorClass: {
13470     auto *UO = cast<UnaryOperator>(E);
13471     switch (UO->getOpcode()) {
13472     default:
13473       break;
13474     case UO_Deref:
13475       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
13476     }
13477     break;
13478   }
13479   case Stmt::BinaryOperatorClass: {
13480     auto *BO = cast<BinaryOperator>(E);
13481     auto Opcode = BO->getOpcode();
13482     switch (Opcode) {
13483     default:
13484       break;
13485     case BO_Comma:
13486       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
13487     }
13488     break;
13489   }
13490   }
13491   return llvm::None;
13492 }
13493 
13494 /// This helper function takes a pointer expression and returns the alignment of
13495 /// a VarDecl and a constant offset from the VarDecl.
13496 Optional<std::pair<CharUnits, CharUnits>>
13497 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
13498   E = E->IgnoreParens();
13499   switch (E->getStmtClass()) {
13500   default:
13501     break;
13502   case Stmt::CStyleCastExprClass:
13503   case Stmt::CXXStaticCastExprClass:
13504   case Stmt::ImplicitCastExprClass: {
13505     auto *CE = cast<CastExpr>(E);
13506     const Expr *From = CE->getSubExpr();
13507     switch (CE->getCastKind()) {
13508     default:
13509       break;
13510     case CK_NoOp:
13511       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13512     case CK_ArrayToPointerDecay:
13513       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13514     case CK_UncheckedDerivedToBase:
13515     case CK_DerivedToBase: {
13516       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13517       if (!P)
13518         break;
13519       return getDerivedToBaseAlignmentAndOffset(
13520           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13521     }
13522     }
13523     break;
13524   }
13525   case Stmt::UnaryOperatorClass: {
13526     auto *UO = cast<UnaryOperator>(E);
13527     if (UO->getOpcode() == UO_AddrOf)
13528       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
13529     break;
13530   }
13531   case Stmt::BinaryOperatorClass: {
13532     auto *BO = cast<BinaryOperator>(E);
13533     auto Opcode = BO->getOpcode();
13534     switch (Opcode) {
13535     default:
13536       break;
13537     case BO_Add:
13538     case BO_Sub: {
13539       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13540       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13541         std::swap(LHS, RHS);
13542       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13543                                                   Ctx);
13544     }
13545     case BO_Comma:
13546       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13547     }
13548     break;
13549   }
13550   }
13551   return llvm::None;
13552 }
13553 
13554 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
13555   // See if we can compute the alignment of a VarDecl and an offset from it.
13556   Optional<std::pair<CharUnits, CharUnits>> P =
13557       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
13558 
13559   if (P)
13560     return P->first.alignmentAtOffset(P->second);
13561 
13562   // If that failed, return the type's alignment.
13563   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
13564 }
13565 
13566 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13567 /// pointer cast increases the alignment requirements.
13568 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13569   // This is actually a lot of work to potentially be doing on every
13570   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13571   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13572     return;
13573 
13574   // Ignore dependent types.
13575   if (T->isDependentType() || Op->getType()->isDependentType())
13576     return;
13577 
13578   // Require that the destination be a pointer type.
13579   const PointerType *DestPtr = T->getAs<PointerType>();
13580   if (!DestPtr) return;
13581 
13582   // If the destination has alignment 1, we're done.
13583   QualType DestPointee = DestPtr->getPointeeType();
13584   if (DestPointee->isIncompleteType()) return;
13585   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13586   if (DestAlign.isOne()) return;
13587 
13588   // Require that the source be a pointer type.
13589   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13590   if (!SrcPtr) return;
13591   QualType SrcPointee = SrcPtr->getPointeeType();
13592 
13593   // Explicitly allow casts from cv void*.  We already implicitly
13594   // allowed casts to cv void*, since they have alignment 1.
13595   // Also allow casts involving incomplete types, which implicitly
13596   // includes 'void'.
13597   if (SrcPointee->isIncompleteType()) return;
13598 
13599   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
13600 
13601   if (SrcAlign >= DestAlign) return;
13602 
13603   Diag(TRange.getBegin(), diag::warn_cast_align)
13604     << Op->getType() << T
13605     << static_cast<unsigned>(SrcAlign.getQuantity())
13606     << static_cast<unsigned>(DestAlign.getQuantity())
13607     << TRange << Op->getSourceRange();
13608 }
13609 
13610 /// Check whether this array fits the idiom of a size-one tail padded
13611 /// array member of a struct.
13612 ///
13613 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13614 /// commonly used to emulate flexible arrays in C89 code.
13615 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13616                                     const NamedDecl *ND) {
13617   if (Size != 1 || !ND) return false;
13618 
13619   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13620   if (!FD) return false;
13621 
13622   // Don't consider sizes resulting from macro expansions or template argument
13623   // substitution to form C89 tail-padded arrays.
13624 
13625   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13626   while (TInfo) {
13627     TypeLoc TL = TInfo->getTypeLoc();
13628     // Look through typedefs.
13629     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13630       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13631       TInfo = TDL->getTypeSourceInfo();
13632       continue;
13633     }
13634     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13635       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13636       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13637         return false;
13638     }
13639     break;
13640   }
13641 
13642   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13643   if (!RD) return false;
13644   if (RD->isUnion()) return false;
13645   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13646     if (!CRD->isStandardLayout()) return false;
13647   }
13648 
13649   // See if this is the last field decl in the record.
13650   const Decl *D = FD;
13651   while ((D = D->getNextDeclInContext()))
13652     if (isa<FieldDecl>(D))
13653       return false;
13654   return true;
13655 }
13656 
13657 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13658                             const ArraySubscriptExpr *ASE,
13659                             bool AllowOnePastEnd, bool IndexNegated) {
13660   // Already diagnosed by the constant evaluator.
13661   if (isConstantEvaluated())
13662     return;
13663 
13664   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13665   if (IndexExpr->isValueDependent())
13666     return;
13667 
13668   const Type *EffectiveType =
13669       BaseExpr->getType()->getPointeeOrArrayElementType();
13670   BaseExpr = BaseExpr->IgnoreParenCasts();
13671   const ConstantArrayType *ArrayTy =
13672       Context.getAsConstantArrayType(BaseExpr->getType());
13673 
13674   if (!ArrayTy)
13675     return;
13676 
13677   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13678   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13679     return;
13680 
13681   Expr::EvalResult Result;
13682   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13683     return;
13684 
13685   llvm::APSInt index = Result.Val.getInt();
13686   if (IndexNegated)
13687     index = -index;
13688 
13689   const NamedDecl *ND = nullptr;
13690   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13691     ND = DRE->getDecl();
13692   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13693     ND = ME->getMemberDecl();
13694 
13695   if (index.isUnsigned() || !index.isNegative()) {
13696     // It is possible that the type of the base expression after
13697     // IgnoreParenCasts is incomplete, even though the type of the base
13698     // expression before IgnoreParenCasts is complete (see PR39746 for an
13699     // example). In this case we have no information about whether the array
13700     // access exceeds the array bounds. However we can still diagnose an array
13701     // access which precedes the array bounds.
13702     if (BaseType->isIncompleteType())
13703       return;
13704 
13705     llvm::APInt size = ArrayTy->getSize();
13706     if (!size.isStrictlyPositive())
13707       return;
13708 
13709     if (BaseType != EffectiveType) {
13710       // Make sure we're comparing apples to apples when comparing index to size
13711       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13712       uint64_t array_typesize = Context.getTypeSize(BaseType);
13713       // Handle ptrarith_typesize being zero, such as when casting to void*
13714       if (!ptrarith_typesize) ptrarith_typesize = 1;
13715       if (ptrarith_typesize != array_typesize) {
13716         // There's a cast to a different size type involved
13717         uint64_t ratio = array_typesize / ptrarith_typesize;
13718         // TODO: Be smarter about handling cases where array_typesize is not a
13719         // multiple of ptrarith_typesize
13720         if (ptrarith_typesize * ratio == array_typesize)
13721           size *= llvm::APInt(size.getBitWidth(), ratio);
13722       }
13723     }
13724 
13725     if (size.getBitWidth() > index.getBitWidth())
13726       index = index.zext(size.getBitWidth());
13727     else if (size.getBitWidth() < index.getBitWidth())
13728       size = size.zext(index.getBitWidth());
13729 
13730     // For array subscripting the index must be less than size, but for pointer
13731     // arithmetic also allow the index (offset) to be equal to size since
13732     // computing the next address after the end of the array is legal and
13733     // commonly done e.g. in C++ iterators and range-based for loops.
13734     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13735       return;
13736 
13737     // Also don't warn for arrays of size 1 which are members of some
13738     // structure. These are often used to approximate flexible arrays in C89
13739     // code.
13740     if (IsTailPaddedMemberArray(*this, size, ND))
13741       return;
13742 
13743     // Suppress the warning if the subscript expression (as identified by the
13744     // ']' location) and the index expression are both from macro expansions
13745     // within a system header.
13746     if (ASE) {
13747       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13748           ASE->getRBracketLoc());
13749       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13750         SourceLocation IndexLoc =
13751             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13752         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13753           return;
13754       }
13755     }
13756 
13757     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13758     if (ASE)
13759       DiagID = diag::warn_array_index_exceeds_bounds;
13760 
13761     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13762                         PDiag(DiagID) << index.toString(10, true)
13763                                       << size.toString(10, true)
13764                                       << (unsigned)size.getLimitedValue(~0U)
13765                                       << IndexExpr->getSourceRange());
13766   } else {
13767     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13768     if (!ASE) {
13769       DiagID = diag::warn_ptr_arith_precedes_bounds;
13770       if (index.isNegative()) index = -index;
13771     }
13772 
13773     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13774                         PDiag(DiagID) << index.toString(10, true)
13775                                       << IndexExpr->getSourceRange());
13776   }
13777 
13778   if (!ND) {
13779     // Try harder to find a NamedDecl to point at in the note.
13780     while (const ArraySubscriptExpr *ASE =
13781            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13782       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13783     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13784       ND = DRE->getDecl();
13785     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13786       ND = ME->getMemberDecl();
13787   }
13788 
13789   if (ND)
13790     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13791                         PDiag(diag::note_array_declared_here)
13792                             << ND->getDeclName());
13793 }
13794 
13795 void Sema::CheckArrayAccess(const Expr *expr) {
13796   int AllowOnePastEnd = 0;
13797   while (expr) {
13798     expr = expr->IgnoreParenImpCasts();
13799     switch (expr->getStmtClass()) {
13800       case Stmt::ArraySubscriptExprClass: {
13801         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13802         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13803                          AllowOnePastEnd > 0);
13804         expr = ASE->getBase();
13805         break;
13806       }
13807       case Stmt::MemberExprClass: {
13808         expr = cast<MemberExpr>(expr)->getBase();
13809         break;
13810       }
13811       case Stmt::OMPArraySectionExprClass: {
13812         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13813         if (ASE->getLowerBound())
13814           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13815                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13816         return;
13817       }
13818       case Stmt::UnaryOperatorClass: {
13819         // Only unwrap the * and & unary operators
13820         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13821         expr = UO->getSubExpr();
13822         switch (UO->getOpcode()) {
13823           case UO_AddrOf:
13824             AllowOnePastEnd++;
13825             break;
13826           case UO_Deref:
13827             AllowOnePastEnd--;
13828             break;
13829           default:
13830             return;
13831         }
13832         break;
13833       }
13834       case Stmt::ConditionalOperatorClass: {
13835         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13836         if (const Expr *lhs = cond->getLHS())
13837           CheckArrayAccess(lhs);
13838         if (const Expr *rhs = cond->getRHS())
13839           CheckArrayAccess(rhs);
13840         return;
13841       }
13842       case Stmt::CXXOperatorCallExprClass: {
13843         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13844         for (const auto *Arg : OCE->arguments())
13845           CheckArrayAccess(Arg);
13846         return;
13847       }
13848       default:
13849         return;
13850     }
13851   }
13852 }
13853 
13854 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13855 
13856 namespace {
13857 
13858 struct RetainCycleOwner {
13859   VarDecl *Variable = nullptr;
13860   SourceRange Range;
13861   SourceLocation Loc;
13862   bool Indirect = false;
13863 
13864   RetainCycleOwner() = default;
13865 
13866   void setLocsFrom(Expr *e) {
13867     Loc = e->getExprLoc();
13868     Range = e->getSourceRange();
13869   }
13870 };
13871 
13872 } // namespace
13873 
13874 /// Consider whether capturing the given variable can possibly lead to
13875 /// a retain cycle.
13876 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13877   // In ARC, it's captured strongly iff the variable has __strong
13878   // lifetime.  In MRR, it's captured strongly if the variable is
13879   // __block and has an appropriate type.
13880   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13881     return false;
13882 
13883   owner.Variable = var;
13884   if (ref)
13885     owner.setLocsFrom(ref);
13886   return true;
13887 }
13888 
13889 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13890   while (true) {
13891     e = e->IgnoreParens();
13892     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13893       switch (cast->getCastKind()) {
13894       case CK_BitCast:
13895       case CK_LValueBitCast:
13896       case CK_LValueToRValue:
13897       case CK_ARCReclaimReturnedObject:
13898         e = cast->getSubExpr();
13899         continue;
13900 
13901       default:
13902         return false;
13903       }
13904     }
13905 
13906     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13907       ObjCIvarDecl *ivar = ref->getDecl();
13908       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13909         return false;
13910 
13911       // Try to find a retain cycle in the base.
13912       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13913         return false;
13914 
13915       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13916       owner.Indirect = true;
13917       return true;
13918     }
13919 
13920     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13921       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13922       if (!var) return false;
13923       return considerVariable(var, ref, owner);
13924     }
13925 
13926     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13927       if (member->isArrow()) return false;
13928 
13929       // Don't count this as an indirect ownership.
13930       e = member->getBase();
13931       continue;
13932     }
13933 
13934     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13935       // Only pay attention to pseudo-objects on property references.
13936       ObjCPropertyRefExpr *pre
13937         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13938                                               ->IgnoreParens());
13939       if (!pre) return false;
13940       if (pre->isImplicitProperty()) return false;
13941       ObjCPropertyDecl *property = pre->getExplicitProperty();
13942       if (!property->isRetaining() &&
13943           !(property->getPropertyIvarDecl() &&
13944             property->getPropertyIvarDecl()->getType()
13945               .getObjCLifetime() == Qualifiers::OCL_Strong))
13946           return false;
13947 
13948       owner.Indirect = true;
13949       if (pre->isSuperReceiver()) {
13950         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13951         if (!owner.Variable)
13952           return false;
13953         owner.Loc = pre->getLocation();
13954         owner.Range = pre->getSourceRange();
13955         return true;
13956       }
13957       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13958                               ->getSourceExpr());
13959       continue;
13960     }
13961 
13962     // Array ivars?
13963 
13964     return false;
13965   }
13966 }
13967 
13968 namespace {
13969 
13970   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13971     ASTContext &Context;
13972     VarDecl *Variable;
13973     Expr *Capturer = nullptr;
13974     bool VarWillBeReased = false;
13975 
13976     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13977         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13978           Context(Context), Variable(variable) {}
13979 
13980     void VisitDeclRefExpr(DeclRefExpr *ref) {
13981       if (ref->getDecl() == Variable && !Capturer)
13982         Capturer = ref;
13983     }
13984 
13985     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13986       if (Capturer) return;
13987       Visit(ref->getBase());
13988       if (Capturer && ref->isFreeIvar())
13989         Capturer = ref;
13990     }
13991 
13992     void VisitBlockExpr(BlockExpr *block) {
13993       // Look inside nested blocks
13994       if (block->getBlockDecl()->capturesVariable(Variable))
13995         Visit(block->getBlockDecl()->getBody());
13996     }
13997 
13998     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13999       if (Capturer) return;
14000       if (OVE->getSourceExpr())
14001         Visit(OVE->getSourceExpr());
14002     }
14003 
14004     void VisitBinaryOperator(BinaryOperator *BinOp) {
14005       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14006         return;
14007       Expr *LHS = BinOp->getLHS();
14008       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14009         if (DRE->getDecl() != Variable)
14010           return;
14011         if (Expr *RHS = BinOp->getRHS()) {
14012           RHS = RHS->IgnoreParenCasts();
14013           llvm::APSInt Value;
14014           VarWillBeReased =
14015             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
14016         }
14017       }
14018     }
14019   };
14020 
14021 } // namespace
14022 
14023 /// Check whether the given argument is a block which captures a
14024 /// variable.
14025 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14026   assert(owner.Variable && owner.Loc.isValid());
14027 
14028   e = e->IgnoreParenCasts();
14029 
14030   // Look through [^{...} copy] and Block_copy(^{...}).
14031   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14032     Selector Cmd = ME->getSelector();
14033     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14034       e = ME->getInstanceReceiver();
14035       if (!e)
14036         return nullptr;
14037       e = e->IgnoreParenCasts();
14038     }
14039   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14040     if (CE->getNumArgs() == 1) {
14041       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14042       if (Fn) {
14043         const IdentifierInfo *FnI = Fn->getIdentifier();
14044         if (FnI && FnI->isStr("_Block_copy")) {
14045           e = CE->getArg(0)->IgnoreParenCasts();
14046         }
14047       }
14048     }
14049   }
14050 
14051   BlockExpr *block = dyn_cast<BlockExpr>(e);
14052   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14053     return nullptr;
14054 
14055   FindCaptureVisitor visitor(S.Context, owner.Variable);
14056   visitor.Visit(block->getBlockDecl()->getBody());
14057   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14058 }
14059 
14060 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14061                                 RetainCycleOwner &owner) {
14062   assert(capturer);
14063   assert(owner.Variable && owner.Loc.isValid());
14064 
14065   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14066     << owner.Variable << capturer->getSourceRange();
14067   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14068     << owner.Indirect << owner.Range;
14069 }
14070 
14071 /// Check for a keyword selector that starts with the word 'add' or
14072 /// 'set'.
14073 static bool isSetterLikeSelector(Selector sel) {
14074   if (sel.isUnarySelector()) return false;
14075 
14076   StringRef str = sel.getNameForSlot(0);
14077   while (!str.empty() && str.front() == '_') str = str.substr(1);
14078   if (str.startswith("set"))
14079     str = str.substr(3);
14080   else if (str.startswith("add")) {
14081     // Specially allow 'addOperationWithBlock:'.
14082     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14083       return false;
14084     str = str.substr(3);
14085   }
14086   else
14087     return false;
14088 
14089   if (str.empty()) return true;
14090   return !isLowercase(str.front());
14091 }
14092 
14093 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14094                                                     ObjCMessageExpr *Message) {
14095   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14096                                                 Message->getReceiverInterface(),
14097                                                 NSAPI::ClassId_NSMutableArray);
14098   if (!IsMutableArray) {
14099     return None;
14100   }
14101 
14102   Selector Sel = Message->getSelector();
14103 
14104   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14105     S.NSAPIObj->getNSArrayMethodKind(Sel);
14106   if (!MKOpt) {
14107     return None;
14108   }
14109 
14110   NSAPI::NSArrayMethodKind MK = *MKOpt;
14111 
14112   switch (MK) {
14113     case NSAPI::NSMutableArr_addObject:
14114     case NSAPI::NSMutableArr_insertObjectAtIndex:
14115     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14116       return 0;
14117     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14118       return 1;
14119 
14120     default:
14121       return None;
14122   }
14123 
14124   return None;
14125 }
14126 
14127 static
14128 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14129                                                   ObjCMessageExpr *Message) {
14130   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14131                                             Message->getReceiverInterface(),
14132                                             NSAPI::ClassId_NSMutableDictionary);
14133   if (!IsMutableDictionary) {
14134     return None;
14135   }
14136 
14137   Selector Sel = Message->getSelector();
14138 
14139   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14140     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14141   if (!MKOpt) {
14142     return None;
14143   }
14144 
14145   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14146 
14147   switch (MK) {
14148     case NSAPI::NSMutableDict_setObjectForKey:
14149     case NSAPI::NSMutableDict_setValueForKey:
14150     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14151       return 0;
14152 
14153     default:
14154       return None;
14155   }
14156 
14157   return None;
14158 }
14159 
14160 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14161   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14162                                                 Message->getReceiverInterface(),
14163                                                 NSAPI::ClassId_NSMutableSet);
14164 
14165   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14166                                             Message->getReceiverInterface(),
14167                                             NSAPI::ClassId_NSMutableOrderedSet);
14168   if (!IsMutableSet && !IsMutableOrderedSet) {
14169     return None;
14170   }
14171 
14172   Selector Sel = Message->getSelector();
14173 
14174   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14175   if (!MKOpt) {
14176     return None;
14177   }
14178 
14179   NSAPI::NSSetMethodKind MK = *MKOpt;
14180 
14181   switch (MK) {
14182     case NSAPI::NSMutableSet_addObject:
14183     case NSAPI::NSOrderedSet_setObjectAtIndex:
14184     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14185     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14186       return 0;
14187     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14188       return 1;
14189   }
14190 
14191   return None;
14192 }
14193 
14194 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14195   if (!Message->isInstanceMessage()) {
14196     return;
14197   }
14198 
14199   Optional<int> ArgOpt;
14200 
14201   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14202       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14203       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14204     return;
14205   }
14206 
14207   int ArgIndex = *ArgOpt;
14208 
14209   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14210   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14211     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14212   }
14213 
14214   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14215     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14216       if (ArgRE->isObjCSelfExpr()) {
14217         Diag(Message->getSourceRange().getBegin(),
14218              diag::warn_objc_circular_container)
14219           << ArgRE->getDecl() << StringRef("'super'");
14220       }
14221     }
14222   } else {
14223     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14224 
14225     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14226       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14227     }
14228 
14229     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14230       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14231         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14232           ValueDecl *Decl = ReceiverRE->getDecl();
14233           Diag(Message->getSourceRange().getBegin(),
14234                diag::warn_objc_circular_container)
14235             << Decl << Decl;
14236           if (!ArgRE->isObjCSelfExpr()) {
14237             Diag(Decl->getLocation(),
14238                  diag::note_objc_circular_container_declared_here)
14239               << Decl;
14240           }
14241         }
14242       }
14243     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14244       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14245         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14246           ObjCIvarDecl *Decl = IvarRE->getDecl();
14247           Diag(Message->getSourceRange().getBegin(),
14248                diag::warn_objc_circular_container)
14249             << Decl << Decl;
14250           Diag(Decl->getLocation(),
14251                diag::note_objc_circular_container_declared_here)
14252             << Decl;
14253         }
14254       }
14255     }
14256   }
14257 }
14258 
14259 /// Check a message send to see if it's likely to cause a retain cycle.
14260 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14261   // Only check instance methods whose selector looks like a setter.
14262   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14263     return;
14264 
14265   // Try to find a variable that the receiver is strongly owned by.
14266   RetainCycleOwner owner;
14267   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14268     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14269       return;
14270   } else {
14271     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14272     owner.Variable = getCurMethodDecl()->getSelfDecl();
14273     owner.Loc = msg->getSuperLoc();
14274     owner.Range = msg->getSuperLoc();
14275   }
14276 
14277   // Check whether the receiver is captured by any of the arguments.
14278   const ObjCMethodDecl *MD = msg->getMethodDecl();
14279   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14280     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14281       // noescape blocks should not be retained by the method.
14282       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14283         continue;
14284       return diagnoseRetainCycle(*this, capturer, owner);
14285     }
14286   }
14287 }
14288 
14289 /// Check a property assign to see if it's likely to cause a retain cycle.
14290 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14291   RetainCycleOwner owner;
14292   if (!findRetainCycleOwner(*this, receiver, owner))
14293     return;
14294 
14295   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14296     diagnoseRetainCycle(*this, capturer, owner);
14297 }
14298 
14299 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14300   RetainCycleOwner Owner;
14301   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14302     return;
14303 
14304   // Because we don't have an expression for the variable, we have to set the
14305   // location explicitly here.
14306   Owner.Loc = Var->getLocation();
14307   Owner.Range = Var->getSourceRange();
14308 
14309   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14310     diagnoseRetainCycle(*this, Capturer, Owner);
14311 }
14312 
14313 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14314                                      Expr *RHS, bool isProperty) {
14315   // Check if RHS is an Objective-C object literal, which also can get
14316   // immediately zapped in a weak reference.  Note that we explicitly
14317   // allow ObjCStringLiterals, since those are designed to never really die.
14318   RHS = RHS->IgnoreParenImpCasts();
14319 
14320   // This enum needs to match with the 'select' in
14321   // warn_objc_arc_literal_assign (off-by-1).
14322   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14323   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14324     return false;
14325 
14326   S.Diag(Loc, diag::warn_arc_literal_assign)
14327     << (unsigned) Kind
14328     << (isProperty ? 0 : 1)
14329     << RHS->getSourceRange();
14330 
14331   return true;
14332 }
14333 
14334 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14335                                     Qualifiers::ObjCLifetime LT,
14336                                     Expr *RHS, bool isProperty) {
14337   // Strip off any implicit cast added to get to the one ARC-specific.
14338   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14339     if (cast->getCastKind() == CK_ARCConsumeObject) {
14340       S.Diag(Loc, diag::warn_arc_retained_assign)
14341         << (LT == Qualifiers::OCL_ExplicitNone)
14342         << (isProperty ? 0 : 1)
14343         << RHS->getSourceRange();
14344       return true;
14345     }
14346     RHS = cast->getSubExpr();
14347   }
14348 
14349   if (LT == Qualifiers::OCL_Weak &&
14350       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14351     return true;
14352 
14353   return false;
14354 }
14355 
14356 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14357                               QualType LHS, Expr *RHS) {
14358   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14359 
14360   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14361     return false;
14362 
14363   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14364     return true;
14365 
14366   return false;
14367 }
14368 
14369 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14370                               Expr *LHS, Expr *RHS) {
14371   QualType LHSType;
14372   // PropertyRef on LHS type need be directly obtained from
14373   // its declaration as it has a PseudoType.
14374   ObjCPropertyRefExpr *PRE
14375     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14376   if (PRE && !PRE->isImplicitProperty()) {
14377     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14378     if (PD)
14379       LHSType = PD->getType();
14380   }
14381 
14382   if (LHSType.isNull())
14383     LHSType = LHS->getType();
14384 
14385   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14386 
14387   if (LT == Qualifiers::OCL_Weak) {
14388     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14389       getCurFunction()->markSafeWeakUse(LHS);
14390   }
14391 
14392   if (checkUnsafeAssigns(Loc, LHSType, RHS))
14393     return;
14394 
14395   // FIXME. Check for other life times.
14396   if (LT != Qualifiers::OCL_None)
14397     return;
14398 
14399   if (PRE) {
14400     if (PRE->isImplicitProperty())
14401       return;
14402     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14403     if (!PD)
14404       return;
14405 
14406     unsigned Attributes = PD->getPropertyAttributes();
14407     if (Attributes & ObjCPropertyAttribute::kind_assign) {
14408       // when 'assign' attribute was not explicitly specified
14409       // by user, ignore it and rely on property type itself
14410       // for lifetime info.
14411       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14412       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14413           LHSType->isObjCRetainableType())
14414         return;
14415 
14416       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14417         if (cast->getCastKind() == CK_ARCConsumeObject) {
14418           Diag(Loc, diag::warn_arc_retained_property_assign)
14419           << RHS->getSourceRange();
14420           return;
14421         }
14422         RHS = cast->getSubExpr();
14423       }
14424     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
14425       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14426         return;
14427     }
14428   }
14429 }
14430 
14431 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14432 
14433 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14434                                         SourceLocation StmtLoc,
14435                                         const NullStmt *Body) {
14436   // Do not warn if the body is a macro that expands to nothing, e.g:
14437   //
14438   // #define CALL(x)
14439   // if (condition)
14440   //   CALL(0);
14441   if (Body->hasLeadingEmptyMacro())
14442     return false;
14443 
14444   // Get line numbers of statement and body.
14445   bool StmtLineInvalid;
14446   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14447                                                       &StmtLineInvalid);
14448   if (StmtLineInvalid)
14449     return false;
14450 
14451   bool BodyLineInvalid;
14452   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14453                                                       &BodyLineInvalid);
14454   if (BodyLineInvalid)
14455     return false;
14456 
14457   // Warn if null statement and body are on the same line.
14458   if (StmtLine != BodyLine)
14459     return false;
14460 
14461   return true;
14462 }
14463 
14464 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14465                                  const Stmt *Body,
14466                                  unsigned DiagID) {
14467   // Since this is a syntactic check, don't emit diagnostic for template
14468   // instantiations, this just adds noise.
14469   if (CurrentInstantiationScope)
14470     return;
14471 
14472   // The body should be a null statement.
14473   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14474   if (!NBody)
14475     return;
14476 
14477   // Do the usual checks.
14478   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14479     return;
14480 
14481   Diag(NBody->getSemiLoc(), DiagID);
14482   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14483 }
14484 
14485 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14486                                  const Stmt *PossibleBody) {
14487   assert(!CurrentInstantiationScope); // Ensured by caller
14488 
14489   SourceLocation StmtLoc;
14490   const Stmt *Body;
14491   unsigned DiagID;
14492   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14493     StmtLoc = FS->getRParenLoc();
14494     Body = FS->getBody();
14495     DiagID = diag::warn_empty_for_body;
14496   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14497     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14498     Body = WS->getBody();
14499     DiagID = diag::warn_empty_while_body;
14500   } else
14501     return; // Neither `for' nor `while'.
14502 
14503   // The body should be a null statement.
14504   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14505   if (!NBody)
14506     return;
14507 
14508   // Skip expensive checks if diagnostic is disabled.
14509   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14510     return;
14511 
14512   // Do the usual checks.
14513   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14514     return;
14515 
14516   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14517   // noise level low, emit diagnostics only if for/while is followed by a
14518   // CompoundStmt, e.g.:
14519   //    for (int i = 0; i < n; i++);
14520   //    {
14521   //      a(i);
14522   //    }
14523   // or if for/while is followed by a statement with more indentation
14524   // than for/while itself:
14525   //    for (int i = 0; i < n; i++);
14526   //      a(i);
14527   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14528   if (!ProbableTypo) {
14529     bool BodyColInvalid;
14530     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14531         PossibleBody->getBeginLoc(), &BodyColInvalid);
14532     if (BodyColInvalid)
14533       return;
14534 
14535     bool StmtColInvalid;
14536     unsigned StmtCol =
14537         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14538     if (StmtColInvalid)
14539       return;
14540 
14541     if (BodyCol > StmtCol)
14542       ProbableTypo = true;
14543   }
14544 
14545   if (ProbableTypo) {
14546     Diag(NBody->getSemiLoc(), DiagID);
14547     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14548   }
14549 }
14550 
14551 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14552 
14553 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14554 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14555                              SourceLocation OpLoc) {
14556   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14557     return;
14558 
14559   if (inTemplateInstantiation())
14560     return;
14561 
14562   // Strip parens and casts away.
14563   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14564   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14565 
14566   // Check for a call expression
14567   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14568   if (!CE || CE->getNumArgs() != 1)
14569     return;
14570 
14571   // Check for a call to std::move
14572   if (!CE->isCallToStdMove())
14573     return;
14574 
14575   // Get argument from std::move
14576   RHSExpr = CE->getArg(0);
14577 
14578   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14579   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14580 
14581   // Two DeclRefExpr's, check that the decls are the same.
14582   if (LHSDeclRef && RHSDeclRef) {
14583     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14584       return;
14585     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14586         RHSDeclRef->getDecl()->getCanonicalDecl())
14587       return;
14588 
14589     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14590                                         << LHSExpr->getSourceRange()
14591                                         << RHSExpr->getSourceRange();
14592     return;
14593   }
14594 
14595   // Member variables require a different approach to check for self moves.
14596   // MemberExpr's are the same if every nested MemberExpr refers to the same
14597   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14598   // the base Expr's are CXXThisExpr's.
14599   const Expr *LHSBase = LHSExpr;
14600   const Expr *RHSBase = RHSExpr;
14601   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14602   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14603   if (!LHSME || !RHSME)
14604     return;
14605 
14606   while (LHSME && RHSME) {
14607     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14608         RHSME->getMemberDecl()->getCanonicalDecl())
14609       return;
14610 
14611     LHSBase = LHSME->getBase();
14612     RHSBase = RHSME->getBase();
14613     LHSME = dyn_cast<MemberExpr>(LHSBase);
14614     RHSME = dyn_cast<MemberExpr>(RHSBase);
14615   }
14616 
14617   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14618   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14619   if (LHSDeclRef && RHSDeclRef) {
14620     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14621       return;
14622     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14623         RHSDeclRef->getDecl()->getCanonicalDecl())
14624       return;
14625 
14626     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14627                                         << LHSExpr->getSourceRange()
14628                                         << RHSExpr->getSourceRange();
14629     return;
14630   }
14631 
14632   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14633     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14634                                         << LHSExpr->getSourceRange()
14635                                         << RHSExpr->getSourceRange();
14636 }
14637 
14638 //===--- Layout compatibility ----------------------------------------------//
14639 
14640 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14641 
14642 /// Check if two enumeration types are layout-compatible.
14643 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14644   // C++11 [dcl.enum] p8:
14645   // Two enumeration types are layout-compatible if they have the same
14646   // underlying type.
14647   return ED1->isComplete() && ED2->isComplete() &&
14648          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14649 }
14650 
14651 /// Check if two fields are layout-compatible.
14652 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14653                                FieldDecl *Field2) {
14654   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14655     return false;
14656 
14657   if (Field1->isBitField() != Field2->isBitField())
14658     return false;
14659 
14660   if (Field1->isBitField()) {
14661     // Make sure that the bit-fields are the same length.
14662     unsigned Bits1 = Field1->getBitWidthValue(C);
14663     unsigned Bits2 = Field2->getBitWidthValue(C);
14664 
14665     if (Bits1 != Bits2)
14666       return false;
14667   }
14668 
14669   return true;
14670 }
14671 
14672 /// Check if two standard-layout structs are layout-compatible.
14673 /// (C++11 [class.mem] p17)
14674 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14675                                      RecordDecl *RD2) {
14676   // If both records are C++ classes, check that base classes match.
14677   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14678     // If one of records is a CXXRecordDecl we are in C++ mode,
14679     // thus the other one is a CXXRecordDecl, too.
14680     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14681     // Check number of base classes.
14682     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14683       return false;
14684 
14685     // Check the base classes.
14686     for (CXXRecordDecl::base_class_const_iterator
14687                Base1 = D1CXX->bases_begin(),
14688            BaseEnd1 = D1CXX->bases_end(),
14689               Base2 = D2CXX->bases_begin();
14690          Base1 != BaseEnd1;
14691          ++Base1, ++Base2) {
14692       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14693         return false;
14694     }
14695   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14696     // If only RD2 is a C++ class, it should have zero base classes.
14697     if (D2CXX->getNumBases() > 0)
14698       return false;
14699   }
14700 
14701   // Check the fields.
14702   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14703                              Field2End = RD2->field_end(),
14704                              Field1 = RD1->field_begin(),
14705                              Field1End = RD1->field_end();
14706   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14707     if (!isLayoutCompatible(C, *Field1, *Field2))
14708       return false;
14709   }
14710   if (Field1 != Field1End || Field2 != Field2End)
14711     return false;
14712 
14713   return true;
14714 }
14715 
14716 /// Check if two standard-layout unions are layout-compatible.
14717 /// (C++11 [class.mem] p18)
14718 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14719                                     RecordDecl *RD2) {
14720   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14721   for (auto *Field2 : RD2->fields())
14722     UnmatchedFields.insert(Field2);
14723 
14724   for (auto *Field1 : RD1->fields()) {
14725     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14726         I = UnmatchedFields.begin(),
14727         E = UnmatchedFields.end();
14728 
14729     for ( ; I != E; ++I) {
14730       if (isLayoutCompatible(C, Field1, *I)) {
14731         bool Result = UnmatchedFields.erase(*I);
14732         (void) Result;
14733         assert(Result);
14734         break;
14735       }
14736     }
14737     if (I == E)
14738       return false;
14739   }
14740 
14741   return UnmatchedFields.empty();
14742 }
14743 
14744 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14745                                RecordDecl *RD2) {
14746   if (RD1->isUnion() != RD2->isUnion())
14747     return false;
14748 
14749   if (RD1->isUnion())
14750     return isLayoutCompatibleUnion(C, RD1, RD2);
14751   else
14752     return isLayoutCompatibleStruct(C, RD1, RD2);
14753 }
14754 
14755 /// Check if two types are layout-compatible in C++11 sense.
14756 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14757   if (T1.isNull() || T2.isNull())
14758     return false;
14759 
14760   // C++11 [basic.types] p11:
14761   // If two types T1 and T2 are the same type, then T1 and T2 are
14762   // layout-compatible types.
14763   if (C.hasSameType(T1, T2))
14764     return true;
14765 
14766   T1 = T1.getCanonicalType().getUnqualifiedType();
14767   T2 = T2.getCanonicalType().getUnqualifiedType();
14768 
14769   const Type::TypeClass TC1 = T1->getTypeClass();
14770   const Type::TypeClass TC2 = T2->getTypeClass();
14771 
14772   if (TC1 != TC2)
14773     return false;
14774 
14775   if (TC1 == Type::Enum) {
14776     return isLayoutCompatible(C,
14777                               cast<EnumType>(T1)->getDecl(),
14778                               cast<EnumType>(T2)->getDecl());
14779   } else if (TC1 == Type::Record) {
14780     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14781       return false;
14782 
14783     return isLayoutCompatible(C,
14784                               cast<RecordType>(T1)->getDecl(),
14785                               cast<RecordType>(T2)->getDecl());
14786   }
14787 
14788   return false;
14789 }
14790 
14791 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14792 
14793 /// Given a type tag expression find the type tag itself.
14794 ///
14795 /// \param TypeExpr Type tag expression, as it appears in user's code.
14796 ///
14797 /// \param VD Declaration of an identifier that appears in a type tag.
14798 ///
14799 /// \param MagicValue Type tag magic value.
14800 ///
14801 /// \param isConstantEvaluated wether the evalaution should be performed in
14802 
14803 /// constant context.
14804 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14805                             const ValueDecl **VD, uint64_t *MagicValue,
14806                             bool isConstantEvaluated) {
14807   while(true) {
14808     if (!TypeExpr)
14809       return false;
14810 
14811     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14812 
14813     switch (TypeExpr->getStmtClass()) {
14814     case Stmt::UnaryOperatorClass: {
14815       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14816       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14817         TypeExpr = UO->getSubExpr();
14818         continue;
14819       }
14820       return false;
14821     }
14822 
14823     case Stmt::DeclRefExprClass: {
14824       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14825       *VD = DRE->getDecl();
14826       return true;
14827     }
14828 
14829     case Stmt::IntegerLiteralClass: {
14830       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14831       llvm::APInt MagicValueAPInt = IL->getValue();
14832       if (MagicValueAPInt.getActiveBits() <= 64) {
14833         *MagicValue = MagicValueAPInt.getZExtValue();
14834         return true;
14835       } else
14836         return false;
14837     }
14838 
14839     case Stmt::BinaryConditionalOperatorClass:
14840     case Stmt::ConditionalOperatorClass: {
14841       const AbstractConditionalOperator *ACO =
14842           cast<AbstractConditionalOperator>(TypeExpr);
14843       bool Result;
14844       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14845                                                      isConstantEvaluated)) {
14846         if (Result)
14847           TypeExpr = ACO->getTrueExpr();
14848         else
14849           TypeExpr = ACO->getFalseExpr();
14850         continue;
14851       }
14852       return false;
14853     }
14854 
14855     case Stmt::BinaryOperatorClass: {
14856       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14857       if (BO->getOpcode() == BO_Comma) {
14858         TypeExpr = BO->getRHS();
14859         continue;
14860       }
14861       return false;
14862     }
14863 
14864     default:
14865       return false;
14866     }
14867   }
14868 }
14869 
14870 /// Retrieve the C type corresponding to type tag TypeExpr.
14871 ///
14872 /// \param TypeExpr Expression that specifies a type tag.
14873 ///
14874 /// \param MagicValues Registered magic values.
14875 ///
14876 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14877 ///        kind.
14878 ///
14879 /// \param TypeInfo Information about the corresponding C type.
14880 ///
14881 /// \param isConstantEvaluated wether the evalaution should be performed in
14882 /// constant context.
14883 ///
14884 /// \returns true if the corresponding C type was found.
14885 static bool GetMatchingCType(
14886     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14887     const ASTContext &Ctx,
14888     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14889         *MagicValues,
14890     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14891     bool isConstantEvaluated) {
14892   FoundWrongKind = false;
14893 
14894   // Variable declaration that has type_tag_for_datatype attribute.
14895   const ValueDecl *VD = nullptr;
14896 
14897   uint64_t MagicValue;
14898 
14899   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14900     return false;
14901 
14902   if (VD) {
14903     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14904       if (I->getArgumentKind() != ArgumentKind) {
14905         FoundWrongKind = true;
14906         return false;
14907       }
14908       TypeInfo.Type = I->getMatchingCType();
14909       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14910       TypeInfo.MustBeNull = I->getMustBeNull();
14911       return true;
14912     }
14913     return false;
14914   }
14915 
14916   if (!MagicValues)
14917     return false;
14918 
14919   llvm::DenseMap<Sema::TypeTagMagicValue,
14920                  Sema::TypeTagData>::const_iterator I =
14921       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14922   if (I == MagicValues->end())
14923     return false;
14924 
14925   TypeInfo = I->second;
14926   return true;
14927 }
14928 
14929 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14930                                       uint64_t MagicValue, QualType Type,
14931                                       bool LayoutCompatible,
14932                                       bool MustBeNull) {
14933   if (!TypeTagForDatatypeMagicValues)
14934     TypeTagForDatatypeMagicValues.reset(
14935         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14936 
14937   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14938   (*TypeTagForDatatypeMagicValues)[Magic] =
14939       TypeTagData(Type, LayoutCompatible, MustBeNull);
14940 }
14941 
14942 static bool IsSameCharType(QualType T1, QualType T2) {
14943   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14944   if (!BT1)
14945     return false;
14946 
14947   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14948   if (!BT2)
14949     return false;
14950 
14951   BuiltinType::Kind T1Kind = BT1->getKind();
14952   BuiltinType::Kind T2Kind = BT2->getKind();
14953 
14954   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14955          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14956          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14957          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14958 }
14959 
14960 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14961                                     const ArrayRef<const Expr *> ExprArgs,
14962                                     SourceLocation CallSiteLoc) {
14963   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14964   bool IsPointerAttr = Attr->getIsPointer();
14965 
14966   // Retrieve the argument representing the 'type_tag'.
14967   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14968   if (TypeTagIdxAST >= ExprArgs.size()) {
14969     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14970         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14971     return;
14972   }
14973   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14974   bool FoundWrongKind;
14975   TypeTagData TypeInfo;
14976   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14977                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14978                         TypeInfo, isConstantEvaluated())) {
14979     if (FoundWrongKind)
14980       Diag(TypeTagExpr->getExprLoc(),
14981            diag::warn_type_tag_for_datatype_wrong_kind)
14982         << TypeTagExpr->getSourceRange();
14983     return;
14984   }
14985 
14986   // Retrieve the argument representing the 'arg_idx'.
14987   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14988   if (ArgumentIdxAST >= ExprArgs.size()) {
14989     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14990         << 1 << Attr->getArgumentIdx().getSourceIndex();
14991     return;
14992   }
14993   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14994   if (IsPointerAttr) {
14995     // Skip implicit cast of pointer to `void *' (as a function argument).
14996     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14997       if (ICE->getType()->isVoidPointerType() &&
14998           ICE->getCastKind() == CK_BitCast)
14999         ArgumentExpr = ICE->getSubExpr();
15000   }
15001   QualType ArgumentType = ArgumentExpr->getType();
15002 
15003   // Passing a `void*' pointer shouldn't trigger a warning.
15004   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15005     return;
15006 
15007   if (TypeInfo.MustBeNull) {
15008     // Type tag with matching void type requires a null pointer.
15009     if (!ArgumentExpr->isNullPointerConstant(Context,
15010                                              Expr::NPC_ValueDependentIsNotNull)) {
15011       Diag(ArgumentExpr->getExprLoc(),
15012            diag::warn_type_safety_null_pointer_required)
15013           << ArgumentKind->getName()
15014           << ArgumentExpr->getSourceRange()
15015           << TypeTagExpr->getSourceRange();
15016     }
15017     return;
15018   }
15019 
15020   QualType RequiredType = TypeInfo.Type;
15021   if (IsPointerAttr)
15022     RequiredType = Context.getPointerType(RequiredType);
15023 
15024   bool mismatch = false;
15025   if (!TypeInfo.LayoutCompatible) {
15026     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15027 
15028     // C++11 [basic.fundamental] p1:
15029     // Plain char, signed char, and unsigned char are three distinct types.
15030     //
15031     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15032     // char' depending on the current char signedness mode.
15033     if (mismatch)
15034       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15035                                            RequiredType->getPointeeType())) ||
15036           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15037         mismatch = false;
15038   } else
15039     if (IsPointerAttr)
15040       mismatch = !isLayoutCompatible(Context,
15041                                      ArgumentType->getPointeeType(),
15042                                      RequiredType->getPointeeType());
15043     else
15044       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15045 
15046   if (mismatch)
15047     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15048         << ArgumentType << ArgumentKind
15049         << TypeInfo.LayoutCompatible << RequiredType
15050         << ArgumentExpr->getSourceRange()
15051         << TypeTagExpr->getSourceRange();
15052 }
15053 
15054 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15055                                          CharUnits Alignment) {
15056   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15057 }
15058 
15059 void Sema::DiagnoseMisalignedMembers() {
15060   for (MisalignedMember &m : MisalignedMembers) {
15061     const NamedDecl *ND = m.RD;
15062     if (ND->getName().empty()) {
15063       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15064         ND = TD;
15065     }
15066     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15067         << m.MD << ND << m.E->getSourceRange();
15068   }
15069   MisalignedMembers.clear();
15070 }
15071 
15072 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15073   E = E->IgnoreParens();
15074   if (!T->isPointerType() && !T->isIntegerType())
15075     return;
15076   if (isa<UnaryOperator>(E) &&
15077       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15078     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15079     if (isa<MemberExpr>(Op)) {
15080       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15081       if (MA != MisalignedMembers.end() &&
15082           (T->isIntegerType() ||
15083            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15084                                    Context.getTypeAlignInChars(
15085                                        T->getPointeeType()) <= MA->Alignment))))
15086         MisalignedMembers.erase(MA);
15087     }
15088   }
15089 }
15090 
15091 void Sema::RefersToMemberWithReducedAlignment(
15092     Expr *E,
15093     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15094         Action) {
15095   const auto *ME = dyn_cast<MemberExpr>(E);
15096   if (!ME)
15097     return;
15098 
15099   // No need to check expressions with an __unaligned-qualified type.
15100   if (E->getType().getQualifiers().hasUnaligned())
15101     return;
15102 
15103   // For a chain of MemberExpr like "a.b.c.d" this list
15104   // will keep FieldDecl's like [d, c, b].
15105   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15106   const MemberExpr *TopME = nullptr;
15107   bool AnyIsPacked = false;
15108   do {
15109     QualType BaseType = ME->getBase()->getType();
15110     if (BaseType->isDependentType())
15111       return;
15112     if (ME->isArrow())
15113       BaseType = BaseType->getPointeeType();
15114     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15115     if (RD->isInvalidDecl())
15116       return;
15117 
15118     ValueDecl *MD = ME->getMemberDecl();
15119     auto *FD = dyn_cast<FieldDecl>(MD);
15120     // We do not care about non-data members.
15121     if (!FD || FD->isInvalidDecl())
15122       return;
15123 
15124     AnyIsPacked =
15125         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15126     ReverseMemberChain.push_back(FD);
15127 
15128     TopME = ME;
15129     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15130   } while (ME);
15131   assert(TopME && "We did not compute a topmost MemberExpr!");
15132 
15133   // Not the scope of this diagnostic.
15134   if (!AnyIsPacked)
15135     return;
15136 
15137   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15138   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15139   // TODO: The innermost base of the member expression may be too complicated.
15140   // For now, just disregard these cases. This is left for future
15141   // improvement.
15142   if (!DRE && !isa<CXXThisExpr>(TopBase))
15143       return;
15144 
15145   // Alignment expected by the whole expression.
15146   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15147 
15148   // No need to do anything else with this case.
15149   if (ExpectedAlignment.isOne())
15150     return;
15151 
15152   // Synthesize offset of the whole access.
15153   CharUnits Offset;
15154   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15155        I++) {
15156     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15157   }
15158 
15159   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15160   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15161       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15162 
15163   // The base expression of the innermost MemberExpr may give
15164   // stronger guarantees than the class containing the member.
15165   if (DRE && !TopME->isArrow()) {
15166     const ValueDecl *VD = DRE->getDecl();
15167     if (!VD->getType()->isReferenceType())
15168       CompleteObjectAlignment =
15169           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15170   }
15171 
15172   // Check if the synthesized offset fulfills the alignment.
15173   if (Offset % ExpectedAlignment != 0 ||
15174       // It may fulfill the offset it but the effective alignment may still be
15175       // lower than the expected expression alignment.
15176       CompleteObjectAlignment < ExpectedAlignment) {
15177     // If this happens, we want to determine a sensible culprit of this.
15178     // Intuitively, watching the chain of member expressions from right to
15179     // left, we start with the required alignment (as required by the field
15180     // type) but some packed attribute in that chain has reduced the alignment.
15181     // It may happen that another packed structure increases it again. But if
15182     // we are here such increase has not been enough. So pointing the first
15183     // FieldDecl that either is packed or else its RecordDecl is,
15184     // seems reasonable.
15185     FieldDecl *FD = nullptr;
15186     CharUnits Alignment;
15187     for (FieldDecl *FDI : ReverseMemberChain) {
15188       if (FDI->hasAttr<PackedAttr>() ||
15189           FDI->getParent()->hasAttr<PackedAttr>()) {
15190         FD = FDI;
15191         Alignment = std::min(
15192             Context.getTypeAlignInChars(FD->getType()),
15193             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15194         break;
15195       }
15196     }
15197     assert(FD && "We did not find a packed FieldDecl!");
15198     Action(E, FD->getParent(), FD, Alignment);
15199   }
15200 }
15201 
15202 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15203   using namespace std::placeholders;
15204 
15205   RefersToMemberWithReducedAlignment(
15206       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15207                      _2, _3, _4));
15208 }
15209 
15210 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15211                                             ExprResult CallResult) {
15212   if (checkArgCount(*this, TheCall, 1))
15213     return ExprError();
15214 
15215   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15216   if (MatrixArg.isInvalid())
15217     return MatrixArg;
15218   Expr *Matrix = MatrixArg.get();
15219 
15220   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15221   if (!MType) {
15222     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15223     return ExprError();
15224   }
15225 
15226   // Create returned matrix type by swapping rows and columns of the argument
15227   // matrix type.
15228   QualType ResultType = Context.getConstantMatrixType(
15229       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15230 
15231   // Change the return type to the type of the returned matrix.
15232   TheCall->setType(ResultType);
15233 
15234   // Update call argument to use the possibly converted matrix argument.
15235   TheCall->setArg(0, Matrix);
15236   return CallResult;
15237 }
15238 
15239 // Get and verify the matrix dimensions.
15240 static llvm::Optional<unsigned>
15241 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15242   llvm::APSInt Value(64);
15243   SourceLocation ErrorPos;
15244   if (!Expr->isIntegerConstantExpr(Value, S.Context, &ErrorPos)) {
15245     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15246         << Name;
15247     return {};
15248   }
15249   uint64_t Dim = Value.getZExtValue();
15250   if (!ConstantMatrixType::isDimensionValid(Dim)) {
15251     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15252         << Name << ConstantMatrixType::getMaxElementsPerDimension();
15253     return {};
15254   }
15255   return Dim;
15256 }
15257 
15258 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15259                                                   ExprResult CallResult) {
15260   if (!getLangOpts().MatrixTypes) {
15261     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15262     return ExprError();
15263   }
15264 
15265   if (checkArgCount(*this, TheCall, 4))
15266     return ExprError();
15267 
15268   Expr *PtrExpr = TheCall->getArg(0);
15269   Expr *RowsExpr = TheCall->getArg(1);
15270   Expr *ColumnsExpr = TheCall->getArg(2);
15271   Expr *StrideExpr = TheCall->getArg(3);
15272 
15273   bool ArgError = false;
15274 
15275   // Check pointer argument.
15276   {
15277     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15278     if (PtrConv.isInvalid())
15279       return PtrConv;
15280     PtrExpr = PtrConv.get();
15281     TheCall->setArg(0, PtrExpr);
15282     if (PtrExpr->isTypeDependent()) {
15283       TheCall->setType(Context.DependentTy);
15284       return TheCall;
15285     }
15286   }
15287 
15288   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15289   QualType ElementTy;
15290   if (!PtrTy) {
15291     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15292         << "first";
15293     ArgError = true;
15294   } else {
15295     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15296 
15297     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15298       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15299           << "first";
15300       ArgError = true;
15301     }
15302   }
15303 
15304   // Apply default Lvalue conversions and convert the expression to size_t.
15305   auto ApplyArgumentConversions = [this](Expr *E) {
15306     ExprResult Conv = DefaultLvalueConversion(E);
15307     if (Conv.isInvalid())
15308       return Conv;
15309 
15310     return tryConvertExprToType(Conv.get(), Context.getSizeType());
15311   };
15312 
15313   // Apply conversion to row and column expressions.
15314   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15315   if (!RowsConv.isInvalid()) {
15316     RowsExpr = RowsConv.get();
15317     TheCall->setArg(1, RowsExpr);
15318   } else
15319     RowsExpr = nullptr;
15320 
15321   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
15322   if (!ColumnsConv.isInvalid()) {
15323     ColumnsExpr = ColumnsConv.get();
15324     TheCall->setArg(2, ColumnsExpr);
15325   } else
15326     ColumnsExpr = nullptr;
15327 
15328   // If any any part of the result matrix type is still pending, just use
15329   // Context.DependentTy, until all parts are resolved.
15330   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
15331       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
15332     TheCall->setType(Context.DependentTy);
15333     return CallResult;
15334   }
15335 
15336   // Check row and column dimenions.
15337   llvm::Optional<unsigned> MaybeRows;
15338   if (RowsExpr)
15339     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
15340 
15341   llvm::Optional<unsigned> MaybeColumns;
15342   if (ColumnsExpr)
15343     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
15344 
15345   // Check stride argument.
15346   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
15347   if (StrideConv.isInvalid())
15348     return ExprError();
15349   StrideExpr = StrideConv.get();
15350   TheCall->setArg(3, StrideExpr);
15351 
15352   llvm::APSInt Value(64);
15353   if (MaybeRows && StrideExpr->isIntegerConstantExpr(Value, Context)) {
15354     uint64_t Stride = Value.getZExtValue();
15355     if (Stride < *MaybeRows) {
15356       Diag(StrideExpr->getBeginLoc(),
15357            diag::err_builtin_matrix_stride_too_small);
15358       ArgError = true;
15359     }
15360   }
15361 
15362   if (ArgError || !MaybeRows || !MaybeColumns)
15363     return ExprError();
15364 
15365   TheCall->setType(
15366       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
15367   return CallResult;
15368 }
15369 
15370 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
15371                                                    ExprResult CallResult) {
15372   if (checkArgCount(*this, TheCall, 3))
15373     return ExprError();
15374 
15375   Expr *MatrixExpr = TheCall->getArg(0);
15376   Expr *PtrExpr = TheCall->getArg(1);
15377   Expr *StrideExpr = TheCall->getArg(2);
15378 
15379   bool ArgError = false;
15380 
15381   {
15382     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
15383     if (MatrixConv.isInvalid())
15384       return MatrixConv;
15385     MatrixExpr = MatrixConv.get();
15386     TheCall->setArg(0, MatrixExpr);
15387   }
15388   if (MatrixExpr->isTypeDependent()) {
15389     TheCall->setType(Context.DependentTy);
15390     return TheCall;
15391   }
15392 
15393   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
15394   if (!MatrixTy) {
15395     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
15396     ArgError = true;
15397   }
15398 
15399   {
15400     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15401     if (PtrConv.isInvalid())
15402       return PtrConv;
15403     PtrExpr = PtrConv.get();
15404     TheCall->setArg(1, PtrExpr);
15405     if (PtrExpr->isTypeDependent()) {
15406       TheCall->setType(Context.DependentTy);
15407       return TheCall;
15408     }
15409   }
15410 
15411   // Check pointer argument.
15412   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15413   if (!PtrTy) {
15414     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15415         << "second";
15416     ArgError = true;
15417   } else {
15418     QualType ElementTy = PtrTy->getPointeeType();
15419     if (ElementTy.isConstQualified()) {
15420       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
15421       ArgError = true;
15422     }
15423     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
15424     if (MatrixTy &&
15425         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
15426       Diag(PtrExpr->getBeginLoc(),
15427            diag::err_builtin_matrix_pointer_arg_mismatch)
15428           << ElementTy << MatrixTy->getElementType();
15429       ArgError = true;
15430     }
15431   }
15432 
15433   // Apply default Lvalue conversions and convert the stride expression to
15434   // size_t.
15435   {
15436     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
15437     if (StrideConv.isInvalid())
15438       return StrideConv;
15439 
15440     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
15441     if (StrideConv.isInvalid())
15442       return StrideConv;
15443     StrideExpr = StrideConv.get();
15444     TheCall->setArg(2, StrideExpr);
15445   }
15446 
15447   // Check stride argument.
15448   llvm::APSInt Value(64);
15449   if (MatrixTy && StrideExpr->isIntegerConstantExpr(Value, Context)) {
15450     uint64_t Stride = Value.getZExtValue();
15451     if (Stride < MatrixTy->getNumRows()) {
15452       Diag(StrideExpr->getBeginLoc(),
15453            diag::err_builtin_matrix_stride_too_small);
15454       ArgError = true;
15455     }
15456   }
15457 
15458   if (ArgError)
15459     return ExprError();
15460 
15461   return CallResult;
15462 }
15463