1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSet.h"
79 #include "llvm/ADT/StringSwitch.h"
80 #include "llvm/ADT/Triple.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include <algorithm>
92 #include <bitset>
93 #include <cassert>
94 #include <cstddef>
95 #include <cstdint>
96 #include <functional>
97 #include <limits>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 
102 using namespace clang;
103 using namespace sema;
104 
105 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
106                                                     unsigned ByteNo) const {
107   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
108                                Context.getTargetInfo());
109 }
110 
111 /// Checks that a call expression's argument count is the desired number.
112 /// This is useful when doing custom type-checking.  Returns true on error.
113 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
114   unsigned argCount = call->getNumArgs();
115   if (argCount == desiredArgCount) return false;
116 
117   if (argCount < desiredArgCount)
118     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
119            << 0 /*function call*/ << desiredArgCount << argCount
120            << call->getSourceRange();
121 
122   // Highlight all the excess arguments.
123   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
124                     call->getArg(argCount - 1)->getEndLoc());
125 
126   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
127     << 0 /*function call*/ << desiredArgCount << argCount
128     << call->getArg(1)->getSourceRange();
129 }
130 
131 /// Check that the first argument to __builtin_annotation is an integer
132 /// and the second argument is a non-wide string literal.
133 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
134   if (checkArgCount(S, TheCall, 2))
135     return true;
136 
137   // First argument should be an integer.
138   Expr *ValArg = TheCall->getArg(0);
139   QualType Ty = ValArg->getType();
140   if (!Ty->isIntegerType()) {
141     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
142         << ValArg->getSourceRange();
143     return true;
144   }
145 
146   // Second argument should be a constant string.
147   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
148   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
149   if (!Literal || !Literal->isAscii()) {
150     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
151         << StrArg->getSourceRange();
152     return true;
153   }
154 
155   TheCall->setType(Ty);
156   return false;
157 }
158 
159 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
160   // We need at least one argument.
161   if (TheCall->getNumArgs() < 1) {
162     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
163         << 0 << 1 << TheCall->getNumArgs()
164         << TheCall->getCallee()->getSourceRange();
165     return true;
166   }
167 
168   // All arguments should be wide string literals.
169   for (Expr *Arg : TheCall->arguments()) {
170     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
171     if (!Literal || !Literal->isWide()) {
172       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
173           << Arg->getSourceRange();
174       return true;
175     }
176   }
177 
178   return false;
179 }
180 
181 /// Check that the argument to __builtin_addressof is a glvalue, and set the
182 /// result type to the corresponding pointer type.
183 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
184   if (checkArgCount(S, TheCall, 1))
185     return true;
186 
187   ExprResult Arg(TheCall->getArg(0));
188   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
189   if (ResultType.isNull())
190     return true;
191 
192   TheCall->setArg(0, Arg.get());
193   TheCall->setType(ResultType);
194   return false;
195 }
196 
197 /// Check the number of arguments and set the result type to
198 /// the argument type.
199 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
200   if (checkArgCount(S, TheCall, 1))
201     return true;
202 
203   TheCall->setType(TheCall->getArg(0)->getType());
204   return false;
205 }
206 
207 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
208 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
209 /// type (but not a function pointer) and that the alignment is a power-of-two.
210 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
211   if (checkArgCount(S, TheCall, 2))
212     return true;
213 
214   clang::Expr *Source = TheCall->getArg(0);
215   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
216 
217   auto IsValidIntegerType = [](QualType Ty) {
218     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
219   };
220   QualType SrcTy = Source->getType();
221   // We should also be able to use it with arrays (but not functions!).
222   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
223     SrcTy = S.Context.getDecayedType(SrcTy);
224   }
225   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
226       SrcTy->isFunctionPointerType()) {
227     // FIXME: this is not quite the right error message since we don't allow
228     // floating point types, or member pointers.
229     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
230         << SrcTy;
231     return true;
232   }
233 
234   clang::Expr *AlignOp = TheCall->getArg(1);
235   if (!IsValidIntegerType(AlignOp->getType())) {
236     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
237         << AlignOp->getType();
238     return true;
239   }
240   Expr::EvalResult AlignResult;
241   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
242   // We can't check validity of alignment if it is value dependent.
243   if (!AlignOp->isValueDependent() &&
244       AlignOp->EvaluateAsInt(AlignResult, S.Context,
245                              Expr::SE_AllowSideEffects)) {
246     llvm::APSInt AlignValue = AlignResult.Val.getInt();
247     llvm::APSInt MaxValue(
248         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
249     if (AlignValue < 1) {
250       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
251       return true;
252     }
253     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
254       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
255           << MaxValue.toString(10);
256       return true;
257     }
258     if (!AlignValue.isPowerOf2()) {
259       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
260       return true;
261     }
262     if (AlignValue == 1) {
263       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
264           << IsBooleanAlignBuiltin;
265     }
266   }
267 
268   ExprResult SrcArg = S.PerformCopyInitialization(
269       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
270       SourceLocation(), Source);
271   if (SrcArg.isInvalid())
272     return true;
273   TheCall->setArg(0, SrcArg.get());
274   ExprResult AlignArg =
275       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
276                                       S.Context, AlignOp->getType(), false),
277                                   SourceLocation(), AlignOp);
278   if (AlignArg.isInvalid())
279     return true;
280   TheCall->setArg(1, AlignArg.get());
281   // For align_up/align_down, the return type is the same as the (potentially
282   // decayed) argument type including qualifiers. For is_aligned(), the result
283   // is always bool.
284   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
285   return false;
286 }
287 
288 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
289                                 unsigned BuiltinID) {
290   if (checkArgCount(S, TheCall, 3))
291     return true;
292 
293   // First two arguments should be integers.
294   for (unsigned I = 0; I < 2; ++I) {
295     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
296     if (Arg.isInvalid()) return true;
297     TheCall->setArg(I, Arg.get());
298 
299     QualType Ty = Arg.get()->getType();
300     if (!Ty->isIntegerType()) {
301       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
302           << Ty << Arg.get()->getSourceRange();
303       return true;
304     }
305   }
306 
307   // Third argument should be a pointer to a non-const integer.
308   // IRGen correctly handles volatile, restrict, and address spaces, and
309   // the other qualifiers aren't possible.
310   {
311     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
312     if (Arg.isInvalid()) return true;
313     TheCall->setArg(2, Arg.get());
314 
315     QualType Ty = Arg.get()->getType();
316     const auto *PtrTy = Ty->getAs<PointerType>();
317     if (!PtrTy ||
318         !PtrTy->getPointeeType()->isIntegerType() ||
319         PtrTy->getPointeeType().isConstQualified()) {
320       S.Diag(Arg.get()->getBeginLoc(),
321              diag::err_overflow_builtin_must_be_ptr_int)
322         << Ty << Arg.get()->getSourceRange();
323       return true;
324     }
325   }
326 
327   // Disallow signed ExtIntType args larger than 128 bits to mul function until
328   // we improve backend support.
329   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
330     for (unsigned I = 0; I < 3; ++I) {
331       const auto Arg = TheCall->getArg(I);
332       // Third argument will be a pointer.
333       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
334       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
335           S.getASTContext().getIntWidth(Ty) > 128)
336         return S.Diag(Arg->getBeginLoc(),
337                       diag::err_overflow_builtin_ext_int_max_size)
338                << 128;
339     }
340   }
341 
342   return false;
343 }
344 
345 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
346   if (checkArgCount(S, BuiltinCall, 2))
347     return true;
348 
349   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
350   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
351   Expr *Call = BuiltinCall->getArg(0);
352   Expr *Chain = BuiltinCall->getArg(1);
353 
354   if (Call->getStmtClass() != Stmt::CallExprClass) {
355     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
356         << Call->getSourceRange();
357     return true;
358   }
359 
360   auto CE = cast<CallExpr>(Call);
361   if (CE->getCallee()->getType()->isBlockPointerType()) {
362     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
363         << Call->getSourceRange();
364     return true;
365   }
366 
367   const Decl *TargetDecl = CE->getCalleeDecl();
368   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
369     if (FD->getBuiltinID()) {
370       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
371           << Call->getSourceRange();
372       return true;
373     }
374 
375   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
376     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
377         << Call->getSourceRange();
378     return true;
379   }
380 
381   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
382   if (ChainResult.isInvalid())
383     return true;
384   if (!ChainResult.get()->getType()->isPointerType()) {
385     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
386         << Chain->getSourceRange();
387     return true;
388   }
389 
390   QualType ReturnTy = CE->getCallReturnType(S.Context);
391   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
392   QualType BuiltinTy = S.Context.getFunctionType(
393       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
394   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
395 
396   Builtin =
397       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
398 
399   BuiltinCall->setType(CE->getType());
400   BuiltinCall->setValueKind(CE->getValueKind());
401   BuiltinCall->setObjectKind(CE->getObjectKind());
402   BuiltinCall->setCallee(Builtin);
403   BuiltinCall->setArg(1, ChainResult.get());
404 
405   return false;
406 }
407 
408 namespace {
409 
410 class EstimateSizeFormatHandler
411     : public analyze_format_string::FormatStringHandler {
412   size_t Size;
413 
414 public:
415   EstimateSizeFormatHandler(StringRef Format)
416       : Size(std::min(Format.find(0), Format.size()) +
417              1 /* null byte always written by sprintf */) {}
418 
419   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
420                              const char *, unsigned SpecifierLen) override {
421 
422     const size_t FieldWidth = computeFieldWidth(FS);
423     const size_t Precision = computePrecision(FS);
424 
425     // The actual format.
426     switch (FS.getConversionSpecifier().getKind()) {
427     // Just a char.
428     case analyze_format_string::ConversionSpecifier::cArg:
429     case analyze_format_string::ConversionSpecifier::CArg:
430       Size += std::max(FieldWidth, (size_t)1);
431       break;
432     // Just an integer.
433     case analyze_format_string::ConversionSpecifier::dArg:
434     case analyze_format_string::ConversionSpecifier::DArg:
435     case analyze_format_string::ConversionSpecifier::iArg:
436     case analyze_format_string::ConversionSpecifier::oArg:
437     case analyze_format_string::ConversionSpecifier::OArg:
438     case analyze_format_string::ConversionSpecifier::uArg:
439     case analyze_format_string::ConversionSpecifier::UArg:
440     case analyze_format_string::ConversionSpecifier::xArg:
441     case analyze_format_string::ConversionSpecifier::XArg:
442       Size += std::max(FieldWidth, Precision);
443       break;
444 
445     // %g style conversion switches between %f or %e style dynamically.
446     // %f always takes less space, so default to it.
447     case analyze_format_string::ConversionSpecifier::gArg:
448     case analyze_format_string::ConversionSpecifier::GArg:
449 
450     // Floating point number in the form '[+]ddd.ddd'.
451     case analyze_format_string::ConversionSpecifier::fArg:
452     case analyze_format_string::ConversionSpecifier::FArg:
453       Size += std::max(FieldWidth, 1 /* integer part */ +
454                                        (Precision ? 1 + Precision
455                                                   : 0) /* period + decimal */);
456       break;
457 
458     // Floating point number in the form '[-]d.ddde[+-]dd'.
459     case analyze_format_string::ConversionSpecifier::eArg:
460     case analyze_format_string::ConversionSpecifier::EArg:
461       Size +=
462           std::max(FieldWidth,
463                    1 /* integer part */ +
464                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
465                        1 /* e or E letter */ + 2 /* exponent */);
466       break;
467 
468     // Floating point number in the form '[-]0xh.hhhhp±dd'.
469     case analyze_format_string::ConversionSpecifier::aArg:
470     case analyze_format_string::ConversionSpecifier::AArg:
471       Size +=
472           std::max(FieldWidth,
473                    2 /* 0x */ + 1 /* integer part */ +
474                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
475                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
476       break;
477 
478     // Just a string.
479     case analyze_format_string::ConversionSpecifier::sArg:
480     case analyze_format_string::ConversionSpecifier::SArg:
481       Size += FieldWidth;
482       break;
483 
484     // Just a pointer in the form '0xddd'.
485     case analyze_format_string::ConversionSpecifier::pArg:
486       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
487       break;
488 
489     // A plain percent.
490     case analyze_format_string::ConversionSpecifier::PercentArg:
491       Size += 1;
492       break;
493 
494     default:
495       break;
496     }
497 
498     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
499 
500     if (FS.hasAlternativeForm()) {
501       switch (FS.getConversionSpecifier().getKind()) {
502       default:
503         break;
504       // Force a leading '0'.
505       case analyze_format_string::ConversionSpecifier::oArg:
506         Size += 1;
507         break;
508       // Force a leading '0x'.
509       case analyze_format_string::ConversionSpecifier::xArg:
510       case analyze_format_string::ConversionSpecifier::XArg:
511         Size += 2;
512         break;
513       // Force a period '.' before decimal, even if precision is 0.
514       case analyze_format_string::ConversionSpecifier::aArg:
515       case analyze_format_string::ConversionSpecifier::AArg:
516       case analyze_format_string::ConversionSpecifier::eArg:
517       case analyze_format_string::ConversionSpecifier::EArg:
518       case analyze_format_string::ConversionSpecifier::fArg:
519       case analyze_format_string::ConversionSpecifier::FArg:
520       case analyze_format_string::ConversionSpecifier::gArg:
521       case analyze_format_string::ConversionSpecifier::GArg:
522         Size += (Precision ? 0 : 1);
523         break;
524       }
525     }
526     assert(SpecifierLen <= Size && "no underflow");
527     Size -= SpecifierLen;
528     return true;
529   }
530 
531   size_t getSizeLowerBound() const { return Size; }
532 
533 private:
534   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
535     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
536     size_t FieldWidth = 0;
537     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
538       FieldWidth = FW.getConstantAmount();
539     return FieldWidth;
540   }
541 
542   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
543     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
544     size_t Precision = 0;
545 
546     // See man 3 printf for default precision value based on the specifier.
547     switch (FW.getHowSpecified()) {
548     case analyze_format_string::OptionalAmount::NotSpecified:
549       switch (FS.getConversionSpecifier().getKind()) {
550       default:
551         break;
552       case analyze_format_string::ConversionSpecifier::dArg: // %d
553       case analyze_format_string::ConversionSpecifier::DArg: // %D
554       case analyze_format_string::ConversionSpecifier::iArg: // %i
555         Precision = 1;
556         break;
557       case analyze_format_string::ConversionSpecifier::oArg: // %d
558       case analyze_format_string::ConversionSpecifier::OArg: // %D
559       case analyze_format_string::ConversionSpecifier::uArg: // %d
560       case analyze_format_string::ConversionSpecifier::UArg: // %D
561       case analyze_format_string::ConversionSpecifier::xArg: // %d
562       case analyze_format_string::ConversionSpecifier::XArg: // %D
563         Precision = 1;
564         break;
565       case analyze_format_string::ConversionSpecifier::fArg: // %f
566       case analyze_format_string::ConversionSpecifier::FArg: // %F
567       case analyze_format_string::ConversionSpecifier::eArg: // %e
568       case analyze_format_string::ConversionSpecifier::EArg: // %E
569       case analyze_format_string::ConversionSpecifier::gArg: // %g
570       case analyze_format_string::ConversionSpecifier::GArg: // %G
571         Precision = 6;
572         break;
573       case analyze_format_string::ConversionSpecifier::pArg: // %d
574         Precision = 1;
575         break;
576       }
577       break;
578     case analyze_format_string::OptionalAmount::Constant:
579       Precision = FW.getConstantAmount();
580       break;
581     default:
582       break;
583     }
584     return Precision;
585   }
586 };
587 
588 } // namespace
589 
590 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
591 /// __builtin_*_chk function, then use the object size argument specified in the
592 /// source. Otherwise, infer the object size using __builtin_object_size.
593 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
594                                                CallExpr *TheCall) {
595   // FIXME: There are some more useful checks we could be doing here:
596   //  - Evaluate strlen of strcpy arguments, use as object size.
597 
598   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
599       isConstantEvaluated())
600     return;
601 
602   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
603   if (!BuiltinID)
604     return;
605 
606   const TargetInfo &TI = getASTContext().getTargetInfo();
607   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
608 
609   unsigned DiagID = 0;
610   bool IsChkVariant = false;
611   Optional<llvm::APSInt> UsedSize;
612   unsigned SizeIndex, ObjectIndex;
613   switch (BuiltinID) {
614   default:
615     return;
616   case Builtin::BIsprintf:
617   case Builtin::BI__builtin___sprintf_chk: {
618     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
619     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
620 
621     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
622 
623       if (!Format->isAscii() && !Format->isUTF8())
624         return;
625 
626       StringRef FormatStrRef = Format->getString();
627       EstimateSizeFormatHandler H(FormatStrRef);
628       const char *FormatBytes = FormatStrRef.data();
629       const ConstantArrayType *T =
630           Context.getAsConstantArrayType(Format->getType());
631       assert(T && "String literal not of constant array type!");
632       size_t TypeSize = T->getSize().getZExtValue();
633 
634       // In case there's a null byte somewhere.
635       size_t StrLen =
636           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
637       if (!analyze_format_string::ParsePrintfString(
638               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
639               Context.getTargetInfo(), false)) {
640         DiagID = diag::warn_fortify_source_format_overflow;
641         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
642                        .extOrTrunc(SizeTypeWidth);
643         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
644           IsChkVariant = true;
645           ObjectIndex = 2;
646         } else {
647           IsChkVariant = false;
648           ObjectIndex = 0;
649         }
650         break;
651       }
652     }
653     return;
654   }
655   case Builtin::BI__builtin___memcpy_chk:
656   case Builtin::BI__builtin___memmove_chk:
657   case Builtin::BI__builtin___memset_chk:
658   case Builtin::BI__builtin___strlcat_chk:
659   case Builtin::BI__builtin___strlcpy_chk:
660   case Builtin::BI__builtin___strncat_chk:
661   case Builtin::BI__builtin___strncpy_chk:
662   case Builtin::BI__builtin___stpncpy_chk:
663   case Builtin::BI__builtin___memccpy_chk:
664   case Builtin::BI__builtin___mempcpy_chk: {
665     DiagID = diag::warn_builtin_chk_overflow;
666     IsChkVariant = true;
667     SizeIndex = TheCall->getNumArgs() - 2;
668     ObjectIndex = TheCall->getNumArgs() - 1;
669     break;
670   }
671 
672   case Builtin::BI__builtin___snprintf_chk:
673   case Builtin::BI__builtin___vsnprintf_chk: {
674     DiagID = diag::warn_builtin_chk_overflow;
675     IsChkVariant = true;
676     SizeIndex = 1;
677     ObjectIndex = 3;
678     break;
679   }
680 
681   case Builtin::BIstrncat:
682   case Builtin::BI__builtin_strncat:
683   case Builtin::BIstrncpy:
684   case Builtin::BI__builtin_strncpy:
685   case Builtin::BIstpncpy:
686   case Builtin::BI__builtin_stpncpy: {
687     // Whether these functions overflow depends on the runtime strlen of the
688     // string, not just the buffer size, so emitting the "always overflow"
689     // diagnostic isn't quite right. We should still diagnose passing a buffer
690     // size larger than the destination buffer though; this is a runtime abort
691     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
692     DiagID = diag::warn_fortify_source_size_mismatch;
693     SizeIndex = TheCall->getNumArgs() - 1;
694     ObjectIndex = 0;
695     break;
696   }
697 
698   case Builtin::BImemcpy:
699   case Builtin::BI__builtin_memcpy:
700   case Builtin::BImemmove:
701   case Builtin::BI__builtin_memmove:
702   case Builtin::BImemset:
703   case Builtin::BI__builtin_memset:
704   case Builtin::BImempcpy:
705   case Builtin::BI__builtin_mempcpy: {
706     DiagID = diag::warn_fortify_source_overflow;
707     SizeIndex = TheCall->getNumArgs() - 1;
708     ObjectIndex = 0;
709     break;
710   }
711   case Builtin::BIsnprintf:
712   case Builtin::BI__builtin_snprintf:
713   case Builtin::BIvsnprintf:
714   case Builtin::BI__builtin_vsnprintf: {
715     DiagID = diag::warn_fortify_source_size_mismatch;
716     SizeIndex = 1;
717     ObjectIndex = 0;
718     break;
719   }
720   }
721 
722   llvm::APSInt ObjectSize;
723   // For __builtin___*_chk, the object size is explicitly provided by the caller
724   // (usually using __builtin_object_size). Use that value to check this call.
725   if (IsChkVariant) {
726     Expr::EvalResult Result;
727     Expr *SizeArg = TheCall->getArg(ObjectIndex);
728     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
729       return;
730     ObjectSize = Result.Val.getInt();
731 
732   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
733   } else {
734     // If the parameter has a pass_object_size attribute, then we should use its
735     // (potentially) more strict checking mode. Otherwise, conservatively assume
736     // type 0.
737     int BOSType = 0;
738     if (const auto *POS =
739             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
740       BOSType = POS->getType();
741 
742     Expr *ObjArg = TheCall->getArg(ObjectIndex);
743     uint64_t Result;
744     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
745       return;
746     // Get the object size in the target's size_t width.
747     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
748   }
749 
750   // Evaluate the number of bytes of the object that this call will use.
751   if (!UsedSize) {
752     Expr::EvalResult Result;
753     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
754     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
755       return;
756     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
757   }
758 
759   if (UsedSize.getValue().ule(ObjectSize))
760     return;
761 
762   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
763   // Skim off the details of whichever builtin was called to produce a better
764   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
765   if (IsChkVariant) {
766     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
767     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
768   } else if (FunctionName.startswith("__builtin_")) {
769     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
770   }
771 
772   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
773                       PDiag(DiagID)
774                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
775                           << UsedSize.getValue().toString(/*Radix=*/10));
776 }
777 
778 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
779                                      Scope::ScopeFlags NeededScopeFlags,
780                                      unsigned DiagID) {
781   // Scopes aren't available during instantiation. Fortunately, builtin
782   // functions cannot be template args so they cannot be formed through template
783   // instantiation. Therefore checking once during the parse is sufficient.
784   if (SemaRef.inTemplateInstantiation())
785     return false;
786 
787   Scope *S = SemaRef.getCurScope();
788   while (S && !S->isSEHExceptScope())
789     S = S->getParent();
790   if (!S || !(S->getFlags() & NeededScopeFlags)) {
791     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
792     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
793         << DRE->getDecl()->getIdentifier();
794     return true;
795   }
796 
797   return false;
798 }
799 
800 static inline bool isBlockPointer(Expr *Arg) {
801   return Arg->getType()->isBlockPointerType();
802 }
803 
804 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
805 /// void*, which is a requirement of device side enqueue.
806 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
807   const BlockPointerType *BPT =
808       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
809   ArrayRef<QualType> Params =
810       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
811   unsigned ArgCounter = 0;
812   bool IllegalParams = false;
813   // Iterate through the block parameters until either one is found that is not
814   // a local void*, or the block is valid.
815   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
816        I != E; ++I, ++ArgCounter) {
817     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
818         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
819             LangAS::opencl_local) {
820       // Get the location of the error. If a block literal has been passed
821       // (BlockExpr) then we can point straight to the offending argument,
822       // else we just point to the variable reference.
823       SourceLocation ErrorLoc;
824       if (isa<BlockExpr>(BlockArg)) {
825         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
826         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
827       } else if (isa<DeclRefExpr>(BlockArg)) {
828         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
829       }
830       S.Diag(ErrorLoc,
831              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
832       IllegalParams = true;
833     }
834   }
835 
836   return IllegalParams;
837 }
838 
839 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
840   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
841     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
842         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
843     return true;
844   }
845   return false;
846 }
847 
848 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
849   if (checkArgCount(S, TheCall, 2))
850     return true;
851 
852   if (checkOpenCLSubgroupExt(S, TheCall))
853     return true;
854 
855   // First argument is an ndrange_t type.
856   Expr *NDRangeArg = TheCall->getArg(0);
857   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
858     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
859         << TheCall->getDirectCallee() << "'ndrange_t'";
860     return true;
861   }
862 
863   Expr *BlockArg = TheCall->getArg(1);
864   if (!isBlockPointer(BlockArg)) {
865     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
866         << TheCall->getDirectCallee() << "block";
867     return true;
868   }
869   return checkOpenCLBlockArgs(S, BlockArg);
870 }
871 
872 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
873 /// get_kernel_work_group_size
874 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
875 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
876   if (checkArgCount(S, TheCall, 1))
877     return true;
878 
879   Expr *BlockArg = TheCall->getArg(0);
880   if (!isBlockPointer(BlockArg)) {
881     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
882         << TheCall->getDirectCallee() << "block";
883     return true;
884   }
885   return checkOpenCLBlockArgs(S, BlockArg);
886 }
887 
888 /// Diagnose integer type and any valid implicit conversion to it.
889 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
890                                       const QualType &IntType);
891 
892 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
893                                             unsigned Start, unsigned End) {
894   bool IllegalParams = false;
895   for (unsigned I = Start; I <= End; ++I)
896     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
897                                               S.Context.getSizeType());
898   return IllegalParams;
899 }
900 
901 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
902 /// 'local void*' parameter of passed block.
903 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
904                                            Expr *BlockArg,
905                                            unsigned NumNonVarArgs) {
906   const BlockPointerType *BPT =
907       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
908   unsigned NumBlockParams =
909       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
910   unsigned TotalNumArgs = TheCall->getNumArgs();
911 
912   // For each argument passed to the block, a corresponding uint needs to
913   // be passed to describe the size of the local memory.
914   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
915     S.Diag(TheCall->getBeginLoc(),
916            diag::err_opencl_enqueue_kernel_local_size_args);
917     return true;
918   }
919 
920   // Check that the sizes of the local memory are specified by integers.
921   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
922                                          TotalNumArgs - 1);
923 }
924 
925 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
926 /// overload formats specified in Table 6.13.17.1.
927 /// int enqueue_kernel(queue_t queue,
928 ///                    kernel_enqueue_flags_t flags,
929 ///                    const ndrange_t ndrange,
930 ///                    void (^block)(void))
931 /// int enqueue_kernel(queue_t queue,
932 ///                    kernel_enqueue_flags_t flags,
933 ///                    const ndrange_t ndrange,
934 ///                    uint num_events_in_wait_list,
935 ///                    clk_event_t *event_wait_list,
936 ///                    clk_event_t *event_ret,
937 ///                    void (^block)(void))
938 /// int enqueue_kernel(queue_t queue,
939 ///                    kernel_enqueue_flags_t flags,
940 ///                    const ndrange_t ndrange,
941 ///                    void (^block)(local void*, ...),
942 ///                    uint size0, ...)
943 /// int enqueue_kernel(queue_t queue,
944 ///                    kernel_enqueue_flags_t flags,
945 ///                    const ndrange_t ndrange,
946 ///                    uint num_events_in_wait_list,
947 ///                    clk_event_t *event_wait_list,
948 ///                    clk_event_t *event_ret,
949 ///                    void (^block)(local void*, ...),
950 ///                    uint size0, ...)
951 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
952   unsigned NumArgs = TheCall->getNumArgs();
953 
954   if (NumArgs < 4) {
955     S.Diag(TheCall->getBeginLoc(),
956            diag::err_typecheck_call_too_few_args_at_least)
957         << 0 << 4 << NumArgs;
958     return true;
959   }
960 
961   Expr *Arg0 = TheCall->getArg(0);
962   Expr *Arg1 = TheCall->getArg(1);
963   Expr *Arg2 = TheCall->getArg(2);
964   Expr *Arg3 = TheCall->getArg(3);
965 
966   // First argument always needs to be a queue_t type.
967   if (!Arg0->getType()->isQueueT()) {
968     S.Diag(TheCall->getArg(0)->getBeginLoc(),
969            diag::err_opencl_builtin_expected_type)
970         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
971     return true;
972   }
973 
974   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
975   if (!Arg1->getType()->isIntegerType()) {
976     S.Diag(TheCall->getArg(1)->getBeginLoc(),
977            diag::err_opencl_builtin_expected_type)
978         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
979     return true;
980   }
981 
982   // Third argument is always an ndrange_t type.
983   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
984     S.Diag(TheCall->getArg(2)->getBeginLoc(),
985            diag::err_opencl_builtin_expected_type)
986         << TheCall->getDirectCallee() << "'ndrange_t'";
987     return true;
988   }
989 
990   // With four arguments, there is only one form that the function could be
991   // called in: no events and no variable arguments.
992   if (NumArgs == 4) {
993     // check that the last argument is the right block type.
994     if (!isBlockPointer(Arg3)) {
995       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
996           << TheCall->getDirectCallee() << "block";
997       return true;
998     }
999     // we have a block type, check the prototype
1000     const BlockPointerType *BPT =
1001         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1002     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1003       S.Diag(Arg3->getBeginLoc(),
1004              diag::err_opencl_enqueue_kernel_blocks_no_args);
1005       return true;
1006     }
1007     return false;
1008   }
1009   // we can have block + varargs.
1010   if (isBlockPointer(Arg3))
1011     return (checkOpenCLBlockArgs(S, Arg3) ||
1012             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1013   // last two cases with either exactly 7 args or 7 args and varargs.
1014   if (NumArgs >= 7) {
1015     // check common block argument.
1016     Expr *Arg6 = TheCall->getArg(6);
1017     if (!isBlockPointer(Arg6)) {
1018       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1019           << TheCall->getDirectCallee() << "block";
1020       return true;
1021     }
1022     if (checkOpenCLBlockArgs(S, Arg6))
1023       return true;
1024 
1025     // Forth argument has to be any integer type.
1026     if (!Arg3->getType()->isIntegerType()) {
1027       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1028              diag::err_opencl_builtin_expected_type)
1029           << TheCall->getDirectCallee() << "integer";
1030       return true;
1031     }
1032     // check remaining common arguments.
1033     Expr *Arg4 = TheCall->getArg(4);
1034     Expr *Arg5 = TheCall->getArg(5);
1035 
1036     // Fifth argument is always passed as a pointer to clk_event_t.
1037     if (!Arg4->isNullPointerConstant(S.Context,
1038                                      Expr::NPC_ValueDependentIsNotNull) &&
1039         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1040       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1041              diag::err_opencl_builtin_expected_type)
1042           << TheCall->getDirectCallee()
1043           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1044       return true;
1045     }
1046 
1047     // Sixth argument is always passed as a pointer to clk_event_t.
1048     if (!Arg5->isNullPointerConstant(S.Context,
1049                                      Expr::NPC_ValueDependentIsNotNull) &&
1050         !(Arg5->getType()->isPointerType() &&
1051           Arg5->getType()->getPointeeType()->isClkEventT())) {
1052       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1053              diag::err_opencl_builtin_expected_type)
1054           << TheCall->getDirectCallee()
1055           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1056       return true;
1057     }
1058 
1059     if (NumArgs == 7)
1060       return false;
1061 
1062     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1063   }
1064 
1065   // None of the specific case has been detected, give generic error
1066   S.Diag(TheCall->getBeginLoc(),
1067          diag::err_opencl_enqueue_kernel_incorrect_args);
1068   return true;
1069 }
1070 
1071 /// Returns OpenCL access qual.
1072 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1073     return D->getAttr<OpenCLAccessAttr>();
1074 }
1075 
1076 /// Returns true if pipe element type is different from the pointer.
1077 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1078   const Expr *Arg0 = Call->getArg(0);
1079   // First argument type should always be pipe.
1080   if (!Arg0->getType()->isPipeType()) {
1081     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1082         << Call->getDirectCallee() << Arg0->getSourceRange();
1083     return true;
1084   }
1085   OpenCLAccessAttr *AccessQual =
1086       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1087   // Validates the access qualifier is compatible with the call.
1088   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1089   // read_only and write_only, and assumed to be read_only if no qualifier is
1090   // specified.
1091   switch (Call->getDirectCallee()->getBuiltinID()) {
1092   case Builtin::BIread_pipe:
1093   case Builtin::BIreserve_read_pipe:
1094   case Builtin::BIcommit_read_pipe:
1095   case Builtin::BIwork_group_reserve_read_pipe:
1096   case Builtin::BIsub_group_reserve_read_pipe:
1097   case Builtin::BIwork_group_commit_read_pipe:
1098   case Builtin::BIsub_group_commit_read_pipe:
1099     if (!(!AccessQual || AccessQual->isReadOnly())) {
1100       S.Diag(Arg0->getBeginLoc(),
1101              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1102           << "read_only" << Arg0->getSourceRange();
1103       return true;
1104     }
1105     break;
1106   case Builtin::BIwrite_pipe:
1107   case Builtin::BIreserve_write_pipe:
1108   case Builtin::BIcommit_write_pipe:
1109   case Builtin::BIwork_group_reserve_write_pipe:
1110   case Builtin::BIsub_group_reserve_write_pipe:
1111   case Builtin::BIwork_group_commit_write_pipe:
1112   case Builtin::BIsub_group_commit_write_pipe:
1113     if (!(AccessQual && AccessQual->isWriteOnly())) {
1114       S.Diag(Arg0->getBeginLoc(),
1115              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1116           << "write_only" << Arg0->getSourceRange();
1117       return true;
1118     }
1119     break;
1120   default:
1121     break;
1122   }
1123   return false;
1124 }
1125 
1126 /// Returns true if pipe element type is different from the pointer.
1127 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1128   const Expr *Arg0 = Call->getArg(0);
1129   const Expr *ArgIdx = Call->getArg(Idx);
1130   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1131   const QualType EltTy = PipeTy->getElementType();
1132   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1133   // The Idx argument should be a pointer and the type of the pointer and
1134   // the type of pipe element should also be the same.
1135   if (!ArgTy ||
1136       !S.Context.hasSameType(
1137           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1138     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1139         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1140         << ArgIdx->getType() << ArgIdx->getSourceRange();
1141     return true;
1142   }
1143   return false;
1144 }
1145 
1146 // Performs semantic analysis for the read/write_pipe call.
1147 // \param S Reference to the semantic analyzer.
1148 // \param Call A pointer to the builtin call.
1149 // \return True if a semantic error has been found, false otherwise.
1150 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1151   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1152   // functions have two forms.
1153   switch (Call->getNumArgs()) {
1154   case 2:
1155     if (checkOpenCLPipeArg(S, Call))
1156       return true;
1157     // The call with 2 arguments should be
1158     // read/write_pipe(pipe T, T*).
1159     // Check packet type T.
1160     if (checkOpenCLPipePacketType(S, Call, 1))
1161       return true;
1162     break;
1163 
1164   case 4: {
1165     if (checkOpenCLPipeArg(S, Call))
1166       return true;
1167     // The call with 4 arguments should be
1168     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1169     // Check reserve_id_t.
1170     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1171       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1172           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1173           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1174       return true;
1175     }
1176 
1177     // Check the index.
1178     const Expr *Arg2 = Call->getArg(2);
1179     if (!Arg2->getType()->isIntegerType() &&
1180         !Arg2->getType()->isUnsignedIntegerType()) {
1181       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1182           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1183           << Arg2->getType() << Arg2->getSourceRange();
1184       return true;
1185     }
1186 
1187     // Check packet type T.
1188     if (checkOpenCLPipePacketType(S, Call, 3))
1189       return true;
1190   } break;
1191   default:
1192     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1193         << Call->getDirectCallee() << Call->getSourceRange();
1194     return true;
1195   }
1196 
1197   return false;
1198 }
1199 
1200 // Performs a semantic analysis on the {work_group_/sub_group_
1201 //        /_}reserve_{read/write}_pipe
1202 // \param S Reference to the semantic analyzer.
1203 // \param Call The call to the builtin function to be analyzed.
1204 // \return True if a semantic error was found, false otherwise.
1205 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1206   if (checkArgCount(S, Call, 2))
1207     return true;
1208 
1209   if (checkOpenCLPipeArg(S, Call))
1210     return true;
1211 
1212   // Check the reserve size.
1213   if (!Call->getArg(1)->getType()->isIntegerType() &&
1214       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1215     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1216         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1217         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1218     return true;
1219   }
1220 
1221   // Since return type of reserve_read/write_pipe built-in function is
1222   // reserve_id_t, which is not defined in the builtin def file , we used int
1223   // as return type and need to override the return type of these functions.
1224   Call->setType(S.Context.OCLReserveIDTy);
1225 
1226   return false;
1227 }
1228 
1229 // Performs a semantic analysis on {work_group_/sub_group_
1230 //        /_}commit_{read/write}_pipe
1231 // \param S Reference to the semantic analyzer.
1232 // \param Call The call to the builtin function to be analyzed.
1233 // \return True if a semantic error was found, false otherwise.
1234 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1235   if (checkArgCount(S, Call, 2))
1236     return true;
1237 
1238   if (checkOpenCLPipeArg(S, Call))
1239     return true;
1240 
1241   // Check reserve_id_t.
1242   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1243     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1244         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1245         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1246     return true;
1247   }
1248 
1249   return false;
1250 }
1251 
1252 // Performs a semantic analysis on the call to built-in Pipe
1253 //        Query Functions.
1254 // \param S Reference to the semantic analyzer.
1255 // \param Call The call to the builtin function to be analyzed.
1256 // \return True if a semantic error was found, false otherwise.
1257 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1258   if (checkArgCount(S, Call, 1))
1259     return true;
1260 
1261   if (!Call->getArg(0)->getType()->isPipeType()) {
1262     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1263         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1264     return true;
1265   }
1266 
1267   return false;
1268 }
1269 
1270 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1271 // Performs semantic analysis for the to_global/local/private call.
1272 // \param S Reference to the semantic analyzer.
1273 // \param BuiltinID ID of the builtin function.
1274 // \param Call A pointer to the builtin call.
1275 // \return True if a semantic error has been found, false otherwise.
1276 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1277                                     CallExpr *Call) {
1278   if (checkArgCount(S, Call, 1))
1279     return true;
1280 
1281   auto RT = Call->getArg(0)->getType();
1282   if (!RT->isPointerType() || RT->getPointeeType()
1283       .getAddressSpace() == LangAS::opencl_constant) {
1284     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1285         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1286     return true;
1287   }
1288 
1289   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1290     S.Diag(Call->getArg(0)->getBeginLoc(),
1291            diag::warn_opencl_generic_address_space_arg)
1292         << Call->getDirectCallee()->getNameInfo().getAsString()
1293         << Call->getArg(0)->getSourceRange();
1294   }
1295 
1296   RT = RT->getPointeeType();
1297   auto Qual = RT.getQualifiers();
1298   switch (BuiltinID) {
1299   case Builtin::BIto_global:
1300     Qual.setAddressSpace(LangAS::opencl_global);
1301     break;
1302   case Builtin::BIto_local:
1303     Qual.setAddressSpace(LangAS::opencl_local);
1304     break;
1305   case Builtin::BIto_private:
1306     Qual.setAddressSpace(LangAS::opencl_private);
1307     break;
1308   default:
1309     llvm_unreachable("Invalid builtin function");
1310   }
1311   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1312       RT.getUnqualifiedType(), Qual)));
1313 
1314   return false;
1315 }
1316 
1317 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1318   if (checkArgCount(S, TheCall, 1))
1319     return ExprError();
1320 
1321   // Compute __builtin_launder's parameter type from the argument.
1322   // The parameter type is:
1323   //  * The type of the argument if it's not an array or function type,
1324   //  Otherwise,
1325   //  * The decayed argument type.
1326   QualType ParamTy = [&]() {
1327     QualType ArgTy = TheCall->getArg(0)->getType();
1328     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1329       return S.Context.getPointerType(Ty->getElementType());
1330     if (ArgTy->isFunctionType()) {
1331       return S.Context.getPointerType(ArgTy);
1332     }
1333     return ArgTy;
1334   }();
1335 
1336   TheCall->setType(ParamTy);
1337 
1338   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1339     if (!ParamTy->isPointerType())
1340       return 0;
1341     if (ParamTy->isFunctionPointerType())
1342       return 1;
1343     if (ParamTy->isVoidPointerType())
1344       return 2;
1345     return llvm::Optional<unsigned>{};
1346   }();
1347   if (DiagSelect.hasValue()) {
1348     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1349         << DiagSelect.getValue() << TheCall->getSourceRange();
1350     return ExprError();
1351   }
1352 
1353   // We either have an incomplete class type, or we have a class template
1354   // whose instantiation has not been forced. Example:
1355   //
1356   //   template <class T> struct Foo { T value; };
1357   //   Foo<int> *p = nullptr;
1358   //   auto *d = __builtin_launder(p);
1359   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1360                             diag::err_incomplete_type))
1361     return ExprError();
1362 
1363   assert(ParamTy->getPointeeType()->isObjectType() &&
1364          "Unhandled non-object pointer case");
1365 
1366   InitializedEntity Entity =
1367       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1368   ExprResult Arg =
1369       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1370   if (Arg.isInvalid())
1371     return ExprError();
1372   TheCall->setArg(0, Arg.get());
1373 
1374   return TheCall;
1375 }
1376 
1377 // Emit an error and return true if the current architecture is not in the list
1378 // of supported architectures.
1379 static bool
1380 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1381                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1382   llvm::Triple::ArchType CurArch =
1383       S.getASTContext().getTargetInfo().getTriple().getArch();
1384   if (llvm::is_contained(SupportedArchs, CurArch))
1385     return false;
1386   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1387       << TheCall->getSourceRange();
1388   return true;
1389 }
1390 
1391 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1392                                  SourceLocation CallSiteLoc);
1393 
1394 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1395                                       CallExpr *TheCall) {
1396   switch (TI.getTriple().getArch()) {
1397   default:
1398     // Some builtins don't require additional checking, so just consider these
1399     // acceptable.
1400     return false;
1401   case llvm::Triple::arm:
1402   case llvm::Triple::armeb:
1403   case llvm::Triple::thumb:
1404   case llvm::Triple::thumbeb:
1405     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1406   case llvm::Triple::aarch64:
1407   case llvm::Triple::aarch64_32:
1408   case llvm::Triple::aarch64_be:
1409     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1410   case llvm::Triple::bpfeb:
1411   case llvm::Triple::bpfel:
1412     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1413   case llvm::Triple::hexagon:
1414     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1415   case llvm::Triple::mips:
1416   case llvm::Triple::mipsel:
1417   case llvm::Triple::mips64:
1418   case llvm::Triple::mips64el:
1419     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1420   case llvm::Triple::systemz:
1421     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1422   case llvm::Triple::x86:
1423   case llvm::Triple::x86_64:
1424     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1425   case llvm::Triple::ppc:
1426   case llvm::Triple::ppcle:
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   case llvm::Triple::riscv32:
1433   case llvm::Triple::riscv64:
1434     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1435   }
1436 }
1437 
1438 ExprResult
1439 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1440                                CallExpr *TheCall) {
1441   ExprResult TheCallResult(TheCall);
1442 
1443   // Find out if any arguments are required to be integer constant expressions.
1444   unsigned ICEArguments = 0;
1445   ASTContext::GetBuiltinTypeError Error;
1446   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1447   if (Error != ASTContext::GE_None)
1448     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1449 
1450   // If any arguments are required to be ICE's, check and diagnose.
1451   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1452     // Skip arguments not required to be ICE's.
1453     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1454 
1455     llvm::APSInt Result;
1456     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1457       return true;
1458     ICEArguments &= ~(1 << ArgNo);
1459   }
1460 
1461   switch (BuiltinID) {
1462   case Builtin::BI__builtin___CFStringMakeConstantString:
1463     assert(TheCall->getNumArgs() == 1 &&
1464            "Wrong # arguments to builtin CFStringMakeConstantString");
1465     if (CheckObjCString(TheCall->getArg(0)))
1466       return ExprError();
1467     break;
1468   case Builtin::BI__builtin_ms_va_start:
1469   case Builtin::BI__builtin_stdarg_start:
1470   case Builtin::BI__builtin_va_start:
1471     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1472       return ExprError();
1473     break;
1474   case Builtin::BI__va_start: {
1475     switch (Context.getTargetInfo().getTriple().getArch()) {
1476     case llvm::Triple::aarch64:
1477     case llvm::Triple::arm:
1478     case llvm::Triple::thumb:
1479       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1480         return ExprError();
1481       break;
1482     default:
1483       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1484         return ExprError();
1485       break;
1486     }
1487     break;
1488   }
1489 
1490   // The acquire, release, and no fence variants are ARM and AArch64 only.
1491   case Builtin::BI_interlockedbittestandset_acq:
1492   case Builtin::BI_interlockedbittestandset_rel:
1493   case Builtin::BI_interlockedbittestandset_nf:
1494   case Builtin::BI_interlockedbittestandreset_acq:
1495   case Builtin::BI_interlockedbittestandreset_rel:
1496   case Builtin::BI_interlockedbittestandreset_nf:
1497     if (CheckBuiltinTargetSupport(
1498             *this, BuiltinID, TheCall,
1499             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1500       return ExprError();
1501     break;
1502 
1503   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1504   case Builtin::BI_bittest64:
1505   case Builtin::BI_bittestandcomplement64:
1506   case Builtin::BI_bittestandreset64:
1507   case Builtin::BI_bittestandset64:
1508   case Builtin::BI_interlockedbittestandreset64:
1509   case Builtin::BI_interlockedbittestandset64:
1510     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1511                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1512                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1513       return ExprError();
1514     break;
1515 
1516   case Builtin::BI__builtin_isgreater:
1517   case Builtin::BI__builtin_isgreaterequal:
1518   case Builtin::BI__builtin_isless:
1519   case Builtin::BI__builtin_islessequal:
1520   case Builtin::BI__builtin_islessgreater:
1521   case Builtin::BI__builtin_isunordered:
1522     if (SemaBuiltinUnorderedCompare(TheCall))
1523       return ExprError();
1524     break;
1525   case Builtin::BI__builtin_fpclassify:
1526     if (SemaBuiltinFPClassification(TheCall, 6))
1527       return ExprError();
1528     break;
1529   case Builtin::BI__builtin_isfinite:
1530   case Builtin::BI__builtin_isinf:
1531   case Builtin::BI__builtin_isinf_sign:
1532   case Builtin::BI__builtin_isnan:
1533   case Builtin::BI__builtin_isnormal:
1534   case Builtin::BI__builtin_signbit:
1535   case Builtin::BI__builtin_signbitf:
1536   case Builtin::BI__builtin_signbitl:
1537     if (SemaBuiltinFPClassification(TheCall, 1))
1538       return ExprError();
1539     break;
1540   case Builtin::BI__builtin_shufflevector:
1541     return SemaBuiltinShuffleVector(TheCall);
1542     // TheCall will be freed by the smart pointer here, but that's fine, since
1543     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1544   case Builtin::BI__builtin_prefetch:
1545     if (SemaBuiltinPrefetch(TheCall))
1546       return ExprError();
1547     break;
1548   case Builtin::BI__builtin_alloca_with_align:
1549     if (SemaBuiltinAllocaWithAlign(TheCall))
1550       return ExprError();
1551     LLVM_FALLTHROUGH;
1552   case Builtin::BI__builtin_alloca:
1553     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1554         << TheCall->getDirectCallee();
1555     break;
1556   case Builtin::BI__assume:
1557   case Builtin::BI__builtin_assume:
1558     if (SemaBuiltinAssume(TheCall))
1559       return ExprError();
1560     break;
1561   case Builtin::BI__builtin_assume_aligned:
1562     if (SemaBuiltinAssumeAligned(TheCall))
1563       return ExprError();
1564     break;
1565   case Builtin::BI__builtin_dynamic_object_size:
1566   case Builtin::BI__builtin_object_size:
1567     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1568       return ExprError();
1569     break;
1570   case Builtin::BI__builtin_longjmp:
1571     if (SemaBuiltinLongjmp(TheCall))
1572       return ExprError();
1573     break;
1574   case Builtin::BI__builtin_setjmp:
1575     if (SemaBuiltinSetjmp(TheCall))
1576       return ExprError();
1577     break;
1578   case Builtin::BI__builtin_classify_type:
1579     if (checkArgCount(*this, TheCall, 1)) return true;
1580     TheCall->setType(Context.IntTy);
1581     break;
1582   case Builtin::BI__builtin_complex:
1583     if (SemaBuiltinComplex(TheCall))
1584       return ExprError();
1585     break;
1586   case Builtin::BI__builtin_constant_p: {
1587     if (checkArgCount(*this, TheCall, 1)) return true;
1588     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1589     if (Arg.isInvalid()) return true;
1590     TheCall->setArg(0, Arg.get());
1591     TheCall->setType(Context.IntTy);
1592     break;
1593   }
1594   case Builtin::BI__builtin_launder:
1595     return SemaBuiltinLaunder(*this, TheCall);
1596   case Builtin::BI__sync_fetch_and_add:
1597   case Builtin::BI__sync_fetch_and_add_1:
1598   case Builtin::BI__sync_fetch_and_add_2:
1599   case Builtin::BI__sync_fetch_and_add_4:
1600   case Builtin::BI__sync_fetch_and_add_8:
1601   case Builtin::BI__sync_fetch_and_add_16:
1602   case Builtin::BI__sync_fetch_and_sub:
1603   case Builtin::BI__sync_fetch_and_sub_1:
1604   case Builtin::BI__sync_fetch_and_sub_2:
1605   case Builtin::BI__sync_fetch_and_sub_4:
1606   case Builtin::BI__sync_fetch_and_sub_8:
1607   case Builtin::BI__sync_fetch_and_sub_16:
1608   case Builtin::BI__sync_fetch_and_or:
1609   case Builtin::BI__sync_fetch_and_or_1:
1610   case Builtin::BI__sync_fetch_and_or_2:
1611   case Builtin::BI__sync_fetch_and_or_4:
1612   case Builtin::BI__sync_fetch_and_or_8:
1613   case Builtin::BI__sync_fetch_and_or_16:
1614   case Builtin::BI__sync_fetch_and_and:
1615   case Builtin::BI__sync_fetch_and_and_1:
1616   case Builtin::BI__sync_fetch_and_and_2:
1617   case Builtin::BI__sync_fetch_and_and_4:
1618   case Builtin::BI__sync_fetch_and_and_8:
1619   case Builtin::BI__sync_fetch_and_and_16:
1620   case Builtin::BI__sync_fetch_and_xor:
1621   case Builtin::BI__sync_fetch_and_xor_1:
1622   case Builtin::BI__sync_fetch_and_xor_2:
1623   case Builtin::BI__sync_fetch_and_xor_4:
1624   case Builtin::BI__sync_fetch_and_xor_8:
1625   case Builtin::BI__sync_fetch_and_xor_16:
1626   case Builtin::BI__sync_fetch_and_nand:
1627   case Builtin::BI__sync_fetch_and_nand_1:
1628   case Builtin::BI__sync_fetch_and_nand_2:
1629   case Builtin::BI__sync_fetch_and_nand_4:
1630   case Builtin::BI__sync_fetch_and_nand_8:
1631   case Builtin::BI__sync_fetch_and_nand_16:
1632   case Builtin::BI__sync_add_and_fetch:
1633   case Builtin::BI__sync_add_and_fetch_1:
1634   case Builtin::BI__sync_add_and_fetch_2:
1635   case Builtin::BI__sync_add_and_fetch_4:
1636   case Builtin::BI__sync_add_and_fetch_8:
1637   case Builtin::BI__sync_add_and_fetch_16:
1638   case Builtin::BI__sync_sub_and_fetch:
1639   case Builtin::BI__sync_sub_and_fetch_1:
1640   case Builtin::BI__sync_sub_and_fetch_2:
1641   case Builtin::BI__sync_sub_and_fetch_4:
1642   case Builtin::BI__sync_sub_and_fetch_8:
1643   case Builtin::BI__sync_sub_and_fetch_16:
1644   case Builtin::BI__sync_and_and_fetch:
1645   case Builtin::BI__sync_and_and_fetch_1:
1646   case Builtin::BI__sync_and_and_fetch_2:
1647   case Builtin::BI__sync_and_and_fetch_4:
1648   case Builtin::BI__sync_and_and_fetch_8:
1649   case Builtin::BI__sync_and_and_fetch_16:
1650   case Builtin::BI__sync_or_and_fetch:
1651   case Builtin::BI__sync_or_and_fetch_1:
1652   case Builtin::BI__sync_or_and_fetch_2:
1653   case Builtin::BI__sync_or_and_fetch_4:
1654   case Builtin::BI__sync_or_and_fetch_8:
1655   case Builtin::BI__sync_or_and_fetch_16:
1656   case Builtin::BI__sync_xor_and_fetch:
1657   case Builtin::BI__sync_xor_and_fetch_1:
1658   case Builtin::BI__sync_xor_and_fetch_2:
1659   case Builtin::BI__sync_xor_and_fetch_4:
1660   case Builtin::BI__sync_xor_and_fetch_8:
1661   case Builtin::BI__sync_xor_and_fetch_16:
1662   case Builtin::BI__sync_nand_and_fetch:
1663   case Builtin::BI__sync_nand_and_fetch_1:
1664   case Builtin::BI__sync_nand_and_fetch_2:
1665   case Builtin::BI__sync_nand_and_fetch_4:
1666   case Builtin::BI__sync_nand_and_fetch_8:
1667   case Builtin::BI__sync_nand_and_fetch_16:
1668   case Builtin::BI__sync_val_compare_and_swap:
1669   case Builtin::BI__sync_val_compare_and_swap_1:
1670   case Builtin::BI__sync_val_compare_and_swap_2:
1671   case Builtin::BI__sync_val_compare_and_swap_4:
1672   case Builtin::BI__sync_val_compare_and_swap_8:
1673   case Builtin::BI__sync_val_compare_and_swap_16:
1674   case Builtin::BI__sync_bool_compare_and_swap:
1675   case Builtin::BI__sync_bool_compare_and_swap_1:
1676   case Builtin::BI__sync_bool_compare_and_swap_2:
1677   case Builtin::BI__sync_bool_compare_and_swap_4:
1678   case Builtin::BI__sync_bool_compare_and_swap_8:
1679   case Builtin::BI__sync_bool_compare_and_swap_16:
1680   case Builtin::BI__sync_lock_test_and_set:
1681   case Builtin::BI__sync_lock_test_and_set_1:
1682   case Builtin::BI__sync_lock_test_and_set_2:
1683   case Builtin::BI__sync_lock_test_and_set_4:
1684   case Builtin::BI__sync_lock_test_and_set_8:
1685   case Builtin::BI__sync_lock_test_and_set_16:
1686   case Builtin::BI__sync_lock_release:
1687   case Builtin::BI__sync_lock_release_1:
1688   case Builtin::BI__sync_lock_release_2:
1689   case Builtin::BI__sync_lock_release_4:
1690   case Builtin::BI__sync_lock_release_8:
1691   case Builtin::BI__sync_lock_release_16:
1692   case Builtin::BI__sync_swap:
1693   case Builtin::BI__sync_swap_1:
1694   case Builtin::BI__sync_swap_2:
1695   case Builtin::BI__sync_swap_4:
1696   case Builtin::BI__sync_swap_8:
1697   case Builtin::BI__sync_swap_16:
1698     return SemaBuiltinAtomicOverloaded(TheCallResult);
1699   case Builtin::BI__sync_synchronize:
1700     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1701         << TheCall->getCallee()->getSourceRange();
1702     break;
1703   case Builtin::BI__builtin_nontemporal_load:
1704   case Builtin::BI__builtin_nontemporal_store:
1705     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1706   case Builtin::BI__builtin_memcpy_inline: {
1707     clang::Expr *SizeOp = TheCall->getArg(2);
1708     // We warn about copying to or from `nullptr` pointers when `size` is
1709     // greater than 0. When `size` is value dependent we cannot evaluate its
1710     // value so we bail out.
1711     if (SizeOp->isValueDependent())
1712       break;
1713     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1714       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1715       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1716     }
1717     break;
1718   }
1719 #define BUILTIN(ID, TYPE, ATTRS)
1720 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1721   case Builtin::BI##ID: \
1722     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1723 #include "clang/Basic/Builtins.def"
1724   case Builtin::BI__annotation:
1725     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1726       return ExprError();
1727     break;
1728   case Builtin::BI__builtin_annotation:
1729     if (SemaBuiltinAnnotation(*this, TheCall))
1730       return ExprError();
1731     break;
1732   case Builtin::BI__builtin_addressof:
1733     if (SemaBuiltinAddressof(*this, TheCall))
1734       return ExprError();
1735     break;
1736   case Builtin::BI__builtin_is_aligned:
1737   case Builtin::BI__builtin_align_up:
1738   case Builtin::BI__builtin_align_down:
1739     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1740       return ExprError();
1741     break;
1742   case Builtin::BI__builtin_add_overflow:
1743   case Builtin::BI__builtin_sub_overflow:
1744   case Builtin::BI__builtin_mul_overflow:
1745     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1746       return ExprError();
1747     break;
1748   case Builtin::BI__builtin_operator_new:
1749   case Builtin::BI__builtin_operator_delete: {
1750     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1751     ExprResult Res =
1752         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1753     if (Res.isInvalid())
1754       CorrectDelayedTyposInExpr(TheCallResult.get());
1755     return Res;
1756   }
1757   case Builtin::BI__builtin_dump_struct: {
1758     // We first want to ensure we are called with 2 arguments
1759     if (checkArgCount(*this, TheCall, 2))
1760       return ExprError();
1761     // Ensure that the first argument is of type 'struct XX *'
1762     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1763     const QualType PtrArgType = PtrArg->getType();
1764     if (!PtrArgType->isPointerType() ||
1765         !PtrArgType->getPointeeType()->isRecordType()) {
1766       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1767           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1768           << "structure pointer";
1769       return ExprError();
1770     }
1771 
1772     // Ensure that the second argument is of type 'FunctionType'
1773     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1774     const QualType FnPtrArgType = FnPtrArg->getType();
1775     if (!FnPtrArgType->isPointerType()) {
1776       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1777           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1778           << FnPtrArgType << "'int (*)(const char *, ...)'";
1779       return ExprError();
1780     }
1781 
1782     const auto *FuncType =
1783         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1784 
1785     if (!FuncType) {
1786       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1787           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1788           << FnPtrArgType << "'int (*)(const char *, ...)'";
1789       return ExprError();
1790     }
1791 
1792     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1793       if (!FT->getNumParams()) {
1794         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1795             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1796             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1797         return ExprError();
1798       }
1799       QualType PT = FT->getParamType(0);
1800       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1801           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1802           !PT->getPointeeType().isConstQualified()) {
1803         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1804             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1805             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1806         return ExprError();
1807       }
1808     }
1809 
1810     TheCall->setType(Context.IntTy);
1811     break;
1812   }
1813   case Builtin::BI__builtin_expect_with_probability: {
1814     // We first want to ensure we are called with 3 arguments
1815     if (checkArgCount(*this, TheCall, 3))
1816       return ExprError();
1817     // then check probability is constant float in range [0.0, 1.0]
1818     const Expr *ProbArg = TheCall->getArg(2);
1819     SmallVector<PartialDiagnosticAt, 8> Notes;
1820     Expr::EvalResult Eval;
1821     Eval.Diag = &Notes;
1822     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1823         !Eval.Val.isFloat()) {
1824       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1825           << ProbArg->getSourceRange();
1826       for (const PartialDiagnosticAt &PDiag : Notes)
1827         Diag(PDiag.first, PDiag.second);
1828       return ExprError();
1829     }
1830     llvm::APFloat Probability = Eval.Val.getFloat();
1831     bool LoseInfo = false;
1832     Probability.convert(llvm::APFloat::IEEEdouble(),
1833                         llvm::RoundingMode::Dynamic, &LoseInfo);
1834     if (!(Probability >= llvm::APFloat(0.0) &&
1835           Probability <= llvm::APFloat(1.0))) {
1836       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1837           << ProbArg->getSourceRange();
1838       return ExprError();
1839     }
1840     break;
1841   }
1842   case Builtin::BI__builtin_preserve_access_index:
1843     if (SemaBuiltinPreserveAI(*this, TheCall))
1844       return ExprError();
1845     break;
1846   case Builtin::BI__builtin_call_with_static_chain:
1847     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1848       return ExprError();
1849     break;
1850   case Builtin::BI__exception_code:
1851   case Builtin::BI_exception_code:
1852     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1853                                  diag::err_seh___except_block))
1854       return ExprError();
1855     break;
1856   case Builtin::BI__exception_info:
1857   case Builtin::BI_exception_info:
1858     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1859                                  diag::err_seh___except_filter))
1860       return ExprError();
1861     break;
1862   case Builtin::BI__GetExceptionInfo:
1863     if (checkArgCount(*this, TheCall, 1))
1864       return ExprError();
1865 
1866     if (CheckCXXThrowOperand(
1867             TheCall->getBeginLoc(),
1868             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1869             TheCall))
1870       return ExprError();
1871 
1872     TheCall->setType(Context.VoidPtrTy);
1873     break;
1874   // OpenCL v2.0, s6.13.16 - Pipe functions
1875   case Builtin::BIread_pipe:
1876   case Builtin::BIwrite_pipe:
1877     // Since those two functions are declared with var args, we need a semantic
1878     // check for the argument.
1879     if (SemaBuiltinRWPipe(*this, TheCall))
1880       return ExprError();
1881     break;
1882   case Builtin::BIreserve_read_pipe:
1883   case Builtin::BIreserve_write_pipe:
1884   case Builtin::BIwork_group_reserve_read_pipe:
1885   case Builtin::BIwork_group_reserve_write_pipe:
1886     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1887       return ExprError();
1888     break;
1889   case Builtin::BIsub_group_reserve_read_pipe:
1890   case Builtin::BIsub_group_reserve_write_pipe:
1891     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1892         SemaBuiltinReserveRWPipe(*this, TheCall))
1893       return ExprError();
1894     break;
1895   case Builtin::BIcommit_read_pipe:
1896   case Builtin::BIcommit_write_pipe:
1897   case Builtin::BIwork_group_commit_read_pipe:
1898   case Builtin::BIwork_group_commit_write_pipe:
1899     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1900       return ExprError();
1901     break;
1902   case Builtin::BIsub_group_commit_read_pipe:
1903   case Builtin::BIsub_group_commit_write_pipe:
1904     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1905         SemaBuiltinCommitRWPipe(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIget_pipe_num_packets:
1909   case Builtin::BIget_pipe_max_packets:
1910     if (SemaBuiltinPipePackets(*this, TheCall))
1911       return ExprError();
1912     break;
1913   case Builtin::BIto_global:
1914   case Builtin::BIto_local:
1915   case Builtin::BIto_private:
1916     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1917       return ExprError();
1918     break;
1919   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1920   case Builtin::BIenqueue_kernel:
1921     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1922       return ExprError();
1923     break;
1924   case Builtin::BIget_kernel_work_group_size:
1925   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1926     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1930   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1931     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1932       return ExprError();
1933     break;
1934   case Builtin::BI__builtin_os_log_format:
1935     Cleanup.setExprNeedsCleanups(true);
1936     LLVM_FALLTHROUGH;
1937   case Builtin::BI__builtin_os_log_format_buffer_size:
1938     if (SemaBuiltinOSLogFormat(TheCall))
1939       return ExprError();
1940     break;
1941   case Builtin::BI__builtin_frame_address:
1942   case Builtin::BI__builtin_return_address: {
1943     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1944       return ExprError();
1945 
1946     // -Wframe-address warning if non-zero passed to builtin
1947     // return/frame address.
1948     Expr::EvalResult Result;
1949     if (!TheCall->getArg(0)->isValueDependent() &&
1950         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1951         Result.Val.getInt() != 0)
1952       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1953           << ((BuiltinID == Builtin::BI__builtin_return_address)
1954                   ? "__builtin_return_address"
1955                   : "__builtin_frame_address")
1956           << TheCall->getSourceRange();
1957     break;
1958   }
1959 
1960   case Builtin::BI__builtin_matrix_transpose:
1961     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1962 
1963   case Builtin::BI__builtin_matrix_column_major_load:
1964     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1965 
1966   case Builtin::BI__builtin_matrix_column_major_store:
1967     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1968   }
1969 
1970   // Since the target specific builtins for each arch overlap, only check those
1971   // of the arch we are compiling for.
1972   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1973     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1974       assert(Context.getAuxTargetInfo() &&
1975              "Aux Target Builtin, but not an aux target?");
1976 
1977       if (CheckTSBuiltinFunctionCall(
1978               *Context.getAuxTargetInfo(),
1979               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1980         return ExprError();
1981     } else {
1982       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1983                                      TheCall))
1984         return ExprError();
1985     }
1986   }
1987 
1988   return TheCallResult;
1989 }
1990 
1991 // Get the valid immediate range for the specified NEON type code.
1992 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1993   NeonTypeFlags Type(t);
1994   int IsQuad = ForceQuad ? true : Type.isQuad();
1995   switch (Type.getEltType()) {
1996   case NeonTypeFlags::Int8:
1997   case NeonTypeFlags::Poly8:
1998     return shift ? 7 : (8 << IsQuad) - 1;
1999   case NeonTypeFlags::Int16:
2000   case NeonTypeFlags::Poly16:
2001     return shift ? 15 : (4 << IsQuad) - 1;
2002   case NeonTypeFlags::Int32:
2003     return shift ? 31 : (2 << IsQuad) - 1;
2004   case NeonTypeFlags::Int64:
2005   case NeonTypeFlags::Poly64:
2006     return shift ? 63 : (1 << IsQuad) - 1;
2007   case NeonTypeFlags::Poly128:
2008     return shift ? 127 : (1 << IsQuad) - 1;
2009   case NeonTypeFlags::Float16:
2010     assert(!shift && "cannot shift float types!");
2011     return (4 << IsQuad) - 1;
2012   case NeonTypeFlags::Float32:
2013     assert(!shift && "cannot shift float types!");
2014     return (2 << IsQuad) - 1;
2015   case NeonTypeFlags::Float64:
2016     assert(!shift && "cannot shift float types!");
2017     return (1 << IsQuad) - 1;
2018   case NeonTypeFlags::BFloat16:
2019     assert(!shift && "cannot shift float types!");
2020     return (4 << IsQuad) - 1;
2021   }
2022   llvm_unreachable("Invalid NeonTypeFlag!");
2023 }
2024 
2025 /// getNeonEltType - Return the QualType corresponding to the elements of
2026 /// the vector type specified by the NeonTypeFlags.  This is used to check
2027 /// the pointer arguments for Neon load/store intrinsics.
2028 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2029                                bool IsPolyUnsigned, bool IsInt64Long) {
2030   switch (Flags.getEltType()) {
2031   case NeonTypeFlags::Int8:
2032     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2033   case NeonTypeFlags::Int16:
2034     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2035   case NeonTypeFlags::Int32:
2036     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2037   case NeonTypeFlags::Int64:
2038     if (IsInt64Long)
2039       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2040     else
2041       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2042                                 : Context.LongLongTy;
2043   case NeonTypeFlags::Poly8:
2044     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2045   case NeonTypeFlags::Poly16:
2046     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2047   case NeonTypeFlags::Poly64:
2048     if (IsInt64Long)
2049       return Context.UnsignedLongTy;
2050     else
2051       return Context.UnsignedLongLongTy;
2052   case NeonTypeFlags::Poly128:
2053     break;
2054   case NeonTypeFlags::Float16:
2055     return Context.HalfTy;
2056   case NeonTypeFlags::Float32:
2057     return Context.FloatTy;
2058   case NeonTypeFlags::Float64:
2059     return Context.DoubleTy;
2060   case NeonTypeFlags::BFloat16:
2061     return Context.BFloat16Ty;
2062   }
2063   llvm_unreachable("Invalid NeonTypeFlag!");
2064 }
2065 
2066 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2067   // Range check SVE intrinsics that take immediate values.
2068   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2069 
2070   switch (BuiltinID) {
2071   default:
2072     return false;
2073 #define GET_SVE_IMMEDIATE_CHECK
2074 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2075 #undef GET_SVE_IMMEDIATE_CHECK
2076   }
2077 
2078   // Perform all the immediate checks for this builtin call.
2079   bool HasError = false;
2080   for (auto &I : ImmChecks) {
2081     int ArgNum, CheckTy, ElementSizeInBits;
2082     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2083 
2084     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2085 
2086     // Function that checks whether the operand (ArgNum) is an immediate
2087     // that is one of the predefined values.
2088     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2089                                    int ErrDiag) -> bool {
2090       // We can't check the value of a dependent argument.
2091       Expr *Arg = TheCall->getArg(ArgNum);
2092       if (Arg->isTypeDependent() || Arg->isValueDependent())
2093         return false;
2094 
2095       // Check constant-ness first.
2096       llvm::APSInt Imm;
2097       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2098         return true;
2099 
2100       if (!CheckImm(Imm.getSExtValue()))
2101         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2102       return false;
2103     };
2104 
2105     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2106     case SVETypeFlags::ImmCheck0_31:
2107       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2108         HasError = true;
2109       break;
2110     case SVETypeFlags::ImmCheck0_13:
2111       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2112         HasError = true;
2113       break;
2114     case SVETypeFlags::ImmCheck1_16:
2115       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2116         HasError = true;
2117       break;
2118     case SVETypeFlags::ImmCheck0_7:
2119       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2120         HasError = true;
2121       break;
2122     case SVETypeFlags::ImmCheckExtract:
2123       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2124                                       (2048 / ElementSizeInBits) - 1))
2125         HasError = true;
2126       break;
2127     case SVETypeFlags::ImmCheckShiftRight:
2128       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2129         HasError = true;
2130       break;
2131     case SVETypeFlags::ImmCheckShiftRightNarrow:
2132       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2133                                       ElementSizeInBits / 2))
2134         HasError = true;
2135       break;
2136     case SVETypeFlags::ImmCheckShiftLeft:
2137       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2138                                       ElementSizeInBits - 1))
2139         HasError = true;
2140       break;
2141     case SVETypeFlags::ImmCheckLaneIndex:
2142       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2143                                       (128 / (1 * ElementSizeInBits)) - 1))
2144         HasError = true;
2145       break;
2146     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2147       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2148                                       (128 / (2 * ElementSizeInBits)) - 1))
2149         HasError = true;
2150       break;
2151     case SVETypeFlags::ImmCheckLaneIndexDot:
2152       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2153                                       (128 / (4 * ElementSizeInBits)) - 1))
2154         HasError = true;
2155       break;
2156     case SVETypeFlags::ImmCheckComplexRot90_270:
2157       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2158                               diag::err_rotation_argument_to_cadd))
2159         HasError = true;
2160       break;
2161     case SVETypeFlags::ImmCheckComplexRotAll90:
2162       if (CheckImmediateInSet(
2163               [](int64_t V) {
2164                 return V == 0 || V == 90 || V == 180 || V == 270;
2165               },
2166               diag::err_rotation_argument_to_cmla))
2167         HasError = true;
2168       break;
2169     case SVETypeFlags::ImmCheck0_1:
2170       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2171         HasError = true;
2172       break;
2173     case SVETypeFlags::ImmCheck0_2:
2174       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2175         HasError = true;
2176       break;
2177     case SVETypeFlags::ImmCheck0_3:
2178       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2179         HasError = true;
2180       break;
2181     }
2182   }
2183 
2184   return HasError;
2185 }
2186 
2187 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2188                                         unsigned BuiltinID, CallExpr *TheCall) {
2189   llvm::APSInt Result;
2190   uint64_t mask = 0;
2191   unsigned TV = 0;
2192   int PtrArgNum = -1;
2193   bool HasConstPtr = false;
2194   switch (BuiltinID) {
2195 #define GET_NEON_OVERLOAD_CHECK
2196 #include "clang/Basic/arm_neon.inc"
2197 #include "clang/Basic/arm_fp16.inc"
2198 #undef GET_NEON_OVERLOAD_CHECK
2199   }
2200 
2201   // For NEON intrinsics which are overloaded on vector element type, validate
2202   // the immediate which specifies which variant to emit.
2203   unsigned ImmArg = TheCall->getNumArgs()-1;
2204   if (mask) {
2205     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2206       return true;
2207 
2208     TV = Result.getLimitedValue(64);
2209     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2210       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2211              << TheCall->getArg(ImmArg)->getSourceRange();
2212   }
2213 
2214   if (PtrArgNum >= 0) {
2215     // Check that pointer arguments have the specified type.
2216     Expr *Arg = TheCall->getArg(PtrArgNum);
2217     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2218       Arg = ICE->getSubExpr();
2219     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2220     QualType RHSTy = RHS.get()->getType();
2221 
2222     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2223     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2224                           Arch == llvm::Triple::aarch64_32 ||
2225                           Arch == llvm::Triple::aarch64_be;
2226     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2227     QualType EltTy =
2228         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2229     if (HasConstPtr)
2230       EltTy = EltTy.withConst();
2231     QualType LHSTy = Context.getPointerType(EltTy);
2232     AssignConvertType ConvTy;
2233     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2234     if (RHS.isInvalid())
2235       return true;
2236     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2237                                  RHS.get(), AA_Assigning))
2238       return true;
2239   }
2240 
2241   // For NEON intrinsics which take an immediate value as part of the
2242   // instruction, range check them here.
2243   unsigned i = 0, l = 0, u = 0;
2244   switch (BuiltinID) {
2245   default:
2246     return false;
2247   #define GET_NEON_IMMEDIATE_CHECK
2248   #include "clang/Basic/arm_neon.inc"
2249   #include "clang/Basic/arm_fp16.inc"
2250   #undef GET_NEON_IMMEDIATE_CHECK
2251   }
2252 
2253   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2254 }
2255 
2256 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2257   switch (BuiltinID) {
2258   default:
2259     return false;
2260   #include "clang/Basic/arm_mve_builtin_sema.inc"
2261   }
2262 }
2263 
2264 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2265                                        CallExpr *TheCall) {
2266   bool Err = false;
2267   switch (BuiltinID) {
2268   default:
2269     return false;
2270 #include "clang/Basic/arm_cde_builtin_sema.inc"
2271   }
2272 
2273   if (Err)
2274     return true;
2275 
2276   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2277 }
2278 
2279 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2280                                         const Expr *CoprocArg, bool WantCDE) {
2281   if (isConstantEvaluated())
2282     return false;
2283 
2284   // We can't check the value of a dependent argument.
2285   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2286     return false;
2287 
2288   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2289   int64_t CoprocNo = CoprocNoAP.getExtValue();
2290   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2291 
2292   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2293   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2294 
2295   if (IsCDECoproc != WantCDE)
2296     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2297            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2298 
2299   return false;
2300 }
2301 
2302 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2303                                         unsigned MaxWidth) {
2304   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2305           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2306           BuiltinID == ARM::BI__builtin_arm_strex ||
2307           BuiltinID == ARM::BI__builtin_arm_stlex ||
2308           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2309           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2310           BuiltinID == AArch64::BI__builtin_arm_strex ||
2311           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2312          "unexpected ARM builtin");
2313   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2314                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2315                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2316                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2317 
2318   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2319 
2320   // Ensure that we have the proper number of arguments.
2321   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2322     return true;
2323 
2324   // Inspect the pointer argument of the atomic builtin.  This should always be
2325   // a pointer type, whose element is an integral scalar or pointer type.
2326   // Because it is a pointer type, we don't have to worry about any implicit
2327   // casts here.
2328   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2329   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2330   if (PointerArgRes.isInvalid())
2331     return true;
2332   PointerArg = PointerArgRes.get();
2333 
2334   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2335   if (!pointerType) {
2336     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2337         << PointerArg->getType() << PointerArg->getSourceRange();
2338     return true;
2339   }
2340 
2341   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2342   // task is to insert the appropriate casts into the AST. First work out just
2343   // what the appropriate type is.
2344   QualType ValType = pointerType->getPointeeType();
2345   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2346   if (IsLdrex)
2347     AddrType.addConst();
2348 
2349   // Issue a warning if the cast is dodgy.
2350   CastKind CastNeeded = CK_NoOp;
2351   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2352     CastNeeded = CK_BitCast;
2353     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2354         << PointerArg->getType() << Context.getPointerType(AddrType)
2355         << AA_Passing << PointerArg->getSourceRange();
2356   }
2357 
2358   // Finally, do the cast and replace the argument with the corrected version.
2359   AddrType = Context.getPointerType(AddrType);
2360   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2361   if (PointerArgRes.isInvalid())
2362     return true;
2363   PointerArg = PointerArgRes.get();
2364 
2365   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2366 
2367   // In general, we allow ints, floats and pointers to be loaded and stored.
2368   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2369       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2370     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2371         << PointerArg->getType() << PointerArg->getSourceRange();
2372     return true;
2373   }
2374 
2375   // But ARM doesn't have instructions to deal with 128-bit versions.
2376   if (Context.getTypeSize(ValType) > MaxWidth) {
2377     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2378     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2379         << PointerArg->getType() << PointerArg->getSourceRange();
2380     return true;
2381   }
2382 
2383   switch (ValType.getObjCLifetime()) {
2384   case Qualifiers::OCL_None:
2385   case Qualifiers::OCL_ExplicitNone:
2386     // okay
2387     break;
2388 
2389   case Qualifiers::OCL_Weak:
2390   case Qualifiers::OCL_Strong:
2391   case Qualifiers::OCL_Autoreleasing:
2392     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2393         << ValType << PointerArg->getSourceRange();
2394     return true;
2395   }
2396 
2397   if (IsLdrex) {
2398     TheCall->setType(ValType);
2399     return false;
2400   }
2401 
2402   // Initialize the argument to be stored.
2403   ExprResult ValArg = TheCall->getArg(0);
2404   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2405       Context, ValType, /*consume*/ false);
2406   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2407   if (ValArg.isInvalid())
2408     return true;
2409   TheCall->setArg(0, ValArg.get());
2410 
2411   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2412   // but the custom checker bypasses all default analysis.
2413   TheCall->setType(Context.IntTy);
2414   return false;
2415 }
2416 
2417 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2418                                        CallExpr *TheCall) {
2419   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2420       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2421       BuiltinID == ARM::BI__builtin_arm_strex ||
2422       BuiltinID == ARM::BI__builtin_arm_stlex) {
2423     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2424   }
2425 
2426   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2427     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2428       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2429   }
2430 
2431   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2432       BuiltinID == ARM::BI__builtin_arm_wsr64)
2433     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2434 
2435   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2436       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2437       BuiltinID == ARM::BI__builtin_arm_wsr ||
2438       BuiltinID == ARM::BI__builtin_arm_wsrp)
2439     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2440 
2441   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2442     return true;
2443   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2444     return true;
2445   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2446     return true;
2447 
2448   // For intrinsics which take an immediate value as part of the instruction,
2449   // range check them here.
2450   // FIXME: VFP Intrinsics should error if VFP not present.
2451   switch (BuiltinID) {
2452   default: return false;
2453   case ARM::BI__builtin_arm_ssat:
2454     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2455   case ARM::BI__builtin_arm_usat:
2456     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2457   case ARM::BI__builtin_arm_ssat16:
2458     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2459   case ARM::BI__builtin_arm_usat16:
2460     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2461   case ARM::BI__builtin_arm_vcvtr_f:
2462   case ARM::BI__builtin_arm_vcvtr_d:
2463     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2464   case ARM::BI__builtin_arm_dmb:
2465   case ARM::BI__builtin_arm_dsb:
2466   case ARM::BI__builtin_arm_isb:
2467   case ARM::BI__builtin_arm_dbg:
2468     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2469   case ARM::BI__builtin_arm_cdp:
2470   case ARM::BI__builtin_arm_cdp2:
2471   case ARM::BI__builtin_arm_mcr:
2472   case ARM::BI__builtin_arm_mcr2:
2473   case ARM::BI__builtin_arm_mrc:
2474   case ARM::BI__builtin_arm_mrc2:
2475   case ARM::BI__builtin_arm_mcrr:
2476   case ARM::BI__builtin_arm_mcrr2:
2477   case ARM::BI__builtin_arm_mrrc:
2478   case ARM::BI__builtin_arm_mrrc2:
2479   case ARM::BI__builtin_arm_ldc:
2480   case ARM::BI__builtin_arm_ldcl:
2481   case ARM::BI__builtin_arm_ldc2:
2482   case ARM::BI__builtin_arm_ldc2l:
2483   case ARM::BI__builtin_arm_stc:
2484   case ARM::BI__builtin_arm_stcl:
2485   case ARM::BI__builtin_arm_stc2:
2486   case ARM::BI__builtin_arm_stc2l:
2487     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2488            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2489                                         /*WantCDE*/ false);
2490   }
2491 }
2492 
2493 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2494                                            unsigned BuiltinID,
2495                                            CallExpr *TheCall) {
2496   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2497       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2498       BuiltinID == AArch64::BI__builtin_arm_strex ||
2499       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2500     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2501   }
2502 
2503   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2504     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2505       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2506       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2507       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2508   }
2509 
2510   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2511       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2512     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2513 
2514   // Memory Tagging Extensions (MTE) Intrinsics
2515   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2516       BuiltinID == AArch64::BI__builtin_arm_addg ||
2517       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2518       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2519       BuiltinID == AArch64::BI__builtin_arm_stg ||
2520       BuiltinID == AArch64::BI__builtin_arm_subp) {
2521     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2522   }
2523 
2524   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2525       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2526       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2527       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2528     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2529 
2530   // Only check the valid encoding range. Any constant in this range would be
2531   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2532   // an exception for incorrect registers. This matches MSVC behavior.
2533   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2534       BuiltinID == AArch64::BI_WriteStatusReg)
2535     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2536 
2537   if (BuiltinID == AArch64::BI__getReg)
2538     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2539 
2540   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2541     return true;
2542 
2543   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2544     return true;
2545 
2546   // For intrinsics which take an immediate value as part of the instruction,
2547   // range check them here.
2548   unsigned i = 0, l = 0, u = 0;
2549   switch (BuiltinID) {
2550   default: return false;
2551   case AArch64::BI__builtin_arm_dmb:
2552   case AArch64::BI__builtin_arm_dsb:
2553   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2554   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2555   }
2556 
2557   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2558 }
2559 
2560 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2561   if (Arg->getType()->getAsPlaceholderType())
2562     return false;
2563 
2564   // The first argument needs to be a record field access.
2565   // If it is an array element access, we delay decision
2566   // to BPF backend to check whether the access is a
2567   // field access or not.
2568   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2569           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2570           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2571 }
2572 
2573 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2574                             QualType VectorTy, QualType EltTy) {
2575   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2576   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2577     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2578         << Call->getSourceRange() << VectorEltTy << EltTy;
2579     return false;
2580   }
2581   return true;
2582 }
2583 
2584 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2585   QualType ArgType = Arg->getType();
2586   if (ArgType->getAsPlaceholderType())
2587     return false;
2588 
2589   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2590   // format:
2591   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2592   //   2. <type> var;
2593   //      __builtin_preserve_type_info(var, flag);
2594   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2595       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2596     return false;
2597 
2598   // Typedef type.
2599   if (ArgType->getAs<TypedefType>())
2600     return true;
2601 
2602   // Record type or Enum type.
2603   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2604   if (const auto *RT = Ty->getAs<RecordType>()) {
2605     if (!RT->getDecl()->getDeclName().isEmpty())
2606       return true;
2607   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2608     if (!ET->getDecl()->getDeclName().isEmpty())
2609       return true;
2610   }
2611 
2612   return false;
2613 }
2614 
2615 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2616   QualType ArgType = Arg->getType();
2617   if (ArgType->getAsPlaceholderType())
2618     return false;
2619 
2620   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2621   // format:
2622   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2623   //                                 flag);
2624   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2625   if (!UO)
2626     return false;
2627 
2628   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2629   if (!CE)
2630     return false;
2631   if (CE->getCastKind() != CK_IntegralToPointer &&
2632       CE->getCastKind() != CK_NullToPointer)
2633     return false;
2634 
2635   // The integer must be from an EnumConstantDecl.
2636   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2637   if (!DR)
2638     return false;
2639 
2640   const EnumConstantDecl *Enumerator =
2641       dyn_cast<EnumConstantDecl>(DR->getDecl());
2642   if (!Enumerator)
2643     return false;
2644 
2645   // The type must be EnumType.
2646   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2647   const auto *ET = Ty->getAs<EnumType>();
2648   if (!ET)
2649     return false;
2650 
2651   // The enum value must be supported.
2652   for (auto *EDI : ET->getDecl()->enumerators()) {
2653     if (EDI == Enumerator)
2654       return true;
2655   }
2656 
2657   return false;
2658 }
2659 
2660 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2661                                        CallExpr *TheCall) {
2662   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2663           BuiltinID == BPF::BI__builtin_btf_type_id ||
2664           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2665           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2666          "unexpected BPF builtin");
2667 
2668   if (checkArgCount(*this, TheCall, 2))
2669     return true;
2670 
2671   // The second argument needs to be a constant int
2672   Expr *Arg = TheCall->getArg(1);
2673   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2674   diag::kind kind;
2675   if (!Value) {
2676     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2677       kind = diag::err_preserve_field_info_not_const;
2678     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2679       kind = diag::err_btf_type_id_not_const;
2680     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2681       kind = diag::err_preserve_type_info_not_const;
2682     else
2683       kind = diag::err_preserve_enum_value_not_const;
2684     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2685     return true;
2686   }
2687 
2688   // The first argument
2689   Arg = TheCall->getArg(0);
2690   bool InvalidArg = false;
2691   bool ReturnUnsignedInt = true;
2692   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2693     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2694       InvalidArg = true;
2695       kind = diag::err_preserve_field_info_not_field;
2696     }
2697   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2698     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2699       InvalidArg = true;
2700       kind = diag::err_preserve_type_info_invalid;
2701     }
2702   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2703     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2704       InvalidArg = true;
2705       kind = diag::err_preserve_enum_value_invalid;
2706     }
2707     ReturnUnsignedInt = false;
2708   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2709     ReturnUnsignedInt = false;
2710   }
2711 
2712   if (InvalidArg) {
2713     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2714     return true;
2715   }
2716 
2717   if (ReturnUnsignedInt)
2718     TheCall->setType(Context.UnsignedIntTy);
2719   else
2720     TheCall->setType(Context.UnsignedLongTy);
2721   return false;
2722 }
2723 
2724 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2725   struct ArgInfo {
2726     uint8_t OpNum;
2727     bool IsSigned;
2728     uint8_t BitWidth;
2729     uint8_t Align;
2730   };
2731   struct BuiltinInfo {
2732     unsigned BuiltinID;
2733     ArgInfo Infos[2];
2734   };
2735 
2736   static BuiltinInfo Infos[] = {
2737     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2738     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2739     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2740     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2741     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2742     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2743     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2744     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2745     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2746     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2747     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2748 
2749     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2750     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2751     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2752     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2753     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2754     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2755     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2756     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2757     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2759     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2760 
2761     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2762     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2791     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2813                                                       {{ 1, false, 6,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2821                                                       {{ 1, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2828                                                        { 2, false, 5,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2830                                                        { 2, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2832                                                        { 3, false, 5,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2834                                                        { 3, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2851                                                       {{ 2, false, 4,  0 },
2852                                                        { 3, false, 5,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2854                                                       {{ 2, false, 4,  0 },
2855                                                        { 3, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2857                                                       {{ 2, false, 4,  0 },
2858                                                        { 3, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2860                                                       {{ 2, false, 4,  0 },
2861                                                        { 3, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2873                                                        { 2, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2875                                                        { 2, false, 6,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2885                                                       {{ 1, false, 4,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2888                                                       {{ 1, false, 4,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2909                                                       {{ 3, false, 1,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2914                                                       {{ 3, false, 1,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2919                                                       {{ 3, false, 1,  0 }} },
2920   };
2921 
2922   // Use a dynamically initialized static to sort the table exactly once on
2923   // first run.
2924   static const bool SortOnce =
2925       (llvm::sort(Infos,
2926                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2927                    return LHS.BuiltinID < RHS.BuiltinID;
2928                  }),
2929        true);
2930   (void)SortOnce;
2931 
2932   const BuiltinInfo *F = llvm::partition_point(
2933       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2934   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2935     return false;
2936 
2937   bool Error = false;
2938 
2939   for (const ArgInfo &A : F->Infos) {
2940     // Ignore empty ArgInfo elements.
2941     if (A.BitWidth == 0)
2942       continue;
2943 
2944     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2945     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2946     if (!A.Align) {
2947       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2948     } else {
2949       unsigned M = 1 << A.Align;
2950       Min *= M;
2951       Max *= M;
2952       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2953                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2954     }
2955   }
2956   return Error;
2957 }
2958 
2959 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2960                                            CallExpr *TheCall) {
2961   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2962 }
2963 
2964 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2965                                         unsigned BuiltinID, CallExpr *TheCall) {
2966   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2967          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2968 }
2969 
2970 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2971                                CallExpr *TheCall) {
2972 
2973   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2974       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2975     if (!TI.hasFeature("dsp"))
2976       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2977   }
2978 
2979   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2980       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2981     if (!TI.hasFeature("dspr2"))
2982       return Diag(TheCall->getBeginLoc(),
2983                   diag::err_mips_builtin_requires_dspr2);
2984   }
2985 
2986   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2987       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2988     if (!TI.hasFeature("msa"))
2989       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2990   }
2991 
2992   return false;
2993 }
2994 
2995 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2996 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2997 // ordering for DSP is unspecified. MSA is ordered by the data format used
2998 // by the underlying instruction i.e., df/m, df/n and then by size.
2999 //
3000 // FIXME: The size tests here should instead be tablegen'd along with the
3001 //        definitions from include/clang/Basic/BuiltinsMips.def.
3002 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3003 //        be too.
3004 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3005   unsigned i = 0, l = 0, u = 0, m = 0;
3006   switch (BuiltinID) {
3007   default: return false;
3008   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3009   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3010   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3011   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3012   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3013   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3014   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3015   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3016   // df/m field.
3017   // These intrinsics take an unsigned 3 bit immediate.
3018   case Mips::BI__builtin_msa_bclri_b:
3019   case Mips::BI__builtin_msa_bnegi_b:
3020   case Mips::BI__builtin_msa_bseti_b:
3021   case Mips::BI__builtin_msa_sat_s_b:
3022   case Mips::BI__builtin_msa_sat_u_b:
3023   case Mips::BI__builtin_msa_slli_b:
3024   case Mips::BI__builtin_msa_srai_b:
3025   case Mips::BI__builtin_msa_srari_b:
3026   case Mips::BI__builtin_msa_srli_b:
3027   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3028   case Mips::BI__builtin_msa_binsli_b:
3029   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3030   // These intrinsics take an unsigned 4 bit immediate.
3031   case Mips::BI__builtin_msa_bclri_h:
3032   case Mips::BI__builtin_msa_bnegi_h:
3033   case Mips::BI__builtin_msa_bseti_h:
3034   case Mips::BI__builtin_msa_sat_s_h:
3035   case Mips::BI__builtin_msa_sat_u_h:
3036   case Mips::BI__builtin_msa_slli_h:
3037   case Mips::BI__builtin_msa_srai_h:
3038   case Mips::BI__builtin_msa_srari_h:
3039   case Mips::BI__builtin_msa_srli_h:
3040   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3041   case Mips::BI__builtin_msa_binsli_h:
3042   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3043   // These intrinsics take an unsigned 5 bit immediate.
3044   // The first block of intrinsics actually have an unsigned 5 bit field,
3045   // not a df/n field.
3046   case Mips::BI__builtin_msa_cfcmsa:
3047   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3048   case Mips::BI__builtin_msa_clei_u_b:
3049   case Mips::BI__builtin_msa_clei_u_h:
3050   case Mips::BI__builtin_msa_clei_u_w:
3051   case Mips::BI__builtin_msa_clei_u_d:
3052   case Mips::BI__builtin_msa_clti_u_b:
3053   case Mips::BI__builtin_msa_clti_u_h:
3054   case Mips::BI__builtin_msa_clti_u_w:
3055   case Mips::BI__builtin_msa_clti_u_d:
3056   case Mips::BI__builtin_msa_maxi_u_b:
3057   case Mips::BI__builtin_msa_maxi_u_h:
3058   case Mips::BI__builtin_msa_maxi_u_w:
3059   case Mips::BI__builtin_msa_maxi_u_d:
3060   case Mips::BI__builtin_msa_mini_u_b:
3061   case Mips::BI__builtin_msa_mini_u_h:
3062   case Mips::BI__builtin_msa_mini_u_w:
3063   case Mips::BI__builtin_msa_mini_u_d:
3064   case Mips::BI__builtin_msa_addvi_b:
3065   case Mips::BI__builtin_msa_addvi_h:
3066   case Mips::BI__builtin_msa_addvi_w:
3067   case Mips::BI__builtin_msa_addvi_d:
3068   case Mips::BI__builtin_msa_bclri_w:
3069   case Mips::BI__builtin_msa_bnegi_w:
3070   case Mips::BI__builtin_msa_bseti_w:
3071   case Mips::BI__builtin_msa_sat_s_w:
3072   case Mips::BI__builtin_msa_sat_u_w:
3073   case Mips::BI__builtin_msa_slli_w:
3074   case Mips::BI__builtin_msa_srai_w:
3075   case Mips::BI__builtin_msa_srari_w:
3076   case Mips::BI__builtin_msa_srli_w:
3077   case Mips::BI__builtin_msa_srlri_w:
3078   case Mips::BI__builtin_msa_subvi_b:
3079   case Mips::BI__builtin_msa_subvi_h:
3080   case Mips::BI__builtin_msa_subvi_w:
3081   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3082   case Mips::BI__builtin_msa_binsli_w:
3083   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3084   // These intrinsics take an unsigned 6 bit immediate.
3085   case Mips::BI__builtin_msa_bclri_d:
3086   case Mips::BI__builtin_msa_bnegi_d:
3087   case Mips::BI__builtin_msa_bseti_d:
3088   case Mips::BI__builtin_msa_sat_s_d:
3089   case Mips::BI__builtin_msa_sat_u_d:
3090   case Mips::BI__builtin_msa_slli_d:
3091   case Mips::BI__builtin_msa_srai_d:
3092   case Mips::BI__builtin_msa_srari_d:
3093   case Mips::BI__builtin_msa_srli_d:
3094   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3095   case Mips::BI__builtin_msa_binsli_d:
3096   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3097   // These intrinsics take a signed 5 bit immediate.
3098   case Mips::BI__builtin_msa_ceqi_b:
3099   case Mips::BI__builtin_msa_ceqi_h:
3100   case Mips::BI__builtin_msa_ceqi_w:
3101   case Mips::BI__builtin_msa_ceqi_d:
3102   case Mips::BI__builtin_msa_clti_s_b:
3103   case Mips::BI__builtin_msa_clti_s_h:
3104   case Mips::BI__builtin_msa_clti_s_w:
3105   case Mips::BI__builtin_msa_clti_s_d:
3106   case Mips::BI__builtin_msa_clei_s_b:
3107   case Mips::BI__builtin_msa_clei_s_h:
3108   case Mips::BI__builtin_msa_clei_s_w:
3109   case Mips::BI__builtin_msa_clei_s_d:
3110   case Mips::BI__builtin_msa_maxi_s_b:
3111   case Mips::BI__builtin_msa_maxi_s_h:
3112   case Mips::BI__builtin_msa_maxi_s_w:
3113   case Mips::BI__builtin_msa_maxi_s_d:
3114   case Mips::BI__builtin_msa_mini_s_b:
3115   case Mips::BI__builtin_msa_mini_s_h:
3116   case Mips::BI__builtin_msa_mini_s_w:
3117   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3118   // These intrinsics take an unsigned 8 bit immediate.
3119   case Mips::BI__builtin_msa_andi_b:
3120   case Mips::BI__builtin_msa_nori_b:
3121   case Mips::BI__builtin_msa_ori_b:
3122   case Mips::BI__builtin_msa_shf_b:
3123   case Mips::BI__builtin_msa_shf_h:
3124   case Mips::BI__builtin_msa_shf_w:
3125   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3126   case Mips::BI__builtin_msa_bseli_b:
3127   case Mips::BI__builtin_msa_bmnzi_b:
3128   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3129   // df/n format
3130   // These intrinsics take an unsigned 4 bit immediate.
3131   case Mips::BI__builtin_msa_copy_s_b:
3132   case Mips::BI__builtin_msa_copy_u_b:
3133   case Mips::BI__builtin_msa_insve_b:
3134   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3135   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3136   // These intrinsics take an unsigned 3 bit immediate.
3137   case Mips::BI__builtin_msa_copy_s_h:
3138   case Mips::BI__builtin_msa_copy_u_h:
3139   case Mips::BI__builtin_msa_insve_h:
3140   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3141   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3142   // These intrinsics take an unsigned 2 bit immediate.
3143   case Mips::BI__builtin_msa_copy_s_w:
3144   case Mips::BI__builtin_msa_copy_u_w:
3145   case Mips::BI__builtin_msa_insve_w:
3146   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3147   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3148   // These intrinsics take an unsigned 1 bit immediate.
3149   case Mips::BI__builtin_msa_copy_s_d:
3150   case Mips::BI__builtin_msa_copy_u_d:
3151   case Mips::BI__builtin_msa_insve_d:
3152   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3153   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3154   // Memory offsets and immediate loads.
3155   // These intrinsics take a signed 10 bit immediate.
3156   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3157   case Mips::BI__builtin_msa_ldi_h:
3158   case Mips::BI__builtin_msa_ldi_w:
3159   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3160   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3161   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3162   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3163   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3164   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3165   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3166   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3167   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3168   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3169   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3170   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3171   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3172   }
3173 
3174   if (!m)
3175     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3176 
3177   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3178          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3179 }
3180 
3181 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3182 /// advancing the pointer over the consumed characters. The decoded type is
3183 /// returned. If the decoded type represents a constant integer with a
3184 /// constraint on its value then Mask is set to that value. The type descriptors
3185 /// used in Str are specific to PPC MMA builtins and are documented in the file
3186 /// defining the PPC builtins.
3187 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3188                                         unsigned &Mask) {
3189   bool RequireICE = false;
3190   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3191   switch (*Str++) {
3192   case 'V':
3193     return Context.getVectorType(Context.UnsignedCharTy, 16,
3194                                  VectorType::VectorKind::AltiVecVector);
3195   case 'i': {
3196     char *End;
3197     unsigned size = strtoul(Str, &End, 10);
3198     assert(End != Str && "Missing constant parameter constraint");
3199     Str = End;
3200     Mask = size;
3201     return Context.IntTy;
3202   }
3203   case 'W': {
3204     char *End;
3205     unsigned size = strtoul(Str, &End, 10);
3206     assert(End != Str && "Missing PowerPC MMA type size");
3207     Str = End;
3208     QualType Type;
3209     switch (size) {
3210   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3211     case size: Type = Context.Id##Ty; break;
3212   #include "clang/Basic/PPCTypes.def"
3213     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3214     }
3215     bool CheckVectorArgs = false;
3216     while (!CheckVectorArgs) {
3217       switch (*Str++) {
3218       case '*':
3219         Type = Context.getPointerType(Type);
3220         break;
3221       case 'C':
3222         Type = Type.withConst();
3223         break;
3224       default:
3225         CheckVectorArgs = true;
3226         --Str;
3227         break;
3228       }
3229     }
3230     return Type;
3231   }
3232   default:
3233     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3234   }
3235 }
3236 
3237 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3238                                        CallExpr *TheCall) {
3239   unsigned i = 0, l = 0, u = 0;
3240   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3241                       BuiltinID == PPC::BI__builtin_divdeu ||
3242                       BuiltinID == PPC::BI__builtin_bpermd;
3243   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3244   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3245                        BuiltinID == PPC::BI__builtin_divweu ||
3246                        BuiltinID == PPC::BI__builtin_divde ||
3247                        BuiltinID == PPC::BI__builtin_divdeu;
3248 
3249   if (Is64BitBltin && !IsTarget64Bit)
3250     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3251            << TheCall->getSourceRange();
3252 
3253   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3254       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3255     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3256            << TheCall->getSourceRange();
3257 
3258   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3259     if (!TI.hasFeature("vsx"))
3260       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3261              << TheCall->getSourceRange();
3262     return false;
3263   };
3264 
3265   switch (BuiltinID) {
3266   default: return false;
3267   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3268   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3269     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3270            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3271   case PPC::BI__builtin_altivec_dss:
3272     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3273   case PPC::BI__builtin_tbegin:
3274   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3275   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3276   case PPC::BI__builtin_tabortwc:
3277   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3278   case PPC::BI__builtin_tabortwci:
3279   case PPC::BI__builtin_tabortdci:
3280     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3281            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3282   case PPC::BI__builtin_altivec_dst:
3283   case PPC::BI__builtin_altivec_dstt:
3284   case PPC::BI__builtin_altivec_dstst:
3285   case PPC::BI__builtin_altivec_dststt:
3286     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3287   case PPC::BI__builtin_vsx_xxpermdi:
3288   case PPC::BI__builtin_vsx_xxsldwi:
3289     return SemaBuiltinVSX(TheCall);
3290   case PPC::BI__builtin_unpack_vector_int128:
3291     return SemaVSXCheck(TheCall) ||
3292            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3293   case PPC::BI__builtin_pack_vector_int128:
3294     return SemaVSXCheck(TheCall);
3295   case PPC::BI__builtin_altivec_vgnb:
3296      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3297   case PPC::BI__builtin_altivec_vec_replace_elt:
3298   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3299     QualType VecTy = TheCall->getArg(0)->getType();
3300     QualType EltTy = TheCall->getArg(1)->getType();
3301     unsigned Width = Context.getIntWidth(EltTy);
3302     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3303            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3304   }
3305   case PPC::BI__builtin_vsx_xxeval:
3306      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3307   case PPC::BI__builtin_altivec_vsldbi:
3308      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3309   case PPC::BI__builtin_altivec_vsrdbi:
3310      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3311   case PPC::BI__builtin_vsx_xxpermx:
3312      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3313 #define CUSTOM_BUILTIN(Name, Types, Acc) \
3314   case PPC::BI__builtin_##Name: \
3315     return SemaBuiltinPPCMMACall(TheCall, Types);
3316 #include "clang/Basic/BuiltinsPPC.def"
3317   }
3318   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3319 }
3320 
3321 // Check if the given type is a non-pointer PPC MMA type. This function is used
3322 // in Sema to prevent invalid uses of restricted PPC MMA types.
3323 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3324   if (Type->isPointerType() || Type->isArrayType())
3325     return false;
3326 
3327   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3328 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3329   if (false
3330 #include "clang/Basic/PPCTypes.def"
3331      ) {
3332     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3333     return true;
3334   }
3335   return false;
3336 }
3337 
3338 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3339                                           CallExpr *TheCall) {
3340   // position of memory order and scope arguments in the builtin
3341   unsigned OrderIndex, ScopeIndex;
3342   switch (BuiltinID) {
3343   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3344   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3345   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3346   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3347     OrderIndex = 2;
3348     ScopeIndex = 3;
3349     break;
3350   case AMDGPU::BI__builtin_amdgcn_fence:
3351     OrderIndex = 0;
3352     ScopeIndex = 1;
3353     break;
3354   default:
3355     return false;
3356   }
3357 
3358   ExprResult Arg = TheCall->getArg(OrderIndex);
3359   auto ArgExpr = Arg.get();
3360   Expr::EvalResult ArgResult;
3361 
3362   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3363     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3364            << ArgExpr->getType();
3365   int ord = ArgResult.Val.getInt().getZExtValue();
3366 
3367   // Check valididty of memory ordering as per C11 / C++11's memody model.
3368   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3369   case llvm::AtomicOrderingCABI::acquire:
3370   case llvm::AtomicOrderingCABI::release:
3371   case llvm::AtomicOrderingCABI::acq_rel:
3372   case llvm::AtomicOrderingCABI::seq_cst:
3373     break;
3374   default: {
3375     return Diag(ArgExpr->getBeginLoc(),
3376                 diag::warn_atomic_op_has_invalid_memory_order)
3377            << ArgExpr->getSourceRange();
3378   }
3379   }
3380 
3381   Arg = TheCall->getArg(ScopeIndex);
3382   ArgExpr = Arg.get();
3383   Expr::EvalResult ArgResult1;
3384   // Check that sync scope is a constant literal
3385   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3386     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3387            << ArgExpr->getType();
3388 
3389   return false;
3390 }
3391 
3392 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3393                                          unsigned BuiltinID,
3394                                          CallExpr *TheCall) {
3395   switch (BuiltinID) {
3396   default:
3397     break;
3398 #define BUILTIN(ID, TYPE, ATTRS) case RISCV::BI##ID:
3399 #include "clang/Basic/BuiltinsRISCV.def"
3400     if (!TI.hasFeature("experimental-v"))
3401       return Diag(TheCall->getBeginLoc(), diag::err_riscvv_builtin_requires_v)
3402              << TheCall->getSourceRange();
3403     break;
3404   }
3405 
3406   return false;
3407 }
3408 
3409 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3410                                            CallExpr *TheCall) {
3411   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3412     Expr *Arg = TheCall->getArg(0);
3413     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3414       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3415         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3416                << Arg->getSourceRange();
3417   }
3418 
3419   // For intrinsics which take an immediate value as part of the instruction,
3420   // range check them here.
3421   unsigned i = 0, l = 0, u = 0;
3422   switch (BuiltinID) {
3423   default: return false;
3424   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3425   case SystemZ::BI__builtin_s390_verimb:
3426   case SystemZ::BI__builtin_s390_verimh:
3427   case SystemZ::BI__builtin_s390_verimf:
3428   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3429   case SystemZ::BI__builtin_s390_vfaeb:
3430   case SystemZ::BI__builtin_s390_vfaeh:
3431   case SystemZ::BI__builtin_s390_vfaef:
3432   case SystemZ::BI__builtin_s390_vfaebs:
3433   case SystemZ::BI__builtin_s390_vfaehs:
3434   case SystemZ::BI__builtin_s390_vfaefs:
3435   case SystemZ::BI__builtin_s390_vfaezb:
3436   case SystemZ::BI__builtin_s390_vfaezh:
3437   case SystemZ::BI__builtin_s390_vfaezf:
3438   case SystemZ::BI__builtin_s390_vfaezbs:
3439   case SystemZ::BI__builtin_s390_vfaezhs:
3440   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3441   case SystemZ::BI__builtin_s390_vfisb:
3442   case SystemZ::BI__builtin_s390_vfidb:
3443     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3444            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3445   case SystemZ::BI__builtin_s390_vftcisb:
3446   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3447   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3448   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3449   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3450   case SystemZ::BI__builtin_s390_vstrcb:
3451   case SystemZ::BI__builtin_s390_vstrch:
3452   case SystemZ::BI__builtin_s390_vstrcf:
3453   case SystemZ::BI__builtin_s390_vstrczb:
3454   case SystemZ::BI__builtin_s390_vstrczh:
3455   case SystemZ::BI__builtin_s390_vstrczf:
3456   case SystemZ::BI__builtin_s390_vstrcbs:
3457   case SystemZ::BI__builtin_s390_vstrchs:
3458   case SystemZ::BI__builtin_s390_vstrcfs:
3459   case SystemZ::BI__builtin_s390_vstrczbs:
3460   case SystemZ::BI__builtin_s390_vstrczhs:
3461   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3462   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3463   case SystemZ::BI__builtin_s390_vfminsb:
3464   case SystemZ::BI__builtin_s390_vfmaxsb:
3465   case SystemZ::BI__builtin_s390_vfmindb:
3466   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3467   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3468   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3469   }
3470   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3471 }
3472 
3473 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3474 /// This checks that the target supports __builtin_cpu_supports and
3475 /// that the string argument is constant and valid.
3476 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3477                                    CallExpr *TheCall) {
3478   Expr *Arg = TheCall->getArg(0);
3479 
3480   // Check if the argument is a string literal.
3481   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3482     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3483            << Arg->getSourceRange();
3484 
3485   // Check the contents of the string.
3486   StringRef Feature =
3487       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3488   if (!TI.validateCpuSupports(Feature))
3489     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3490            << Arg->getSourceRange();
3491   return false;
3492 }
3493 
3494 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3495 /// This checks that the target supports __builtin_cpu_is and
3496 /// that the string argument is constant and valid.
3497 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3498   Expr *Arg = TheCall->getArg(0);
3499 
3500   // Check if the argument is a string literal.
3501   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3502     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3503            << Arg->getSourceRange();
3504 
3505   // Check the contents of the string.
3506   StringRef Feature =
3507       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3508   if (!TI.validateCpuIs(Feature))
3509     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3510            << Arg->getSourceRange();
3511   return false;
3512 }
3513 
3514 // Check if the rounding mode is legal.
3515 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3516   // Indicates if this instruction has rounding control or just SAE.
3517   bool HasRC = false;
3518 
3519   unsigned ArgNum = 0;
3520   switch (BuiltinID) {
3521   default:
3522     return false;
3523   case X86::BI__builtin_ia32_vcvttsd2si32:
3524   case X86::BI__builtin_ia32_vcvttsd2si64:
3525   case X86::BI__builtin_ia32_vcvttsd2usi32:
3526   case X86::BI__builtin_ia32_vcvttsd2usi64:
3527   case X86::BI__builtin_ia32_vcvttss2si32:
3528   case X86::BI__builtin_ia32_vcvttss2si64:
3529   case X86::BI__builtin_ia32_vcvttss2usi32:
3530   case X86::BI__builtin_ia32_vcvttss2usi64:
3531     ArgNum = 1;
3532     break;
3533   case X86::BI__builtin_ia32_maxpd512:
3534   case X86::BI__builtin_ia32_maxps512:
3535   case X86::BI__builtin_ia32_minpd512:
3536   case X86::BI__builtin_ia32_minps512:
3537     ArgNum = 2;
3538     break;
3539   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3540   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3541   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3542   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3543   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3544   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3545   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3546   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3547   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3548   case X86::BI__builtin_ia32_exp2pd_mask:
3549   case X86::BI__builtin_ia32_exp2ps_mask:
3550   case X86::BI__builtin_ia32_getexppd512_mask:
3551   case X86::BI__builtin_ia32_getexpps512_mask:
3552   case X86::BI__builtin_ia32_rcp28pd_mask:
3553   case X86::BI__builtin_ia32_rcp28ps_mask:
3554   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3555   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3556   case X86::BI__builtin_ia32_vcomisd:
3557   case X86::BI__builtin_ia32_vcomiss:
3558   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3559     ArgNum = 3;
3560     break;
3561   case X86::BI__builtin_ia32_cmppd512_mask:
3562   case X86::BI__builtin_ia32_cmpps512_mask:
3563   case X86::BI__builtin_ia32_cmpsd_mask:
3564   case X86::BI__builtin_ia32_cmpss_mask:
3565   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3566   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3567   case X86::BI__builtin_ia32_getexpss128_round_mask:
3568   case X86::BI__builtin_ia32_getmantpd512_mask:
3569   case X86::BI__builtin_ia32_getmantps512_mask:
3570   case X86::BI__builtin_ia32_maxsd_round_mask:
3571   case X86::BI__builtin_ia32_maxss_round_mask:
3572   case X86::BI__builtin_ia32_minsd_round_mask:
3573   case X86::BI__builtin_ia32_minss_round_mask:
3574   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3575   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3576   case X86::BI__builtin_ia32_reducepd512_mask:
3577   case X86::BI__builtin_ia32_reduceps512_mask:
3578   case X86::BI__builtin_ia32_rndscalepd_mask:
3579   case X86::BI__builtin_ia32_rndscaleps_mask:
3580   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3581   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3582     ArgNum = 4;
3583     break;
3584   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3585   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3586   case X86::BI__builtin_ia32_fixupimmps512_mask:
3587   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3588   case X86::BI__builtin_ia32_fixupimmsd_mask:
3589   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3590   case X86::BI__builtin_ia32_fixupimmss_mask:
3591   case X86::BI__builtin_ia32_fixupimmss_maskz:
3592   case X86::BI__builtin_ia32_getmantsd_round_mask:
3593   case X86::BI__builtin_ia32_getmantss_round_mask:
3594   case X86::BI__builtin_ia32_rangepd512_mask:
3595   case X86::BI__builtin_ia32_rangeps512_mask:
3596   case X86::BI__builtin_ia32_rangesd128_round_mask:
3597   case X86::BI__builtin_ia32_rangess128_round_mask:
3598   case X86::BI__builtin_ia32_reducesd_mask:
3599   case X86::BI__builtin_ia32_reducess_mask:
3600   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3601   case X86::BI__builtin_ia32_rndscaless_round_mask:
3602     ArgNum = 5;
3603     break;
3604   case X86::BI__builtin_ia32_vcvtsd2si64:
3605   case X86::BI__builtin_ia32_vcvtsd2si32:
3606   case X86::BI__builtin_ia32_vcvtsd2usi32:
3607   case X86::BI__builtin_ia32_vcvtsd2usi64:
3608   case X86::BI__builtin_ia32_vcvtss2si32:
3609   case X86::BI__builtin_ia32_vcvtss2si64:
3610   case X86::BI__builtin_ia32_vcvtss2usi32:
3611   case X86::BI__builtin_ia32_vcvtss2usi64:
3612   case X86::BI__builtin_ia32_sqrtpd512:
3613   case X86::BI__builtin_ia32_sqrtps512:
3614     ArgNum = 1;
3615     HasRC = true;
3616     break;
3617   case X86::BI__builtin_ia32_addpd512:
3618   case X86::BI__builtin_ia32_addps512:
3619   case X86::BI__builtin_ia32_divpd512:
3620   case X86::BI__builtin_ia32_divps512:
3621   case X86::BI__builtin_ia32_mulpd512:
3622   case X86::BI__builtin_ia32_mulps512:
3623   case X86::BI__builtin_ia32_subpd512:
3624   case X86::BI__builtin_ia32_subps512:
3625   case X86::BI__builtin_ia32_cvtsi2sd64:
3626   case X86::BI__builtin_ia32_cvtsi2ss32:
3627   case X86::BI__builtin_ia32_cvtsi2ss64:
3628   case X86::BI__builtin_ia32_cvtusi2sd64:
3629   case X86::BI__builtin_ia32_cvtusi2ss32:
3630   case X86::BI__builtin_ia32_cvtusi2ss64:
3631     ArgNum = 2;
3632     HasRC = true;
3633     break;
3634   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3635   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3636   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3637   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3638   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3639   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3640   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3641   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3642   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3643   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3644   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3645   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3646   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3647   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3648   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3649     ArgNum = 3;
3650     HasRC = true;
3651     break;
3652   case X86::BI__builtin_ia32_addss_round_mask:
3653   case X86::BI__builtin_ia32_addsd_round_mask:
3654   case X86::BI__builtin_ia32_divss_round_mask:
3655   case X86::BI__builtin_ia32_divsd_round_mask:
3656   case X86::BI__builtin_ia32_mulss_round_mask:
3657   case X86::BI__builtin_ia32_mulsd_round_mask:
3658   case X86::BI__builtin_ia32_subss_round_mask:
3659   case X86::BI__builtin_ia32_subsd_round_mask:
3660   case X86::BI__builtin_ia32_scalefpd512_mask:
3661   case X86::BI__builtin_ia32_scalefps512_mask:
3662   case X86::BI__builtin_ia32_scalefsd_round_mask:
3663   case X86::BI__builtin_ia32_scalefss_round_mask:
3664   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3665   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3666   case X86::BI__builtin_ia32_sqrtss_round_mask:
3667   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3668   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3669   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3670   case X86::BI__builtin_ia32_vfmaddss3_mask:
3671   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3672   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3673   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3674   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3675   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3676   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3677   case X86::BI__builtin_ia32_vfmaddps512_mask:
3678   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3679   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3680   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3681   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3682   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3683   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3684   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3685   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3686   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3687   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3688   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3689     ArgNum = 4;
3690     HasRC = true;
3691     break;
3692   }
3693 
3694   llvm::APSInt Result;
3695 
3696   // We can't check the value of a dependent argument.
3697   Expr *Arg = TheCall->getArg(ArgNum);
3698   if (Arg->isTypeDependent() || Arg->isValueDependent())
3699     return false;
3700 
3701   // Check constant-ness first.
3702   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3703     return true;
3704 
3705   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3706   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3707   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3708   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3709   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3710       Result == 8/*ROUND_NO_EXC*/ ||
3711       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3712       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3713     return false;
3714 
3715   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3716          << Arg->getSourceRange();
3717 }
3718 
3719 // Check if the gather/scatter scale is legal.
3720 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3721                                              CallExpr *TheCall) {
3722   unsigned ArgNum = 0;
3723   switch (BuiltinID) {
3724   default:
3725     return false;
3726   case X86::BI__builtin_ia32_gatherpfdpd:
3727   case X86::BI__builtin_ia32_gatherpfdps:
3728   case X86::BI__builtin_ia32_gatherpfqpd:
3729   case X86::BI__builtin_ia32_gatherpfqps:
3730   case X86::BI__builtin_ia32_scatterpfdpd:
3731   case X86::BI__builtin_ia32_scatterpfdps:
3732   case X86::BI__builtin_ia32_scatterpfqpd:
3733   case X86::BI__builtin_ia32_scatterpfqps:
3734     ArgNum = 3;
3735     break;
3736   case X86::BI__builtin_ia32_gatherd_pd:
3737   case X86::BI__builtin_ia32_gatherd_pd256:
3738   case X86::BI__builtin_ia32_gatherq_pd:
3739   case X86::BI__builtin_ia32_gatherq_pd256:
3740   case X86::BI__builtin_ia32_gatherd_ps:
3741   case X86::BI__builtin_ia32_gatherd_ps256:
3742   case X86::BI__builtin_ia32_gatherq_ps:
3743   case X86::BI__builtin_ia32_gatherq_ps256:
3744   case X86::BI__builtin_ia32_gatherd_q:
3745   case X86::BI__builtin_ia32_gatherd_q256:
3746   case X86::BI__builtin_ia32_gatherq_q:
3747   case X86::BI__builtin_ia32_gatherq_q256:
3748   case X86::BI__builtin_ia32_gatherd_d:
3749   case X86::BI__builtin_ia32_gatherd_d256:
3750   case X86::BI__builtin_ia32_gatherq_d:
3751   case X86::BI__builtin_ia32_gatherq_d256:
3752   case X86::BI__builtin_ia32_gather3div2df:
3753   case X86::BI__builtin_ia32_gather3div2di:
3754   case X86::BI__builtin_ia32_gather3div4df:
3755   case X86::BI__builtin_ia32_gather3div4di:
3756   case X86::BI__builtin_ia32_gather3div4sf:
3757   case X86::BI__builtin_ia32_gather3div4si:
3758   case X86::BI__builtin_ia32_gather3div8sf:
3759   case X86::BI__builtin_ia32_gather3div8si:
3760   case X86::BI__builtin_ia32_gather3siv2df:
3761   case X86::BI__builtin_ia32_gather3siv2di:
3762   case X86::BI__builtin_ia32_gather3siv4df:
3763   case X86::BI__builtin_ia32_gather3siv4di:
3764   case X86::BI__builtin_ia32_gather3siv4sf:
3765   case X86::BI__builtin_ia32_gather3siv4si:
3766   case X86::BI__builtin_ia32_gather3siv8sf:
3767   case X86::BI__builtin_ia32_gather3siv8si:
3768   case X86::BI__builtin_ia32_gathersiv8df:
3769   case X86::BI__builtin_ia32_gathersiv16sf:
3770   case X86::BI__builtin_ia32_gatherdiv8df:
3771   case X86::BI__builtin_ia32_gatherdiv16sf:
3772   case X86::BI__builtin_ia32_gathersiv8di:
3773   case X86::BI__builtin_ia32_gathersiv16si:
3774   case X86::BI__builtin_ia32_gatherdiv8di:
3775   case X86::BI__builtin_ia32_gatherdiv16si:
3776   case X86::BI__builtin_ia32_scatterdiv2df:
3777   case X86::BI__builtin_ia32_scatterdiv2di:
3778   case X86::BI__builtin_ia32_scatterdiv4df:
3779   case X86::BI__builtin_ia32_scatterdiv4di:
3780   case X86::BI__builtin_ia32_scatterdiv4sf:
3781   case X86::BI__builtin_ia32_scatterdiv4si:
3782   case X86::BI__builtin_ia32_scatterdiv8sf:
3783   case X86::BI__builtin_ia32_scatterdiv8si:
3784   case X86::BI__builtin_ia32_scattersiv2df:
3785   case X86::BI__builtin_ia32_scattersiv2di:
3786   case X86::BI__builtin_ia32_scattersiv4df:
3787   case X86::BI__builtin_ia32_scattersiv4di:
3788   case X86::BI__builtin_ia32_scattersiv4sf:
3789   case X86::BI__builtin_ia32_scattersiv4si:
3790   case X86::BI__builtin_ia32_scattersiv8sf:
3791   case X86::BI__builtin_ia32_scattersiv8si:
3792   case X86::BI__builtin_ia32_scattersiv8df:
3793   case X86::BI__builtin_ia32_scattersiv16sf:
3794   case X86::BI__builtin_ia32_scatterdiv8df:
3795   case X86::BI__builtin_ia32_scatterdiv16sf:
3796   case X86::BI__builtin_ia32_scattersiv8di:
3797   case X86::BI__builtin_ia32_scattersiv16si:
3798   case X86::BI__builtin_ia32_scatterdiv8di:
3799   case X86::BI__builtin_ia32_scatterdiv16si:
3800     ArgNum = 4;
3801     break;
3802   }
3803 
3804   llvm::APSInt Result;
3805 
3806   // We can't check the value of a dependent argument.
3807   Expr *Arg = TheCall->getArg(ArgNum);
3808   if (Arg->isTypeDependent() || Arg->isValueDependent())
3809     return false;
3810 
3811   // Check constant-ness first.
3812   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3813     return true;
3814 
3815   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3816     return false;
3817 
3818   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3819          << Arg->getSourceRange();
3820 }
3821 
3822 enum { TileRegLow = 0, TileRegHigh = 7 };
3823 
3824 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3825                                              ArrayRef<int> ArgNums) {
3826   for (int ArgNum : ArgNums) {
3827     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3828       return true;
3829   }
3830   return false;
3831 }
3832 
3833 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3834                                         ArrayRef<int> ArgNums) {
3835   // Because the max number of tile register is TileRegHigh + 1, so here we use
3836   // each bit to represent the usage of them in bitset.
3837   std::bitset<TileRegHigh + 1> ArgValues;
3838   for (int ArgNum : ArgNums) {
3839     Expr *Arg = TheCall->getArg(ArgNum);
3840     if (Arg->isTypeDependent() || Arg->isValueDependent())
3841       continue;
3842 
3843     llvm::APSInt Result;
3844     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3845       return true;
3846     int ArgExtValue = Result.getExtValue();
3847     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3848            "Incorrect tile register num.");
3849     if (ArgValues.test(ArgExtValue))
3850       return Diag(TheCall->getBeginLoc(),
3851                   diag::err_x86_builtin_tile_arg_duplicate)
3852              << TheCall->getArg(ArgNum)->getSourceRange();
3853     ArgValues.set(ArgExtValue);
3854   }
3855   return false;
3856 }
3857 
3858 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3859                                                 ArrayRef<int> ArgNums) {
3860   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3861          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3862 }
3863 
3864 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3865   switch (BuiltinID) {
3866   default:
3867     return false;
3868   case X86::BI__builtin_ia32_tileloadd64:
3869   case X86::BI__builtin_ia32_tileloaddt164:
3870   case X86::BI__builtin_ia32_tilestored64:
3871   case X86::BI__builtin_ia32_tilezero:
3872     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3873   case X86::BI__builtin_ia32_tdpbssd:
3874   case X86::BI__builtin_ia32_tdpbsud:
3875   case X86::BI__builtin_ia32_tdpbusd:
3876   case X86::BI__builtin_ia32_tdpbuud:
3877   case X86::BI__builtin_ia32_tdpbf16ps:
3878     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3879   }
3880 }
3881 static bool isX86_32Builtin(unsigned BuiltinID) {
3882   // These builtins only work on x86-32 targets.
3883   switch (BuiltinID) {
3884   case X86::BI__builtin_ia32_readeflags_u32:
3885   case X86::BI__builtin_ia32_writeeflags_u32:
3886     return true;
3887   }
3888 
3889   return false;
3890 }
3891 
3892 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3893                                        CallExpr *TheCall) {
3894   if (BuiltinID == X86::BI__builtin_cpu_supports)
3895     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3896 
3897   if (BuiltinID == X86::BI__builtin_cpu_is)
3898     return SemaBuiltinCpuIs(*this, TI, TheCall);
3899 
3900   // Check for 32-bit only builtins on a 64-bit target.
3901   const llvm::Triple &TT = TI.getTriple();
3902   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3903     return Diag(TheCall->getCallee()->getBeginLoc(),
3904                 diag::err_32_bit_builtin_64_bit_tgt);
3905 
3906   // If the intrinsic has rounding or SAE make sure its valid.
3907   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3908     return true;
3909 
3910   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3911   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3912     return true;
3913 
3914   // If the intrinsic has a tile arguments, make sure they are valid.
3915   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3916     return true;
3917 
3918   // For intrinsics which take an immediate value as part of the instruction,
3919   // range check them here.
3920   int i = 0, l = 0, u = 0;
3921   switch (BuiltinID) {
3922   default:
3923     return false;
3924   case X86::BI__builtin_ia32_vec_ext_v2si:
3925   case X86::BI__builtin_ia32_vec_ext_v2di:
3926   case X86::BI__builtin_ia32_vextractf128_pd256:
3927   case X86::BI__builtin_ia32_vextractf128_ps256:
3928   case X86::BI__builtin_ia32_vextractf128_si256:
3929   case X86::BI__builtin_ia32_extract128i256:
3930   case X86::BI__builtin_ia32_extractf64x4_mask:
3931   case X86::BI__builtin_ia32_extracti64x4_mask:
3932   case X86::BI__builtin_ia32_extractf32x8_mask:
3933   case X86::BI__builtin_ia32_extracti32x8_mask:
3934   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3935   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3936   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3937   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3938     i = 1; l = 0; u = 1;
3939     break;
3940   case X86::BI__builtin_ia32_vec_set_v2di:
3941   case X86::BI__builtin_ia32_vinsertf128_pd256:
3942   case X86::BI__builtin_ia32_vinsertf128_ps256:
3943   case X86::BI__builtin_ia32_vinsertf128_si256:
3944   case X86::BI__builtin_ia32_insert128i256:
3945   case X86::BI__builtin_ia32_insertf32x8:
3946   case X86::BI__builtin_ia32_inserti32x8:
3947   case X86::BI__builtin_ia32_insertf64x4:
3948   case X86::BI__builtin_ia32_inserti64x4:
3949   case X86::BI__builtin_ia32_insertf64x2_256:
3950   case X86::BI__builtin_ia32_inserti64x2_256:
3951   case X86::BI__builtin_ia32_insertf32x4_256:
3952   case X86::BI__builtin_ia32_inserti32x4_256:
3953     i = 2; l = 0; u = 1;
3954     break;
3955   case X86::BI__builtin_ia32_vpermilpd:
3956   case X86::BI__builtin_ia32_vec_ext_v4hi:
3957   case X86::BI__builtin_ia32_vec_ext_v4si:
3958   case X86::BI__builtin_ia32_vec_ext_v4sf:
3959   case X86::BI__builtin_ia32_vec_ext_v4di:
3960   case X86::BI__builtin_ia32_extractf32x4_mask:
3961   case X86::BI__builtin_ia32_extracti32x4_mask:
3962   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3963   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3964     i = 1; l = 0; u = 3;
3965     break;
3966   case X86::BI_mm_prefetch:
3967   case X86::BI__builtin_ia32_vec_ext_v8hi:
3968   case X86::BI__builtin_ia32_vec_ext_v8si:
3969     i = 1; l = 0; u = 7;
3970     break;
3971   case X86::BI__builtin_ia32_sha1rnds4:
3972   case X86::BI__builtin_ia32_blendpd:
3973   case X86::BI__builtin_ia32_shufpd:
3974   case X86::BI__builtin_ia32_vec_set_v4hi:
3975   case X86::BI__builtin_ia32_vec_set_v4si:
3976   case X86::BI__builtin_ia32_vec_set_v4di:
3977   case X86::BI__builtin_ia32_shuf_f32x4_256:
3978   case X86::BI__builtin_ia32_shuf_f64x2_256:
3979   case X86::BI__builtin_ia32_shuf_i32x4_256:
3980   case X86::BI__builtin_ia32_shuf_i64x2_256:
3981   case X86::BI__builtin_ia32_insertf64x2_512:
3982   case X86::BI__builtin_ia32_inserti64x2_512:
3983   case X86::BI__builtin_ia32_insertf32x4:
3984   case X86::BI__builtin_ia32_inserti32x4:
3985     i = 2; l = 0; u = 3;
3986     break;
3987   case X86::BI__builtin_ia32_vpermil2pd:
3988   case X86::BI__builtin_ia32_vpermil2pd256:
3989   case X86::BI__builtin_ia32_vpermil2ps:
3990   case X86::BI__builtin_ia32_vpermil2ps256:
3991     i = 3; l = 0; u = 3;
3992     break;
3993   case X86::BI__builtin_ia32_cmpb128_mask:
3994   case X86::BI__builtin_ia32_cmpw128_mask:
3995   case X86::BI__builtin_ia32_cmpd128_mask:
3996   case X86::BI__builtin_ia32_cmpq128_mask:
3997   case X86::BI__builtin_ia32_cmpb256_mask:
3998   case X86::BI__builtin_ia32_cmpw256_mask:
3999   case X86::BI__builtin_ia32_cmpd256_mask:
4000   case X86::BI__builtin_ia32_cmpq256_mask:
4001   case X86::BI__builtin_ia32_cmpb512_mask:
4002   case X86::BI__builtin_ia32_cmpw512_mask:
4003   case X86::BI__builtin_ia32_cmpd512_mask:
4004   case X86::BI__builtin_ia32_cmpq512_mask:
4005   case X86::BI__builtin_ia32_ucmpb128_mask:
4006   case X86::BI__builtin_ia32_ucmpw128_mask:
4007   case X86::BI__builtin_ia32_ucmpd128_mask:
4008   case X86::BI__builtin_ia32_ucmpq128_mask:
4009   case X86::BI__builtin_ia32_ucmpb256_mask:
4010   case X86::BI__builtin_ia32_ucmpw256_mask:
4011   case X86::BI__builtin_ia32_ucmpd256_mask:
4012   case X86::BI__builtin_ia32_ucmpq256_mask:
4013   case X86::BI__builtin_ia32_ucmpb512_mask:
4014   case X86::BI__builtin_ia32_ucmpw512_mask:
4015   case X86::BI__builtin_ia32_ucmpd512_mask:
4016   case X86::BI__builtin_ia32_ucmpq512_mask:
4017   case X86::BI__builtin_ia32_vpcomub:
4018   case X86::BI__builtin_ia32_vpcomuw:
4019   case X86::BI__builtin_ia32_vpcomud:
4020   case X86::BI__builtin_ia32_vpcomuq:
4021   case X86::BI__builtin_ia32_vpcomb:
4022   case X86::BI__builtin_ia32_vpcomw:
4023   case X86::BI__builtin_ia32_vpcomd:
4024   case X86::BI__builtin_ia32_vpcomq:
4025   case X86::BI__builtin_ia32_vec_set_v8hi:
4026   case X86::BI__builtin_ia32_vec_set_v8si:
4027     i = 2; l = 0; u = 7;
4028     break;
4029   case X86::BI__builtin_ia32_vpermilpd256:
4030   case X86::BI__builtin_ia32_roundps:
4031   case X86::BI__builtin_ia32_roundpd:
4032   case X86::BI__builtin_ia32_roundps256:
4033   case X86::BI__builtin_ia32_roundpd256:
4034   case X86::BI__builtin_ia32_getmantpd128_mask:
4035   case X86::BI__builtin_ia32_getmantpd256_mask:
4036   case X86::BI__builtin_ia32_getmantps128_mask:
4037   case X86::BI__builtin_ia32_getmantps256_mask:
4038   case X86::BI__builtin_ia32_getmantpd512_mask:
4039   case X86::BI__builtin_ia32_getmantps512_mask:
4040   case X86::BI__builtin_ia32_vec_ext_v16qi:
4041   case X86::BI__builtin_ia32_vec_ext_v16hi:
4042     i = 1; l = 0; u = 15;
4043     break;
4044   case X86::BI__builtin_ia32_pblendd128:
4045   case X86::BI__builtin_ia32_blendps:
4046   case X86::BI__builtin_ia32_blendpd256:
4047   case X86::BI__builtin_ia32_shufpd256:
4048   case X86::BI__builtin_ia32_roundss:
4049   case X86::BI__builtin_ia32_roundsd:
4050   case X86::BI__builtin_ia32_rangepd128_mask:
4051   case X86::BI__builtin_ia32_rangepd256_mask:
4052   case X86::BI__builtin_ia32_rangepd512_mask:
4053   case X86::BI__builtin_ia32_rangeps128_mask:
4054   case X86::BI__builtin_ia32_rangeps256_mask:
4055   case X86::BI__builtin_ia32_rangeps512_mask:
4056   case X86::BI__builtin_ia32_getmantsd_round_mask:
4057   case X86::BI__builtin_ia32_getmantss_round_mask:
4058   case X86::BI__builtin_ia32_vec_set_v16qi:
4059   case X86::BI__builtin_ia32_vec_set_v16hi:
4060     i = 2; l = 0; u = 15;
4061     break;
4062   case X86::BI__builtin_ia32_vec_ext_v32qi:
4063     i = 1; l = 0; u = 31;
4064     break;
4065   case X86::BI__builtin_ia32_cmpps:
4066   case X86::BI__builtin_ia32_cmpss:
4067   case X86::BI__builtin_ia32_cmppd:
4068   case X86::BI__builtin_ia32_cmpsd:
4069   case X86::BI__builtin_ia32_cmpps256:
4070   case X86::BI__builtin_ia32_cmppd256:
4071   case X86::BI__builtin_ia32_cmpps128_mask:
4072   case X86::BI__builtin_ia32_cmppd128_mask:
4073   case X86::BI__builtin_ia32_cmpps256_mask:
4074   case X86::BI__builtin_ia32_cmppd256_mask:
4075   case X86::BI__builtin_ia32_cmpps512_mask:
4076   case X86::BI__builtin_ia32_cmppd512_mask:
4077   case X86::BI__builtin_ia32_cmpsd_mask:
4078   case X86::BI__builtin_ia32_cmpss_mask:
4079   case X86::BI__builtin_ia32_vec_set_v32qi:
4080     i = 2; l = 0; u = 31;
4081     break;
4082   case X86::BI__builtin_ia32_permdf256:
4083   case X86::BI__builtin_ia32_permdi256:
4084   case X86::BI__builtin_ia32_permdf512:
4085   case X86::BI__builtin_ia32_permdi512:
4086   case X86::BI__builtin_ia32_vpermilps:
4087   case X86::BI__builtin_ia32_vpermilps256:
4088   case X86::BI__builtin_ia32_vpermilpd512:
4089   case X86::BI__builtin_ia32_vpermilps512:
4090   case X86::BI__builtin_ia32_pshufd:
4091   case X86::BI__builtin_ia32_pshufd256:
4092   case X86::BI__builtin_ia32_pshufd512:
4093   case X86::BI__builtin_ia32_pshufhw:
4094   case X86::BI__builtin_ia32_pshufhw256:
4095   case X86::BI__builtin_ia32_pshufhw512:
4096   case X86::BI__builtin_ia32_pshuflw:
4097   case X86::BI__builtin_ia32_pshuflw256:
4098   case X86::BI__builtin_ia32_pshuflw512:
4099   case X86::BI__builtin_ia32_vcvtps2ph:
4100   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4101   case X86::BI__builtin_ia32_vcvtps2ph256:
4102   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4103   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4104   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4105   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4106   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4107   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4108   case X86::BI__builtin_ia32_rndscaleps_mask:
4109   case X86::BI__builtin_ia32_rndscalepd_mask:
4110   case X86::BI__builtin_ia32_reducepd128_mask:
4111   case X86::BI__builtin_ia32_reducepd256_mask:
4112   case X86::BI__builtin_ia32_reducepd512_mask:
4113   case X86::BI__builtin_ia32_reduceps128_mask:
4114   case X86::BI__builtin_ia32_reduceps256_mask:
4115   case X86::BI__builtin_ia32_reduceps512_mask:
4116   case X86::BI__builtin_ia32_prold512:
4117   case X86::BI__builtin_ia32_prolq512:
4118   case X86::BI__builtin_ia32_prold128:
4119   case X86::BI__builtin_ia32_prold256:
4120   case X86::BI__builtin_ia32_prolq128:
4121   case X86::BI__builtin_ia32_prolq256:
4122   case X86::BI__builtin_ia32_prord512:
4123   case X86::BI__builtin_ia32_prorq512:
4124   case X86::BI__builtin_ia32_prord128:
4125   case X86::BI__builtin_ia32_prord256:
4126   case X86::BI__builtin_ia32_prorq128:
4127   case X86::BI__builtin_ia32_prorq256:
4128   case X86::BI__builtin_ia32_fpclasspd128_mask:
4129   case X86::BI__builtin_ia32_fpclasspd256_mask:
4130   case X86::BI__builtin_ia32_fpclassps128_mask:
4131   case X86::BI__builtin_ia32_fpclassps256_mask:
4132   case X86::BI__builtin_ia32_fpclassps512_mask:
4133   case X86::BI__builtin_ia32_fpclasspd512_mask:
4134   case X86::BI__builtin_ia32_fpclasssd_mask:
4135   case X86::BI__builtin_ia32_fpclassss_mask:
4136   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4137   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4138   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4139   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4140   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4141   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4142   case X86::BI__builtin_ia32_kshiftliqi:
4143   case X86::BI__builtin_ia32_kshiftlihi:
4144   case X86::BI__builtin_ia32_kshiftlisi:
4145   case X86::BI__builtin_ia32_kshiftlidi:
4146   case X86::BI__builtin_ia32_kshiftriqi:
4147   case X86::BI__builtin_ia32_kshiftrihi:
4148   case X86::BI__builtin_ia32_kshiftrisi:
4149   case X86::BI__builtin_ia32_kshiftridi:
4150     i = 1; l = 0; u = 255;
4151     break;
4152   case X86::BI__builtin_ia32_vperm2f128_pd256:
4153   case X86::BI__builtin_ia32_vperm2f128_ps256:
4154   case X86::BI__builtin_ia32_vperm2f128_si256:
4155   case X86::BI__builtin_ia32_permti256:
4156   case X86::BI__builtin_ia32_pblendw128:
4157   case X86::BI__builtin_ia32_pblendw256:
4158   case X86::BI__builtin_ia32_blendps256:
4159   case X86::BI__builtin_ia32_pblendd256:
4160   case X86::BI__builtin_ia32_palignr128:
4161   case X86::BI__builtin_ia32_palignr256:
4162   case X86::BI__builtin_ia32_palignr512:
4163   case X86::BI__builtin_ia32_alignq512:
4164   case X86::BI__builtin_ia32_alignd512:
4165   case X86::BI__builtin_ia32_alignd128:
4166   case X86::BI__builtin_ia32_alignd256:
4167   case X86::BI__builtin_ia32_alignq128:
4168   case X86::BI__builtin_ia32_alignq256:
4169   case X86::BI__builtin_ia32_vcomisd:
4170   case X86::BI__builtin_ia32_vcomiss:
4171   case X86::BI__builtin_ia32_shuf_f32x4:
4172   case X86::BI__builtin_ia32_shuf_f64x2:
4173   case X86::BI__builtin_ia32_shuf_i32x4:
4174   case X86::BI__builtin_ia32_shuf_i64x2:
4175   case X86::BI__builtin_ia32_shufpd512:
4176   case X86::BI__builtin_ia32_shufps:
4177   case X86::BI__builtin_ia32_shufps256:
4178   case X86::BI__builtin_ia32_shufps512:
4179   case X86::BI__builtin_ia32_dbpsadbw128:
4180   case X86::BI__builtin_ia32_dbpsadbw256:
4181   case X86::BI__builtin_ia32_dbpsadbw512:
4182   case X86::BI__builtin_ia32_vpshldd128:
4183   case X86::BI__builtin_ia32_vpshldd256:
4184   case X86::BI__builtin_ia32_vpshldd512:
4185   case X86::BI__builtin_ia32_vpshldq128:
4186   case X86::BI__builtin_ia32_vpshldq256:
4187   case X86::BI__builtin_ia32_vpshldq512:
4188   case X86::BI__builtin_ia32_vpshldw128:
4189   case X86::BI__builtin_ia32_vpshldw256:
4190   case X86::BI__builtin_ia32_vpshldw512:
4191   case X86::BI__builtin_ia32_vpshrdd128:
4192   case X86::BI__builtin_ia32_vpshrdd256:
4193   case X86::BI__builtin_ia32_vpshrdd512:
4194   case X86::BI__builtin_ia32_vpshrdq128:
4195   case X86::BI__builtin_ia32_vpshrdq256:
4196   case X86::BI__builtin_ia32_vpshrdq512:
4197   case X86::BI__builtin_ia32_vpshrdw128:
4198   case X86::BI__builtin_ia32_vpshrdw256:
4199   case X86::BI__builtin_ia32_vpshrdw512:
4200     i = 2; l = 0; u = 255;
4201     break;
4202   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4203   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4204   case X86::BI__builtin_ia32_fixupimmps512_mask:
4205   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4206   case X86::BI__builtin_ia32_fixupimmsd_mask:
4207   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4208   case X86::BI__builtin_ia32_fixupimmss_mask:
4209   case X86::BI__builtin_ia32_fixupimmss_maskz:
4210   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4211   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4212   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4213   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4214   case X86::BI__builtin_ia32_fixupimmps128_mask:
4215   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4216   case X86::BI__builtin_ia32_fixupimmps256_mask:
4217   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4218   case X86::BI__builtin_ia32_pternlogd512_mask:
4219   case X86::BI__builtin_ia32_pternlogd512_maskz:
4220   case X86::BI__builtin_ia32_pternlogq512_mask:
4221   case X86::BI__builtin_ia32_pternlogq512_maskz:
4222   case X86::BI__builtin_ia32_pternlogd128_mask:
4223   case X86::BI__builtin_ia32_pternlogd128_maskz:
4224   case X86::BI__builtin_ia32_pternlogd256_mask:
4225   case X86::BI__builtin_ia32_pternlogd256_maskz:
4226   case X86::BI__builtin_ia32_pternlogq128_mask:
4227   case X86::BI__builtin_ia32_pternlogq128_maskz:
4228   case X86::BI__builtin_ia32_pternlogq256_mask:
4229   case X86::BI__builtin_ia32_pternlogq256_maskz:
4230     i = 3; l = 0; u = 255;
4231     break;
4232   case X86::BI__builtin_ia32_gatherpfdpd:
4233   case X86::BI__builtin_ia32_gatherpfdps:
4234   case X86::BI__builtin_ia32_gatherpfqpd:
4235   case X86::BI__builtin_ia32_gatherpfqps:
4236   case X86::BI__builtin_ia32_scatterpfdpd:
4237   case X86::BI__builtin_ia32_scatterpfdps:
4238   case X86::BI__builtin_ia32_scatterpfqpd:
4239   case X86::BI__builtin_ia32_scatterpfqps:
4240     i = 4; l = 2; u = 3;
4241     break;
4242   case X86::BI__builtin_ia32_reducesd_mask:
4243   case X86::BI__builtin_ia32_reducess_mask:
4244   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4245   case X86::BI__builtin_ia32_rndscaless_round_mask:
4246     i = 4; l = 0; u = 255;
4247     break;
4248   }
4249 
4250   // Note that we don't force a hard error on the range check here, allowing
4251   // template-generated or macro-generated dead code to potentially have out-of-
4252   // range values. These need to code generate, but don't need to necessarily
4253   // make any sense. We use a warning that defaults to an error.
4254   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4255 }
4256 
4257 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4258 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4259 /// Returns true when the format fits the function and the FormatStringInfo has
4260 /// been populated.
4261 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4262                                FormatStringInfo *FSI) {
4263   FSI->HasVAListArg = Format->getFirstArg() == 0;
4264   FSI->FormatIdx = Format->getFormatIdx() - 1;
4265   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4266 
4267   // The way the format attribute works in GCC, the implicit this argument
4268   // of member functions is counted. However, it doesn't appear in our own
4269   // lists, so decrement format_idx in that case.
4270   if (IsCXXMember) {
4271     if(FSI->FormatIdx == 0)
4272       return false;
4273     --FSI->FormatIdx;
4274     if (FSI->FirstDataArg != 0)
4275       --FSI->FirstDataArg;
4276   }
4277   return true;
4278 }
4279 
4280 /// Checks if a the given expression evaluates to null.
4281 ///
4282 /// Returns true if the value evaluates to null.
4283 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4284   // If the expression has non-null type, it doesn't evaluate to null.
4285   if (auto nullability
4286         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4287     if (*nullability == NullabilityKind::NonNull)
4288       return false;
4289   }
4290 
4291   // As a special case, transparent unions initialized with zero are
4292   // considered null for the purposes of the nonnull attribute.
4293   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4294     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4295       if (const CompoundLiteralExpr *CLE =
4296           dyn_cast<CompoundLiteralExpr>(Expr))
4297         if (const InitListExpr *ILE =
4298             dyn_cast<InitListExpr>(CLE->getInitializer()))
4299           Expr = ILE->getInit(0);
4300   }
4301 
4302   bool Result;
4303   return (!Expr->isValueDependent() &&
4304           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4305           !Result);
4306 }
4307 
4308 static void CheckNonNullArgument(Sema &S,
4309                                  const Expr *ArgExpr,
4310                                  SourceLocation CallSiteLoc) {
4311   if (CheckNonNullExpr(S, ArgExpr))
4312     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4313                           S.PDiag(diag::warn_null_arg)
4314                               << ArgExpr->getSourceRange());
4315 }
4316 
4317 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4318   FormatStringInfo FSI;
4319   if ((GetFormatStringType(Format) == FST_NSString) &&
4320       getFormatStringInfo(Format, false, &FSI)) {
4321     Idx = FSI.FormatIdx;
4322     return true;
4323   }
4324   return false;
4325 }
4326 
4327 /// Diagnose use of %s directive in an NSString which is being passed
4328 /// as formatting string to formatting method.
4329 static void
4330 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4331                                         const NamedDecl *FDecl,
4332                                         Expr **Args,
4333                                         unsigned NumArgs) {
4334   unsigned Idx = 0;
4335   bool Format = false;
4336   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4337   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4338     Idx = 2;
4339     Format = true;
4340   }
4341   else
4342     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4343       if (S.GetFormatNSStringIdx(I, Idx)) {
4344         Format = true;
4345         break;
4346       }
4347     }
4348   if (!Format || NumArgs <= Idx)
4349     return;
4350   const Expr *FormatExpr = Args[Idx];
4351   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4352     FormatExpr = CSCE->getSubExpr();
4353   const StringLiteral *FormatString;
4354   if (const ObjCStringLiteral *OSL =
4355       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4356     FormatString = OSL->getString();
4357   else
4358     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4359   if (!FormatString)
4360     return;
4361   if (S.FormatStringHasSArg(FormatString)) {
4362     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4363       << "%s" << 1 << 1;
4364     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4365       << FDecl->getDeclName();
4366   }
4367 }
4368 
4369 /// Determine whether the given type has a non-null nullability annotation.
4370 static bool isNonNullType(ASTContext &ctx, QualType type) {
4371   if (auto nullability = type->getNullability(ctx))
4372     return *nullability == NullabilityKind::NonNull;
4373 
4374   return false;
4375 }
4376 
4377 static void CheckNonNullArguments(Sema &S,
4378                                   const NamedDecl *FDecl,
4379                                   const FunctionProtoType *Proto,
4380                                   ArrayRef<const Expr *> Args,
4381                                   SourceLocation CallSiteLoc) {
4382   assert((FDecl || Proto) && "Need a function declaration or prototype");
4383 
4384   // Already checked by by constant evaluator.
4385   if (S.isConstantEvaluated())
4386     return;
4387   // Check the attributes attached to the method/function itself.
4388   llvm::SmallBitVector NonNullArgs;
4389   if (FDecl) {
4390     // Handle the nonnull attribute on the function/method declaration itself.
4391     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4392       if (!NonNull->args_size()) {
4393         // Easy case: all pointer arguments are nonnull.
4394         for (const auto *Arg : Args)
4395           if (S.isValidPointerAttrType(Arg->getType()))
4396             CheckNonNullArgument(S, Arg, CallSiteLoc);
4397         return;
4398       }
4399 
4400       for (const ParamIdx &Idx : NonNull->args()) {
4401         unsigned IdxAST = Idx.getASTIndex();
4402         if (IdxAST >= Args.size())
4403           continue;
4404         if (NonNullArgs.empty())
4405           NonNullArgs.resize(Args.size());
4406         NonNullArgs.set(IdxAST);
4407       }
4408     }
4409   }
4410 
4411   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4412     // Handle the nonnull attribute on the parameters of the
4413     // function/method.
4414     ArrayRef<ParmVarDecl*> parms;
4415     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4416       parms = FD->parameters();
4417     else
4418       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4419 
4420     unsigned ParamIndex = 0;
4421     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4422          I != E; ++I, ++ParamIndex) {
4423       const ParmVarDecl *PVD = *I;
4424       if (PVD->hasAttr<NonNullAttr>() ||
4425           isNonNullType(S.Context, PVD->getType())) {
4426         if (NonNullArgs.empty())
4427           NonNullArgs.resize(Args.size());
4428 
4429         NonNullArgs.set(ParamIndex);
4430       }
4431     }
4432   } else {
4433     // If we have a non-function, non-method declaration but no
4434     // function prototype, try to dig out the function prototype.
4435     if (!Proto) {
4436       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4437         QualType type = VD->getType().getNonReferenceType();
4438         if (auto pointerType = type->getAs<PointerType>())
4439           type = pointerType->getPointeeType();
4440         else if (auto blockType = type->getAs<BlockPointerType>())
4441           type = blockType->getPointeeType();
4442         // FIXME: data member pointers?
4443 
4444         // Dig out the function prototype, if there is one.
4445         Proto = type->getAs<FunctionProtoType>();
4446       }
4447     }
4448 
4449     // Fill in non-null argument information from the nullability
4450     // information on the parameter types (if we have them).
4451     if (Proto) {
4452       unsigned Index = 0;
4453       for (auto paramType : Proto->getParamTypes()) {
4454         if (isNonNullType(S.Context, paramType)) {
4455           if (NonNullArgs.empty())
4456             NonNullArgs.resize(Args.size());
4457 
4458           NonNullArgs.set(Index);
4459         }
4460 
4461         ++Index;
4462       }
4463     }
4464   }
4465 
4466   // Check for non-null arguments.
4467   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4468        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4469     if (NonNullArgs[ArgIndex])
4470       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4471   }
4472 }
4473 
4474 /// Handles the checks for format strings, non-POD arguments to vararg
4475 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4476 /// attributes.
4477 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4478                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4479                      bool IsMemberFunction, SourceLocation Loc,
4480                      SourceRange Range, VariadicCallType CallType) {
4481   // FIXME: We should check as much as we can in the template definition.
4482   if (CurContext->isDependentContext())
4483     return;
4484 
4485   // Printf and scanf checking.
4486   llvm::SmallBitVector CheckedVarArgs;
4487   if (FDecl) {
4488     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4489       // Only create vector if there are format attributes.
4490       CheckedVarArgs.resize(Args.size());
4491 
4492       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4493                            CheckedVarArgs);
4494     }
4495   }
4496 
4497   // Refuse POD arguments that weren't caught by the format string
4498   // checks above.
4499   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4500   if (CallType != VariadicDoesNotApply &&
4501       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4502     unsigned NumParams = Proto ? Proto->getNumParams()
4503                        : FDecl && isa<FunctionDecl>(FDecl)
4504                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4505                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4506                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4507                        : 0;
4508 
4509     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4510       // Args[ArgIdx] can be null in malformed code.
4511       if (const Expr *Arg = Args[ArgIdx]) {
4512         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4513           checkVariadicArgument(Arg, CallType);
4514       }
4515     }
4516   }
4517 
4518   if (FDecl || Proto) {
4519     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4520 
4521     // Type safety checking.
4522     if (FDecl) {
4523       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4524         CheckArgumentWithTypeTag(I, Args, Loc);
4525     }
4526   }
4527 
4528   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4529     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4530     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4531     if (!Arg->isValueDependent()) {
4532       Expr::EvalResult Align;
4533       if (Arg->EvaluateAsInt(Align, Context)) {
4534         const llvm::APSInt &I = Align.Val.getInt();
4535         if (!I.isPowerOf2())
4536           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4537               << Arg->getSourceRange();
4538 
4539         if (I > Sema::MaximumAlignment)
4540           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4541               << Arg->getSourceRange() << Sema::MaximumAlignment;
4542       }
4543     }
4544   }
4545 
4546   if (FD)
4547     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4548 }
4549 
4550 /// CheckConstructorCall - Check a constructor call for correctness and safety
4551 /// properties not enforced by the C type system.
4552 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4553                                 ArrayRef<const Expr *> Args,
4554                                 const FunctionProtoType *Proto,
4555                                 SourceLocation Loc) {
4556   VariadicCallType CallType =
4557     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4558   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4559             Loc, SourceRange(), CallType);
4560 }
4561 
4562 /// CheckFunctionCall - Check a direct function call for various correctness
4563 /// and safety properties not strictly enforced by the C type system.
4564 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4565                              const FunctionProtoType *Proto) {
4566   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4567                               isa<CXXMethodDecl>(FDecl);
4568   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4569                           IsMemberOperatorCall;
4570   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4571                                                   TheCall->getCallee());
4572   Expr** Args = TheCall->getArgs();
4573   unsigned NumArgs = TheCall->getNumArgs();
4574 
4575   Expr *ImplicitThis = nullptr;
4576   if (IsMemberOperatorCall) {
4577     // If this is a call to a member operator, hide the first argument
4578     // from checkCall.
4579     // FIXME: Our choice of AST representation here is less than ideal.
4580     ImplicitThis = Args[0];
4581     ++Args;
4582     --NumArgs;
4583   } else if (IsMemberFunction)
4584     ImplicitThis =
4585         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4586 
4587   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4588             IsMemberFunction, TheCall->getRParenLoc(),
4589             TheCall->getCallee()->getSourceRange(), CallType);
4590 
4591   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4592   // None of the checks below are needed for functions that don't have
4593   // simple names (e.g., C++ conversion functions).
4594   if (!FnInfo)
4595     return false;
4596 
4597   CheckTCBEnforcement(TheCall, FDecl);
4598 
4599   CheckAbsoluteValueFunction(TheCall, FDecl);
4600   CheckMaxUnsignedZero(TheCall, FDecl);
4601 
4602   if (getLangOpts().ObjC)
4603     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4604 
4605   unsigned CMId = FDecl->getMemoryFunctionKind();
4606 
4607   // Handle memory setting and copying functions.
4608   switch (CMId) {
4609   case 0:
4610     return false;
4611   case Builtin::BIstrlcpy: // fallthrough
4612   case Builtin::BIstrlcat:
4613     CheckStrlcpycatArguments(TheCall, FnInfo);
4614     break;
4615   case Builtin::BIstrncat:
4616     CheckStrncatArguments(TheCall, FnInfo);
4617     break;
4618   case Builtin::BIfree:
4619     CheckFreeArguments(TheCall);
4620     break;
4621   default:
4622     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4623   }
4624 
4625   return false;
4626 }
4627 
4628 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4629                                ArrayRef<const Expr *> Args) {
4630   VariadicCallType CallType =
4631       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4632 
4633   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4634             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4635             CallType);
4636 
4637   return false;
4638 }
4639 
4640 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4641                             const FunctionProtoType *Proto) {
4642   QualType Ty;
4643   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4644     Ty = V->getType().getNonReferenceType();
4645   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4646     Ty = F->getType().getNonReferenceType();
4647   else
4648     return false;
4649 
4650   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4651       !Ty->isFunctionProtoType())
4652     return false;
4653 
4654   VariadicCallType CallType;
4655   if (!Proto || !Proto->isVariadic()) {
4656     CallType = VariadicDoesNotApply;
4657   } else if (Ty->isBlockPointerType()) {
4658     CallType = VariadicBlock;
4659   } else { // Ty->isFunctionPointerType()
4660     CallType = VariadicFunction;
4661   }
4662 
4663   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4664             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4665             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4666             TheCall->getCallee()->getSourceRange(), CallType);
4667 
4668   return false;
4669 }
4670 
4671 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4672 /// such as function pointers returned from functions.
4673 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4674   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4675                                                   TheCall->getCallee());
4676   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4677             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4678             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4679             TheCall->getCallee()->getSourceRange(), CallType);
4680 
4681   return false;
4682 }
4683 
4684 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4685   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4686     return false;
4687 
4688   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4689   switch (Op) {
4690   case AtomicExpr::AO__c11_atomic_init:
4691   case AtomicExpr::AO__opencl_atomic_init:
4692     llvm_unreachable("There is no ordering argument for an init");
4693 
4694   case AtomicExpr::AO__c11_atomic_load:
4695   case AtomicExpr::AO__opencl_atomic_load:
4696   case AtomicExpr::AO__atomic_load_n:
4697   case AtomicExpr::AO__atomic_load:
4698     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4699            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4700 
4701   case AtomicExpr::AO__c11_atomic_store:
4702   case AtomicExpr::AO__opencl_atomic_store:
4703   case AtomicExpr::AO__atomic_store:
4704   case AtomicExpr::AO__atomic_store_n:
4705     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4706            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4707            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4708 
4709   default:
4710     return true;
4711   }
4712 }
4713 
4714 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4715                                          AtomicExpr::AtomicOp Op) {
4716   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4717   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4718   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4719   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4720                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4721                          Op);
4722 }
4723 
4724 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4725                                  SourceLocation RParenLoc, MultiExprArg Args,
4726                                  AtomicExpr::AtomicOp Op,
4727                                  AtomicArgumentOrder ArgOrder) {
4728   // All the non-OpenCL operations take one of the following forms.
4729   // The OpenCL operations take the __c11 forms with one extra argument for
4730   // synchronization scope.
4731   enum {
4732     // C    __c11_atomic_init(A *, C)
4733     Init,
4734 
4735     // C    __c11_atomic_load(A *, int)
4736     Load,
4737 
4738     // void __atomic_load(A *, CP, int)
4739     LoadCopy,
4740 
4741     // void __atomic_store(A *, CP, int)
4742     Copy,
4743 
4744     // C    __c11_atomic_add(A *, M, int)
4745     Arithmetic,
4746 
4747     // C    __atomic_exchange_n(A *, CP, int)
4748     Xchg,
4749 
4750     // void __atomic_exchange(A *, C *, CP, int)
4751     GNUXchg,
4752 
4753     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4754     C11CmpXchg,
4755 
4756     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4757     GNUCmpXchg
4758   } Form = Init;
4759 
4760   const unsigned NumForm = GNUCmpXchg + 1;
4761   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4762   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4763   // where:
4764   //   C is an appropriate type,
4765   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4766   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4767   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4768   //   the int parameters are for orderings.
4769 
4770   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4771       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4772       "need to update code for modified forms");
4773   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4774                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4775                         AtomicExpr::AO__atomic_load,
4776                 "need to update code for modified C11 atomics");
4777   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4778                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4779   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4780                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4781                IsOpenCL;
4782   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4783              Op == AtomicExpr::AO__atomic_store_n ||
4784              Op == AtomicExpr::AO__atomic_exchange_n ||
4785              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4786   bool IsAddSub = false;
4787 
4788   switch (Op) {
4789   case AtomicExpr::AO__c11_atomic_init:
4790   case AtomicExpr::AO__opencl_atomic_init:
4791     Form = Init;
4792     break;
4793 
4794   case AtomicExpr::AO__c11_atomic_load:
4795   case AtomicExpr::AO__opencl_atomic_load:
4796   case AtomicExpr::AO__atomic_load_n:
4797     Form = Load;
4798     break;
4799 
4800   case AtomicExpr::AO__atomic_load:
4801     Form = LoadCopy;
4802     break;
4803 
4804   case AtomicExpr::AO__c11_atomic_store:
4805   case AtomicExpr::AO__opencl_atomic_store:
4806   case AtomicExpr::AO__atomic_store:
4807   case AtomicExpr::AO__atomic_store_n:
4808     Form = Copy;
4809     break;
4810 
4811   case AtomicExpr::AO__c11_atomic_fetch_add:
4812   case AtomicExpr::AO__c11_atomic_fetch_sub:
4813   case AtomicExpr::AO__opencl_atomic_fetch_add:
4814   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4815   case AtomicExpr::AO__atomic_fetch_add:
4816   case AtomicExpr::AO__atomic_fetch_sub:
4817   case AtomicExpr::AO__atomic_add_fetch:
4818   case AtomicExpr::AO__atomic_sub_fetch:
4819     IsAddSub = true;
4820     LLVM_FALLTHROUGH;
4821   case AtomicExpr::AO__c11_atomic_fetch_and:
4822   case AtomicExpr::AO__c11_atomic_fetch_or:
4823   case AtomicExpr::AO__c11_atomic_fetch_xor:
4824   case AtomicExpr::AO__opencl_atomic_fetch_and:
4825   case AtomicExpr::AO__opencl_atomic_fetch_or:
4826   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4827   case AtomicExpr::AO__atomic_fetch_and:
4828   case AtomicExpr::AO__atomic_fetch_or:
4829   case AtomicExpr::AO__atomic_fetch_xor:
4830   case AtomicExpr::AO__atomic_fetch_nand:
4831   case AtomicExpr::AO__atomic_and_fetch:
4832   case AtomicExpr::AO__atomic_or_fetch:
4833   case AtomicExpr::AO__atomic_xor_fetch:
4834   case AtomicExpr::AO__atomic_nand_fetch:
4835   case AtomicExpr::AO__c11_atomic_fetch_min:
4836   case AtomicExpr::AO__c11_atomic_fetch_max:
4837   case AtomicExpr::AO__opencl_atomic_fetch_min:
4838   case AtomicExpr::AO__opencl_atomic_fetch_max:
4839   case AtomicExpr::AO__atomic_min_fetch:
4840   case AtomicExpr::AO__atomic_max_fetch:
4841   case AtomicExpr::AO__atomic_fetch_min:
4842   case AtomicExpr::AO__atomic_fetch_max:
4843     Form = Arithmetic;
4844     break;
4845 
4846   case AtomicExpr::AO__c11_atomic_exchange:
4847   case AtomicExpr::AO__opencl_atomic_exchange:
4848   case AtomicExpr::AO__atomic_exchange_n:
4849     Form = Xchg;
4850     break;
4851 
4852   case AtomicExpr::AO__atomic_exchange:
4853     Form = GNUXchg;
4854     break;
4855 
4856   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4857   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4858   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4859   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4860     Form = C11CmpXchg;
4861     break;
4862 
4863   case AtomicExpr::AO__atomic_compare_exchange:
4864   case AtomicExpr::AO__atomic_compare_exchange_n:
4865     Form = GNUCmpXchg;
4866     break;
4867   }
4868 
4869   unsigned AdjustedNumArgs = NumArgs[Form];
4870   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4871     ++AdjustedNumArgs;
4872   // Check we have the right number of arguments.
4873   if (Args.size() < AdjustedNumArgs) {
4874     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4875         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4876         << ExprRange;
4877     return ExprError();
4878   } else if (Args.size() > AdjustedNumArgs) {
4879     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4880          diag::err_typecheck_call_too_many_args)
4881         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4882         << ExprRange;
4883     return ExprError();
4884   }
4885 
4886   // Inspect the first argument of the atomic operation.
4887   Expr *Ptr = Args[0];
4888   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4889   if (ConvertedPtr.isInvalid())
4890     return ExprError();
4891 
4892   Ptr = ConvertedPtr.get();
4893   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4894   if (!pointerType) {
4895     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4896         << Ptr->getType() << Ptr->getSourceRange();
4897     return ExprError();
4898   }
4899 
4900   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4901   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4902   QualType ValType = AtomTy; // 'C'
4903   if (IsC11) {
4904     if (!AtomTy->isAtomicType()) {
4905       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4906           << Ptr->getType() << Ptr->getSourceRange();
4907       return ExprError();
4908     }
4909     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4910         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4911       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4912           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4913           << Ptr->getSourceRange();
4914       return ExprError();
4915     }
4916     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4917   } else if (Form != Load && Form != LoadCopy) {
4918     if (ValType.isConstQualified()) {
4919       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4920           << Ptr->getType() << Ptr->getSourceRange();
4921       return ExprError();
4922     }
4923   }
4924 
4925   // For an arithmetic operation, the implied arithmetic must be well-formed.
4926   if (Form == Arithmetic) {
4927     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4928     if (IsAddSub && !ValType->isIntegerType()
4929         && !ValType->isPointerType()) {
4930       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4931           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4932       return ExprError();
4933     }
4934     if (!IsAddSub && !ValType->isIntegerType()) {
4935       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4936           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4937       return ExprError();
4938     }
4939     if (IsC11 && ValType->isPointerType() &&
4940         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4941                             diag::err_incomplete_type)) {
4942       return ExprError();
4943     }
4944   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4945     // For __atomic_*_n operations, the value type must be a scalar integral or
4946     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4947     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4948         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4949     return ExprError();
4950   }
4951 
4952   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4953       !AtomTy->isScalarType()) {
4954     // For GNU atomics, require a trivially-copyable type. This is not part of
4955     // the GNU atomics specification, but we enforce it for sanity.
4956     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4957         << Ptr->getType() << Ptr->getSourceRange();
4958     return ExprError();
4959   }
4960 
4961   switch (ValType.getObjCLifetime()) {
4962   case Qualifiers::OCL_None:
4963   case Qualifiers::OCL_ExplicitNone:
4964     // okay
4965     break;
4966 
4967   case Qualifiers::OCL_Weak:
4968   case Qualifiers::OCL_Strong:
4969   case Qualifiers::OCL_Autoreleasing:
4970     // FIXME: Can this happen? By this point, ValType should be known
4971     // to be trivially copyable.
4972     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4973         << ValType << Ptr->getSourceRange();
4974     return ExprError();
4975   }
4976 
4977   // All atomic operations have an overload which takes a pointer to a volatile
4978   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4979   // into the result or the other operands. Similarly atomic_load takes a
4980   // pointer to a const 'A'.
4981   ValType.removeLocalVolatile();
4982   ValType.removeLocalConst();
4983   QualType ResultType = ValType;
4984   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4985       Form == Init)
4986     ResultType = Context.VoidTy;
4987   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4988     ResultType = Context.BoolTy;
4989 
4990   // The type of a parameter passed 'by value'. In the GNU atomics, such
4991   // arguments are actually passed as pointers.
4992   QualType ByValType = ValType; // 'CP'
4993   bool IsPassedByAddress = false;
4994   if (!IsC11 && !IsN) {
4995     ByValType = Ptr->getType();
4996     IsPassedByAddress = true;
4997   }
4998 
4999   SmallVector<Expr *, 5> APIOrderedArgs;
5000   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5001     APIOrderedArgs.push_back(Args[0]);
5002     switch (Form) {
5003     case Init:
5004     case Load:
5005       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5006       break;
5007     case LoadCopy:
5008     case Copy:
5009     case Arithmetic:
5010     case Xchg:
5011       APIOrderedArgs.push_back(Args[2]); // Val1
5012       APIOrderedArgs.push_back(Args[1]); // Order
5013       break;
5014     case GNUXchg:
5015       APIOrderedArgs.push_back(Args[2]); // Val1
5016       APIOrderedArgs.push_back(Args[3]); // Val2
5017       APIOrderedArgs.push_back(Args[1]); // Order
5018       break;
5019     case C11CmpXchg:
5020       APIOrderedArgs.push_back(Args[2]); // Val1
5021       APIOrderedArgs.push_back(Args[4]); // Val2
5022       APIOrderedArgs.push_back(Args[1]); // Order
5023       APIOrderedArgs.push_back(Args[3]); // OrderFail
5024       break;
5025     case GNUCmpXchg:
5026       APIOrderedArgs.push_back(Args[2]); // Val1
5027       APIOrderedArgs.push_back(Args[4]); // Val2
5028       APIOrderedArgs.push_back(Args[5]); // Weak
5029       APIOrderedArgs.push_back(Args[1]); // Order
5030       APIOrderedArgs.push_back(Args[3]); // OrderFail
5031       break;
5032     }
5033   } else
5034     APIOrderedArgs.append(Args.begin(), Args.end());
5035 
5036   // The first argument's non-CV pointer type is used to deduce the type of
5037   // subsequent arguments, except for:
5038   //  - weak flag (always converted to bool)
5039   //  - memory order (always converted to int)
5040   //  - scope  (always converted to int)
5041   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5042     QualType Ty;
5043     if (i < NumVals[Form] + 1) {
5044       switch (i) {
5045       case 0:
5046         // The first argument is always a pointer. It has a fixed type.
5047         // It is always dereferenced, a nullptr is undefined.
5048         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5049         // Nothing else to do: we already know all we want about this pointer.
5050         continue;
5051       case 1:
5052         // The second argument is the non-atomic operand. For arithmetic, this
5053         // is always passed by value, and for a compare_exchange it is always
5054         // passed by address. For the rest, GNU uses by-address and C11 uses
5055         // by-value.
5056         assert(Form != Load);
5057         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
5058           Ty = ValType;
5059         else if (Form == Copy || Form == Xchg) {
5060           if (IsPassedByAddress) {
5061             // The value pointer is always dereferenced, a nullptr is undefined.
5062             CheckNonNullArgument(*this, APIOrderedArgs[i],
5063                                  ExprRange.getBegin());
5064           }
5065           Ty = ByValType;
5066         } else if (Form == Arithmetic)
5067           Ty = Context.getPointerDiffType();
5068         else {
5069           Expr *ValArg = APIOrderedArgs[i];
5070           // The value pointer is always dereferenced, a nullptr is undefined.
5071           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5072           LangAS AS = LangAS::Default;
5073           // Keep address space of non-atomic pointer type.
5074           if (const PointerType *PtrTy =
5075                   ValArg->getType()->getAs<PointerType>()) {
5076             AS = PtrTy->getPointeeType().getAddressSpace();
5077           }
5078           Ty = Context.getPointerType(
5079               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5080         }
5081         break;
5082       case 2:
5083         // The third argument to compare_exchange / GNU exchange is the desired
5084         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5085         if (IsPassedByAddress)
5086           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5087         Ty = ByValType;
5088         break;
5089       case 3:
5090         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5091         Ty = Context.BoolTy;
5092         break;
5093       }
5094     } else {
5095       // The order(s) and scope are always converted to int.
5096       Ty = Context.IntTy;
5097     }
5098 
5099     InitializedEntity Entity =
5100         InitializedEntity::InitializeParameter(Context, Ty, false);
5101     ExprResult Arg = APIOrderedArgs[i];
5102     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5103     if (Arg.isInvalid())
5104       return true;
5105     APIOrderedArgs[i] = Arg.get();
5106   }
5107 
5108   // Permute the arguments into a 'consistent' order.
5109   SmallVector<Expr*, 5> SubExprs;
5110   SubExprs.push_back(Ptr);
5111   switch (Form) {
5112   case Init:
5113     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5114     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5115     break;
5116   case Load:
5117     SubExprs.push_back(APIOrderedArgs[1]); // Order
5118     break;
5119   case LoadCopy:
5120   case Copy:
5121   case Arithmetic:
5122   case Xchg:
5123     SubExprs.push_back(APIOrderedArgs[2]); // Order
5124     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5125     break;
5126   case GNUXchg:
5127     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5128     SubExprs.push_back(APIOrderedArgs[3]); // Order
5129     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5130     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5131     break;
5132   case C11CmpXchg:
5133     SubExprs.push_back(APIOrderedArgs[3]); // Order
5134     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5135     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5136     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5137     break;
5138   case GNUCmpXchg:
5139     SubExprs.push_back(APIOrderedArgs[4]); // Order
5140     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5141     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5142     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5143     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5144     break;
5145   }
5146 
5147   if (SubExprs.size() >= 2 && Form != Init) {
5148     if (Optional<llvm::APSInt> Result =
5149             SubExprs[1]->getIntegerConstantExpr(Context))
5150       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5151         Diag(SubExprs[1]->getBeginLoc(),
5152              diag::warn_atomic_op_has_invalid_memory_order)
5153             << SubExprs[1]->getSourceRange();
5154   }
5155 
5156   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5157     auto *Scope = Args[Args.size() - 1];
5158     if (Optional<llvm::APSInt> Result =
5159             Scope->getIntegerConstantExpr(Context)) {
5160       if (!ScopeModel->isValid(Result->getZExtValue()))
5161         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5162             << Scope->getSourceRange();
5163     }
5164     SubExprs.push_back(Scope);
5165   }
5166 
5167   AtomicExpr *AE = new (Context)
5168       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5169 
5170   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5171        Op == AtomicExpr::AO__c11_atomic_store ||
5172        Op == AtomicExpr::AO__opencl_atomic_load ||
5173        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5174       Context.AtomicUsesUnsupportedLibcall(AE))
5175     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5176         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5177              Op == AtomicExpr::AO__opencl_atomic_load)
5178                 ? 0
5179                 : 1);
5180 
5181   if (ValType->isExtIntType()) {
5182     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5183     return ExprError();
5184   }
5185 
5186   return AE;
5187 }
5188 
5189 /// checkBuiltinArgument - Given a call to a builtin function, perform
5190 /// normal type-checking on the given argument, updating the call in
5191 /// place.  This is useful when a builtin function requires custom
5192 /// type-checking for some of its arguments but not necessarily all of
5193 /// them.
5194 ///
5195 /// Returns true on error.
5196 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5197   FunctionDecl *Fn = E->getDirectCallee();
5198   assert(Fn && "builtin call without direct callee!");
5199 
5200   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5201   InitializedEntity Entity =
5202     InitializedEntity::InitializeParameter(S.Context, Param);
5203 
5204   ExprResult Arg = E->getArg(0);
5205   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5206   if (Arg.isInvalid())
5207     return true;
5208 
5209   E->setArg(ArgIndex, Arg.get());
5210   return false;
5211 }
5212 
5213 /// We have a call to a function like __sync_fetch_and_add, which is an
5214 /// overloaded function based on the pointer type of its first argument.
5215 /// The main BuildCallExpr routines have already promoted the types of
5216 /// arguments because all of these calls are prototyped as void(...).
5217 ///
5218 /// This function goes through and does final semantic checking for these
5219 /// builtins, as well as generating any warnings.
5220 ExprResult
5221 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5222   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5223   Expr *Callee = TheCall->getCallee();
5224   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5225   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5226 
5227   // Ensure that we have at least one argument to do type inference from.
5228   if (TheCall->getNumArgs() < 1) {
5229     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5230         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5231     return ExprError();
5232   }
5233 
5234   // Inspect the first argument of the atomic builtin.  This should always be
5235   // a pointer type, whose element is an integral scalar or pointer type.
5236   // Because it is a pointer type, we don't have to worry about any implicit
5237   // casts here.
5238   // FIXME: We don't allow floating point scalars as input.
5239   Expr *FirstArg = TheCall->getArg(0);
5240   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5241   if (FirstArgResult.isInvalid())
5242     return ExprError();
5243   FirstArg = FirstArgResult.get();
5244   TheCall->setArg(0, FirstArg);
5245 
5246   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5247   if (!pointerType) {
5248     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5249         << FirstArg->getType() << FirstArg->getSourceRange();
5250     return ExprError();
5251   }
5252 
5253   QualType ValType = pointerType->getPointeeType();
5254   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5255       !ValType->isBlockPointerType()) {
5256     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5257         << FirstArg->getType() << FirstArg->getSourceRange();
5258     return ExprError();
5259   }
5260 
5261   if (ValType.isConstQualified()) {
5262     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5263         << FirstArg->getType() << FirstArg->getSourceRange();
5264     return ExprError();
5265   }
5266 
5267   switch (ValType.getObjCLifetime()) {
5268   case Qualifiers::OCL_None:
5269   case Qualifiers::OCL_ExplicitNone:
5270     // okay
5271     break;
5272 
5273   case Qualifiers::OCL_Weak:
5274   case Qualifiers::OCL_Strong:
5275   case Qualifiers::OCL_Autoreleasing:
5276     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5277         << ValType << FirstArg->getSourceRange();
5278     return ExprError();
5279   }
5280 
5281   // Strip any qualifiers off ValType.
5282   ValType = ValType.getUnqualifiedType();
5283 
5284   // The majority of builtins return a value, but a few have special return
5285   // types, so allow them to override appropriately below.
5286   QualType ResultType = ValType;
5287 
5288   // We need to figure out which concrete builtin this maps onto.  For example,
5289   // __sync_fetch_and_add with a 2 byte object turns into
5290   // __sync_fetch_and_add_2.
5291 #define BUILTIN_ROW(x) \
5292   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5293     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5294 
5295   static const unsigned BuiltinIndices[][5] = {
5296     BUILTIN_ROW(__sync_fetch_and_add),
5297     BUILTIN_ROW(__sync_fetch_and_sub),
5298     BUILTIN_ROW(__sync_fetch_and_or),
5299     BUILTIN_ROW(__sync_fetch_and_and),
5300     BUILTIN_ROW(__sync_fetch_and_xor),
5301     BUILTIN_ROW(__sync_fetch_and_nand),
5302 
5303     BUILTIN_ROW(__sync_add_and_fetch),
5304     BUILTIN_ROW(__sync_sub_and_fetch),
5305     BUILTIN_ROW(__sync_and_and_fetch),
5306     BUILTIN_ROW(__sync_or_and_fetch),
5307     BUILTIN_ROW(__sync_xor_and_fetch),
5308     BUILTIN_ROW(__sync_nand_and_fetch),
5309 
5310     BUILTIN_ROW(__sync_val_compare_and_swap),
5311     BUILTIN_ROW(__sync_bool_compare_and_swap),
5312     BUILTIN_ROW(__sync_lock_test_and_set),
5313     BUILTIN_ROW(__sync_lock_release),
5314     BUILTIN_ROW(__sync_swap)
5315   };
5316 #undef BUILTIN_ROW
5317 
5318   // Determine the index of the size.
5319   unsigned SizeIndex;
5320   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5321   case 1: SizeIndex = 0; break;
5322   case 2: SizeIndex = 1; break;
5323   case 4: SizeIndex = 2; break;
5324   case 8: SizeIndex = 3; break;
5325   case 16: SizeIndex = 4; break;
5326   default:
5327     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5328         << FirstArg->getType() << FirstArg->getSourceRange();
5329     return ExprError();
5330   }
5331 
5332   // Each of these builtins has one pointer argument, followed by some number of
5333   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5334   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5335   // as the number of fixed args.
5336   unsigned BuiltinID = FDecl->getBuiltinID();
5337   unsigned BuiltinIndex, NumFixed = 1;
5338   bool WarnAboutSemanticsChange = false;
5339   switch (BuiltinID) {
5340   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5341   case Builtin::BI__sync_fetch_and_add:
5342   case Builtin::BI__sync_fetch_and_add_1:
5343   case Builtin::BI__sync_fetch_and_add_2:
5344   case Builtin::BI__sync_fetch_and_add_4:
5345   case Builtin::BI__sync_fetch_and_add_8:
5346   case Builtin::BI__sync_fetch_and_add_16:
5347     BuiltinIndex = 0;
5348     break;
5349 
5350   case Builtin::BI__sync_fetch_and_sub:
5351   case Builtin::BI__sync_fetch_and_sub_1:
5352   case Builtin::BI__sync_fetch_and_sub_2:
5353   case Builtin::BI__sync_fetch_and_sub_4:
5354   case Builtin::BI__sync_fetch_and_sub_8:
5355   case Builtin::BI__sync_fetch_and_sub_16:
5356     BuiltinIndex = 1;
5357     break;
5358 
5359   case Builtin::BI__sync_fetch_and_or:
5360   case Builtin::BI__sync_fetch_and_or_1:
5361   case Builtin::BI__sync_fetch_and_or_2:
5362   case Builtin::BI__sync_fetch_and_or_4:
5363   case Builtin::BI__sync_fetch_and_or_8:
5364   case Builtin::BI__sync_fetch_and_or_16:
5365     BuiltinIndex = 2;
5366     break;
5367 
5368   case Builtin::BI__sync_fetch_and_and:
5369   case Builtin::BI__sync_fetch_and_and_1:
5370   case Builtin::BI__sync_fetch_and_and_2:
5371   case Builtin::BI__sync_fetch_and_and_4:
5372   case Builtin::BI__sync_fetch_and_and_8:
5373   case Builtin::BI__sync_fetch_and_and_16:
5374     BuiltinIndex = 3;
5375     break;
5376 
5377   case Builtin::BI__sync_fetch_and_xor:
5378   case Builtin::BI__sync_fetch_and_xor_1:
5379   case Builtin::BI__sync_fetch_and_xor_2:
5380   case Builtin::BI__sync_fetch_and_xor_4:
5381   case Builtin::BI__sync_fetch_and_xor_8:
5382   case Builtin::BI__sync_fetch_and_xor_16:
5383     BuiltinIndex = 4;
5384     break;
5385 
5386   case Builtin::BI__sync_fetch_and_nand:
5387   case Builtin::BI__sync_fetch_and_nand_1:
5388   case Builtin::BI__sync_fetch_and_nand_2:
5389   case Builtin::BI__sync_fetch_and_nand_4:
5390   case Builtin::BI__sync_fetch_and_nand_8:
5391   case Builtin::BI__sync_fetch_and_nand_16:
5392     BuiltinIndex = 5;
5393     WarnAboutSemanticsChange = true;
5394     break;
5395 
5396   case Builtin::BI__sync_add_and_fetch:
5397   case Builtin::BI__sync_add_and_fetch_1:
5398   case Builtin::BI__sync_add_and_fetch_2:
5399   case Builtin::BI__sync_add_and_fetch_4:
5400   case Builtin::BI__sync_add_and_fetch_8:
5401   case Builtin::BI__sync_add_and_fetch_16:
5402     BuiltinIndex = 6;
5403     break;
5404 
5405   case Builtin::BI__sync_sub_and_fetch:
5406   case Builtin::BI__sync_sub_and_fetch_1:
5407   case Builtin::BI__sync_sub_and_fetch_2:
5408   case Builtin::BI__sync_sub_and_fetch_4:
5409   case Builtin::BI__sync_sub_and_fetch_8:
5410   case Builtin::BI__sync_sub_and_fetch_16:
5411     BuiltinIndex = 7;
5412     break;
5413 
5414   case Builtin::BI__sync_and_and_fetch:
5415   case Builtin::BI__sync_and_and_fetch_1:
5416   case Builtin::BI__sync_and_and_fetch_2:
5417   case Builtin::BI__sync_and_and_fetch_4:
5418   case Builtin::BI__sync_and_and_fetch_8:
5419   case Builtin::BI__sync_and_and_fetch_16:
5420     BuiltinIndex = 8;
5421     break;
5422 
5423   case Builtin::BI__sync_or_and_fetch:
5424   case Builtin::BI__sync_or_and_fetch_1:
5425   case Builtin::BI__sync_or_and_fetch_2:
5426   case Builtin::BI__sync_or_and_fetch_4:
5427   case Builtin::BI__sync_or_and_fetch_8:
5428   case Builtin::BI__sync_or_and_fetch_16:
5429     BuiltinIndex = 9;
5430     break;
5431 
5432   case Builtin::BI__sync_xor_and_fetch:
5433   case Builtin::BI__sync_xor_and_fetch_1:
5434   case Builtin::BI__sync_xor_and_fetch_2:
5435   case Builtin::BI__sync_xor_and_fetch_4:
5436   case Builtin::BI__sync_xor_and_fetch_8:
5437   case Builtin::BI__sync_xor_and_fetch_16:
5438     BuiltinIndex = 10;
5439     break;
5440 
5441   case Builtin::BI__sync_nand_and_fetch:
5442   case Builtin::BI__sync_nand_and_fetch_1:
5443   case Builtin::BI__sync_nand_and_fetch_2:
5444   case Builtin::BI__sync_nand_and_fetch_4:
5445   case Builtin::BI__sync_nand_and_fetch_8:
5446   case Builtin::BI__sync_nand_and_fetch_16:
5447     BuiltinIndex = 11;
5448     WarnAboutSemanticsChange = true;
5449     break;
5450 
5451   case Builtin::BI__sync_val_compare_and_swap:
5452   case Builtin::BI__sync_val_compare_and_swap_1:
5453   case Builtin::BI__sync_val_compare_and_swap_2:
5454   case Builtin::BI__sync_val_compare_and_swap_4:
5455   case Builtin::BI__sync_val_compare_and_swap_8:
5456   case Builtin::BI__sync_val_compare_and_swap_16:
5457     BuiltinIndex = 12;
5458     NumFixed = 2;
5459     break;
5460 
5461   case Builtin::BI__sync_bool_compare_and_swap:
5462   case Builtin::BI__sync_bool_compare_and_swap_1:
5463   case Builtin::BI__sync_bool_compare_and_swap_2:
5464   case Builtin::BI__sync_bool_compare_and_swap_4:
5465   case Builtin::BI__sync_bool_compare_and_swap_8:
5466   case Builtin::BI__sync_bool_compare_and_swap_16:
5467     BuiltinIndex = 13;
5468     NumFixed = 2;
5469     ResultType = Context.BoolTy;
5470     break;
5471 
5472   case Builtin::BI__sync_lock_test_and_set:
5473   case Builtin::BI__sync_lock_test_and_set_1:
5474   case Builtin::BI__sync_lock_test_and_set_2:
5475   case Builtin::BI__sync_lock_test_and_set_4:
5476   case Builtin::BI__sync_lock_test_and_set_8:
5477   case Builtin::BI__sync_lock_test_and_set_16:
5478     BuiltinIndex = 14;
5479     break;
5480 
5481   case Builtin::BI__sync_lock_release:
5482   case Builtin::BI__sync_lock_release_1:
5483   case Builtin::BI__sync_lock_release_2:
5484   case Builtin::BI__sync_lock_release_4:
5485   case Builtin::BI__sync_lock_release_8:
5486   case Builtin::BI__sync_lock_release_16:
5487     BuiltinIndex = 15;
5488     NumFixed = 0;
5489     ResultType = Context.VoidTy;
5490     break;
5491 
5492   case Builtin::BI__sync_swap:
5493   case Builtin::BI__sync_swap_1:
5494   case Builtin::BI__sync_swap_2:
5495   case Builtin::BI__sync_swap_4:
5496   case Builtin::BI__sync_swap_8:
5497   case Builtin::BI__sync_swap_16:
5498     BuiltinIndex = 16;
5499     break;
5500   }
5501 
5502   // Now that we know how many fixed arguments we expect, first check that we
5503   // have at least that many.
5504   if (TheCall->getNumArgs() < 1+NumFixed) {
5505     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5506         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5507         << Callee->getSourceRange();
5508     return ExprError();
5509   }
5510 
5511   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5512       << Callee->getSourceRange();
5513 
5514   if (WarnAboutSemanticsChange) {
5515     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5516         << Callee->getSourceRange();
5517   }
5518 
5519   // Get the decl for the concrete builtin from this, we can tell what the
5520   // concrete integer type we should convert to is.
5521   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5522   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5523   FunctionDecl *NewBuiltinDecl;
5524   if (NewBuiltinID == BuiltinID)
5525     NewBuiltinDecl = FDecl;
5526   else {
5527     // Perform builtin lookup to avoid redeclaring it.
5528     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5529     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5530     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5531     assert(Res.getFoundDecl());
5532     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5533     if (!NewBuiltinDecl)
5534       return ExprError();
5535   }
5536 
5537   // The first argument --- the pointer --- has a fixed type; we
5538   // deduce the types of the rest of the arguments accordingly.  Walk
5539   // the remaining arguments, converting them to the deduced value type.
5540   for (unsigned i = 0; i != NumFixed; ++i) {
5541     ExprResult Arg = TheCall->getArg(i+1);
5542 
5543     // GCC does an implicit conversion to the pointer or integer ValType.  This
5544     // can fail in some cases (1i -> int**), check for this error case now.
5545     // Initialize the argument.
5546     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5547                                                    ValType, /*consume*/ false);
5548     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5549     if (Arg.isInvalid())
5550       return ExprError();
5551 
5552     // Okay, we have something that *can* be converted to the right type.  Check
5553     // to see if there is a potentially weird extension going on here.  This can
5554     // happen when you do an atomic operation on something like an char* and
5555     // pass in 42.  The 42 gets converted to char.  This is even more strange
5556     // for things like 45.123 -> char, etc.
5557     // FIXME: Do this check.
5558     TheCall->setArg(i+1, Arg.get());
5559   }
5560 
5561   // Create a new DeclRefExpr to refer to the new decl.
5562   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5563       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5564       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5565       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5566 
5567   // Set the callee in the CallExpr.
5568   // FIXME: This loses syntactic information.
5569   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5570   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5571                                               CK_BuiltinFnToFnPtr);
5572   TheCall->setCallee(PromotedCall.get());
5573 
5574   // Change the result type of the call to match the original value type. This
5575   // is arbitrary, but the codegen for these builtins ins design to handle it
5576   // gracefully.
5577   TheCall->setType(ResultType);
5578 
5579   // Prohibit use of _ExtInt with atomic builtins.
5580   // The arguments would have already been converted to the first argument's
5581   // type, so only need to check the first argument.
5582   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5583   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5584     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5585     return ExprError();
5586   }
5587 
5588   return TheCallResult;
5589 }
5590 
5591 /// SemaBuiltinNontemporalOverloaded - We have a call to
5592 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5593 /// overloaded function based on the pointer type of its last argument.
5594 ///
5595 /// This function goes through and does final semantic checking for these
5596 /// builtins.
5597 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5598   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5599   DeclRefExpr *DRE =
5600       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5601   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5602   unsigned BuiltinID = FDecl->getBuiltinID();
5603   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5604           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5605          "Unexpected nontemporal load/store builtin!");
5606   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5607   unsigned numArgs = isStore ? 2 : 1;
5608 
5609   // Ensure that we have the proper number of arguments.
5610   if (checkArgCount(*this, TheCall, numArgs))
5611     return ExprError();
5612 
5613   // Inspect the last argument of the nontemporal builtin.  This should always
5614   // be a pointer type, from which we imply the type of the memory access.
5615   // Because it is a pointer type, we don't have to worry about any implicit
5616   // casts here.
5617   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5618   ExprResult PointerArgResult =
5619       DefaultFunctionArrayLvalueConversion(PointerArg);
5620 
5621   if (PointerArgResult.isInvalid())
5622     return ExprError();
5623   PointerArg = PointerArgResult.get();
5624   TheCall->setArg(numArgs - 1, PointerArg);
5625 
5626   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5627   if (!pointerType) {
5628     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5629         << PointerArg->getType() << PointerArg->getSourceRange();
5630     return ExprError();
5631   }
5632 
5633   QualType ValType = pointerType->getPointeeType();
5634 
5635   // Strip any qualifiers off ValType.
5636   ValType = ValType.getUnqualifiedType();
5637   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5638       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5639       !ValType->isVectorType()) {
5640     Diag(DRE->getBeginLoc(),
5641          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5642         << PointerArg->getType() << PointerArg->getSourceRange();
5643     return ExprError();
5644   }
5645 
5646   if (!isStore) {
5647     TheCall->setType(ValType);
5648     return TheCallResult;
5649   }
5650 
5651   ExprResult ValArg = TheCall->getArg(0);
5652   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5653       Context, ValType, /*consume*/ false);
5654   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5655   if (ValArg.isInvalid())
5656     return ExprError();
5657 
5658   TheCall->setArg(0, ValArg.get());
5659   TheCall->setType(Context.VoidTy);
5660   return TheCallResult;
5661 }
5662 
5663 /// CheckObjCString - Checks that the argument to the builtin
5664 /// CFString constructor is correct
5665 /// Note: It might also make sense to do the UTF-16 conversion here (would
5666 /// simplify the backend).
5667 bool Sema::CheckObjCString(Expr *Arg) {
5668   Arg = Arg->IgnoreParenCasts();
5669   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5670 
5671   if (!Literal || !Literal->isAscii()) {
5672     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5673         << Arg->getSourceRange();
5674     return true;
5675   }
5676 
5677   if (Literal->containsNonAsciiOrNull()) {
5678     StringRef String = Literal->getString();
5679     unsigned NumBytes = String.size();
5680     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5681     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5682     llvm::UTF16 *ToPtr = &ToBuf[0];
5683 
5684     llvm::ConversionResult Result =
5685         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5686                                  ToPtr + NumBytes, llvm::strictConversion);
5687     // Check for conversion failure.
5688     if (Result != llvm::conversionOK)
5689       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5690           << Arg->getSourceRange();
5691   }
5692   return false;
5693 }
5694 
5695 /// CheckObjCString - Checks that the format string argument to the os_log()
5696 /// and os_trace() functions is correct, and converts it to const char *.
5697 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5698   Arg = Arg->IgnoreParenCasts();
5699   auto *Literal = dyn_cast<StringLiteral>(Arg);
5700   if (!Literal) {
5701     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5702       Literal = ObjcLiteral->getString();
5703     }
5704   }
5705 
5706   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5707     return ExprError(
5708         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5709         << Arg->getSourceRange());
5710   }
5711 
5712   ExprResult Result(Literal);
5713   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5714   InitializedEntity Entity =
5715       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5716   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5717   return Result;
5718 }
5719 
5720 /// Check that the user is calling the appropriate va_start builtin for the
5721 /// target and calling convention.
5722 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5723   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5724   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5725   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5726                     TT.getArch() == llvm::Triple::aarch64_32);
5727   bool IsWindows = TT.isOSWindows();
5728   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5729   if (IsX64 || IsAArch64) {
5730     CallingConv CC = CC_C;
5731     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5732       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5733     if (IsMSVAStart) {
5734       // Don't allow this in System V ABI functions.
5735       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5736         return S.Diag(Fn->getBeginLoc(),
5737                       diag::err_ms_va_start_used_in_sysv_function);
5738     } else {
5739       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5740       // On x64 Windows, don't allow this in System V ABI functions.
5741       // (Yes, that means there's no corresponding way to support variadic
5742       // System V ABI functions on Windows.)
5743       if ((IsWindows && CC == CC_X86_64SysV) ||
5744           (!IsWindows && CC == CC_Win64))
5745         return S.Diag(Fn->getBeginLoc(),
5746                       diag::err_va_start_used_in_wrong_abi_function)
5747                << !IsWindows;
5748     }
5749     return false;
5750   }
5751 
5752   if (IsMSVAStart)
5753     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5754   return false;
5755 }
5756 
5757 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5758                                              ParmVarDecl **LastParam = nullptr) {
5759   // Determine whether the current function, block, or obj-c method is variadic
5760   // and get its parameter list.
5761   bool IsVariadic = false;
5762   ArrayRef<ParmVarDecl *> Params;
5763   DeclContext *Caller = S.CurContext;
5764   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5765     IsVariadic = Block->isVariadic();
5766     Params = Block->parameters();
5767   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5768     IsVariadic = FD->isVariadic();
5769     Params = FD->parameters();
5770   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5771     IsVariadic = MD->isVariadic();
5772     // FIXME: This isn't correct for methods (results in bogus warning).
5773     Params = MD->parameters();
5774   } else if (isa<CapturedDecl>(Caller)) {
5775     // We don't support va_start in a CapturedDecl.
5776     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5777     return true;
5778   } else {
5779     // This must be some other declcontext that parses exprs.
5780     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5781     return true;
5782   }
5783 
5784   if (!IsVariadic) {
5785     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5786     return true;
5787   }
5788 
5789   if (LastParam)
5790     *LastParam = Params.empty() ? nullptr : Params.back();
5791 
5792   return false;
5793 }
5794 
5795 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5796 /// for validity.  Emit an error and return true on failure; return false
5797 /// on success.
5798 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5799   Expr *Fn = TheCall->getCallee();
5800 
5801   if (checkVAStartABI(*this, BuiltinID, Fn))
5802     return true;
5803 
5804   if (checkArgCount(*this, TheCall, 2))
5805     return true;
5806 
5807   // Type-check the first argument normally.
5808   if (checkBuiltinArgument(*this, TheCall, 0))
5809     return true;
5810 
5811   // Check that the current function is variadic, and get its last parameter.
5812   ParmVarDecl *LastParam;
5813   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5814     return true;
5815 
5816   // Verify that the second argument to the builtin is the last argument of the
5817   // current function or method.
5818   bool SecondArgIsLastNamedArgument = false;
5819   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5820 
5821   // These are valid if SecondArgIsLastNamedArgument is false after the next
5822   // block.
5823   QualType Type;
5824   SourceLocation ParamLoc;
5825   bool IsCRegister = false;
5826 
5827   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5828     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5829       SecondArgIsLastNamedArgument = PV == LastParam;
5830 
5831       Type = PV->getType();
5832       ParamLoc = PV->getLocation();
5833       IsCRegister =
5834           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5835     }
5836   }
5837 
5838   if (!SecondArgIsLastNamedArgument)
5839     Diag(TheCall->getArg(1)->getBeginLoc(),
5840          diag::warn_second_arg_of_va_start_not_last_named_param);
5841   else if (IsCRegister || Type->isReferenceType() ||
5842            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5843              // Promotable integers are UB, but enumerations need a bit of
5844              // extra checking to see what their promotable type actually is.
5845              if (!Type->isPromotableIntegerType())
5846                return false;
5847              if (!Type->isEnumeralType())
5848                return true;
5849              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5850              return !(ED &&
5851                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5852            }()) {
5853     unsigned Reason = 0;
5854     if (Type->isReferenceType())  Reason = 1;
5855     else if (IsCRegister)         Reason = 2;
5856     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5857     Diag(ParamLoc, diag::note_parameter_type) << Type;
5858   }
5859 
5860   TheCall->setType(Context.VoidTy);
5861   return false;
5862 }
5863 
5864 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5865   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5866   //                 const char *named_addr);
5867 
5868   Expr *Func = Call->getCallee();
5869 
5870   if (Call->getNumArgs() < 3)
5871     return Diag(Call->getEndLoc(),
5872                 diag::err_typecheck_call_too_few_args_at_least)
5873            << 0 /*function call*/ << 3 << Call->getNumArgs();
5874 
5875   // Type-check the first argument normally.
5876   if (checkBuiltinArgument(*this, Call, 0))
5877     return true;
5878 
5879   // Check that the current function is variadic.
5880   if (checkVAStartIsInVariadicFunction(*this, Func))
5881     return true;
5882 
5883   // __va_start on Windows does not validate the parameter qualifiers
5884 
5885   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5886   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5887 
5888   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5889   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5890 
5891   const QualType &ConstCharPtrTy =
5892       Context.getPointerType(Context.CharTy.withConst());
5893   if (!Arg1Ty->isPointerType() ||
5894       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5895     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5896         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5897         << 0                                      /* qualifier difference */
5898         << 3                                      /* parameter mismatch */
5899         << 2 << Arg1->getType() << ConstCharPtrTy;
5900 
5901   const QualType SizeTy = Context.getSizeType();
5902   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5903     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5904         << Arg2->getType() << SizeTy << 1 /* different class */
5905         << 0                              /* qualifier difference */
5906         << 3                              /* parameter mismatch */
5907         << 3 << Arg2->getType() << SizeTy;
5908 
5909   return false;
5910 }
5911 
5912 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5913 /// friends.  This is declared to take (...), so we have to check everything.
5914 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5915   if (checkArgCount(*this, TheCall, 2))
5916     return true;
5917 
5918   ExprResult OrigArg0 = TheCall->getArg(0);
5919   ExprResult OrigArg1 = TheCall->getArg(1);
5920 
5921   // Do standard promotions between the two arguments, returning their common
5922   // type.
5923   QualType Res = UsualArithmeticConversions(
5924       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5925   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5926     return true;
5927 
5928   // Make sure any conversions are pushed back into the call; this is
5929   // type safe since unordered compare builtins are declared as "_Bool
5930   // foo(...)".
5931   TheCall->setArg(0, OrigArg0.get());
5932   TheCall->setArg(1, OrigArg1.get());
5933 
5934   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5935     return false;
5936 
5937   // If the common type isn't a real floating type, then the arguments were
5938   // invalid for this operation.
5939   if (Res.isNull() || !Res->isRealFloatingType())
5940     return Diag(OrigArg0.get()->getBeginLoc(),
5941                 diag::err_typecheck_call_invalid_ordered_compare)
5942            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5943            << SourceRange(OrigArg0.get()->getBeginLoc(),
5944                           OrigArg1.get()->getEndLoc());
5945 
5946   return false;
5947 }
5948 
5949 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5950 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5951 /// to check everything. We expect the last argument to be a floating point
5952 /// value.
5953 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5954   if (checkArgCount(*this, TheCall, NumArgs))
5955     return true;
5956 
5957   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5958   // on all preceding parameters just being int.  Try all of those.
5959   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5960     Expr *Arg = TheCall->getArg(i);
5961 
5962     if (Arg->isTypeDependent())
5963       return false;
5964 
5965     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5966 
5967     if (Res.isInvalid())
5968       return true;
5969     TheCall->setArg(i, Res.get());
5970   }
5971 
5972   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5973 
5974   if (OrigArg->isTypeDependent())
5975     return false;
5976 
5977   // Usual Unary Conversions will convert half to float, which we want for
5978   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5979   // type how it is, but do normal L->Rvalue conversions.
5980   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5981     OrigArg = UsualUnaryConversions(OrigArg).get();
5982   else
5983     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5984   TheCall->setArg(NumArgs - 1, OrigArg);
5985 
5986   // This operation requires a non-_Complex floating-point number.
5987   if (!OrigArg->getType()->isRealFloatingType())
5988     return Diag(OrigArg->getBeginLoc(),
5989                 diag::err_typecheck_call_invalid_unary_fp)
5990            << OrigArg->getType() << OrigArg->getSourceRange();
5991 
5992   return false;
5993 }
5994 
5995 /// Perform semantic analysis for a call to __builtin_complex.
5996 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
5997   if (checkArgCount(*this, TheCall, 2))
5998     return true;
5999 
6000   bool Dependent = false;
6001   for (unsigned I = 0; I != 2; ++I) {
6002     Expr *Arg = TheCall->getArg(I);
6003     QualType T = Arg->getType();
6004     if (T->isDependentType()) {
6005       Dependent = true;
6006       continue;
6007     }
6008 
6009     // Despite supporting _Complex int, GCC requires a real floating point type
6010     // for the operands of __builtin_complex.
6011     if (!T->isRealFloatingType()) {
6012       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6013              << Arg->getType() << Arg->getSourceRange();
6014     }
6015 
6016     ExprResult Converted = DefaultLvalueConversion(Arg);
6017     if (Converted.isInvalid())
6018       return true;
6019     TheCall->setArg(I, Converted.get());
6020   }
6021 
6022   if (Dependent) {
6023     TheCall->setType(Context.DependentTy);
6024     return false;
6025   }
6026 
6027   Expr *Real = TheCall->getArg(0);
6028   Expr *Imag = TheCall->getArg(1);
6029   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6030     return Diag(Real->getBeginLoc(),
6031                 diag::err_typecheck_call_different_arg_types)
6032            << Real->getType() << Imag->getType()
6033            << Real->getSourceRange() << Imag->getSourceRange();
6034   }
6035 
6036   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6037   // don't allow this builtin to form those types either.
6038   // FIXME: Should we allow these types?
6039   if (Real->getType()->isFloat16Type())
6040     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6041            << "_Float16";
6042   if (Real->getType()->isHalfType())
6043     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6044            << "half";
6045 
6046   TheCall->setType(Context.getComplexType(Real->getType()));
6047   return false;
6048 }
6049 
6050 // Customized Sema Checking for VSX builtins that have the following signature:
6051 // vector [...] builtinName(vector [...], vector [...], const int);
6052 // Which takes the same type of vectors (any legal vector type) for the first
6053 // two arguments and takes compile time constant for the third argument.
6054 // Example builtins are :
6055 // vector double vec_xxpermdi(vector double, vector double, int);
6056 // vector short vec_xxsldwi(vector short, vector short, int);
6057 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6058   unsigned ExpectedNumArgs = 3;
6059   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6060     return true;
6061 
6062   // Check the third argument is a compile time constant
6063   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6064     return Diag(TheCall->getBeginLoc(),
6065                 diag::err_vsx_builtin_nonconstant_argument)
6066            << 3 /* argument index */ << TheCall->getDirectCallee()
6067            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6068                           TheCall->getArg(2)->getEndLoc());
6069 
6070   QualType Arg1Ty = TheCall->getArg(0)->getType();
6071   QualType Arg2Ty = TheCall->getArg(1)->getType();
6072 
6073   // Check the type of argument 1 and argument 2 are vectors.
6074   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6075   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6076       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6077     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6078            << TheCall->getDirectCallee()
6079            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6080                           TheCall->getArg(1)->getEndLoc());
6081   }
6082 
6083   // Check the first two arguments are the same type.
6084   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6085     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6086            << TheCall->getDirectCallee()
6087            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6088                           TheCall->getArg(1)->getEndLoc());
6089   }
6090 
6091   // When default clang type checking is turned off and the customized type
6092   // checking is used, the returning type of the function must be explicitly
6093   // set. Otherwise it is _Bool by default.
6094   TheCall->setType(Arg1Ty);
6095 
6096   return false;
6097 }
6098 
6099 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6100 // This is declared to take (...), so we have to check everything.
6101 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6102   if (TheCall->getNumArgs() < 2)
6103     return ExprError(Diag(TheCall->getEndLoc(),
6104                           diag::err_typecheck_call_too_few_args_at_least)
6105                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6106                      << TheCall->getSourceRange());
6107 
6108   // Determine which of the following types of shufflevector we're checking:
6109   // 1) unary, vector mask: (lhs, mask)
6110   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6111   QualType resType = TheCall->getArg(0)->getType();
6112   unsigned numElements = 0;
6113 
6114   if (!TheCall->getArg(0)->isTypeDependent() &&
6115       !TheCall->getArg(1)->isTypeDependent()) {
6116     QualType LHSType = TheCall->getArg(0)->getType();
6117     QualType RHSType = TheCall->getArg(1)->getType();
6118 
6119     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6120       return ExprError(
6121           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6122           << TheCall->getDirectCallee()
6123           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6124                          TheCall->getArg(1)->getEndLoc()));
6125 
6126     numElements = LHSType->castAs<VectorType>()->getNumElements();
6127     unsigned numResElements = TheCall->getNumArgs() - 2;
6128 
6129     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6130     // with mask.  If so, verify that RHS is an integer vector type with the
6131     // same number of elts as lhs.
6132     if (TheCall->getNumArgs() == 2) {
6133       if (!RHSType->hasIntegerRepresentation() ||
6134           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6135         return ExprError(Diag(TheCall->getBeginLoc(),
6136                               diag::err_vec_builtin_incompatible_vector)
6137                          << TheCall->getDirectCallee()
6138                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6139                                         TheCall->getArg(1)->getEndLoc()));
6140     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6141       return ExprError(Diag(TheCall->getBeginLoc(),
6142                             diag::err_vec_builtin_incompatible_vector)
6143                        << TheCall->getDirectCallee()
6144                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6145                                       TheCall->getArg(1)->getEndLoc()));
6146     } else if (numElements != numResElements) {
6147       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6148       resType = Context.getVectorType(eltType, numResElements,
6149                                       VectorType::GenericVector);
6150     }
6151   }
6152 
6153   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6154     if (TheCall->getArg(i)->isTypeDependent() ||
6155         TheCall->getArg(i)->isValueDependent())
6156       continue;
6157 
6158     Optional<llvm::APSInt> Result;
6159     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6160       return ExprError(Diag(TheCall->getBeginLoc(),
6161                             diag::err_shufflevector_nonconstant_argument)
6162                        << TheCall->getArg(i)->getSourceRange());
6163 
6164     // Allow -1 which will be translated to undef in the IR.
6165     if (Result->isSigned() && Result->isAllOnesValue())
6166       continue;
6167 
6168     if (Result->getActiveBits() > 64 ||
6169         Result->getZExtValue() >= numElements * 2)
6170       return ExprError(Diag(TheCall->getBeginLoc(),
6171                             diag::err_shufflevector_argument_too_large)
6172                        << TheCall->getArg(i)->getSourceRange());
6173   }
6174 
6175   SmallVector<Expr*, 32> exprs;
6176 
6177   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6178     exprs.push_back(TheCall->getArg(i));
6179     TheCall->setArg(i, nullptr);
6180   }
6181 
6182   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6183                                          TheCall->getCallee()->getBeginLoc(),
6184                                          TheCall->getRParenLoc());
6185 }
6186 
6187 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6188 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6189                                        SourceLocation BuiltinLoc,
6190                                        SourceLocation RParenLoc) {
6191   ExprValueKind VK = VK_RValue;
6192   ExprObjectKind OK = OK_Ordinary;
6193   QualType DstTy = TInfo->getType();
6194   QualType SrcTy = E->getType();
6195 
6196   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6197     return ExprError(Diag(BuiltinLoc,
6198                           diag::err_convertvector_non_vector)
6199                      << E->getSourceRange());
6200   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6201     return ExprError(Diag(BuiltinLoc,
6202                           diag::err_convertvector_non_vector_type));
6203 
6204   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6205     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6206     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6207     if (SrcElts != DstElts)
6208       return ExprError(Diag(BuiltinLoc,
6209                             diag::err_convertvector_incompatible_vector)
6210                        << E->getSourceRange());
6211   }
6212 
6213   return new (Context)
6214       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6215 }
6216 
6217 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6218 // This is declared to take (const void*, ...) and can take two
6219 // optional constant int args.
6220 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6221   unsigned NumArgs = TheCall->getNumArgs();
6222 
6223   if (NumArgs > 3)
6224     return Diag(TheCall->getEndLoc(),
6225                 diag::err_typecheck_call_too_many_args_at_most)
6226            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6227 
6228   // Argument 0 is checked for us and the remaining arguments must be
6229   // constant integers.
6230   for (unsigned i = 1; i != NumArgs; ++i)
6231     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6232       return true;
6233 
6234   return false;
6235 }
6236 
6237 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6238 // __assume does not evaluate its arguments, and should warn if its argument
6239 // has side effects.
6240 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6241   Expr *Arg = TheCall->getArg(0);
6242   if (Arg->isInstantiationDependent()) return false;
6243 
6244   if (Arg->HasSideEffects(Context))
6245     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6246         << Arg->getSourceRange()
6247         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6248 
6249   return false;
6250 }
6251 
6252 /// Handle __builtin_alloca_with_align. This is declared
6253 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6254 /// than 8.
6255 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6256   // The alignment must be a constant integer.
6257   Expr *Arg = TheCall->getArg(1);
6258 
6259   // We can't check the value of a dependent argument.
6260   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6261     if (const auto *UE =
6262             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6263       if (UE->getKind() == UETT_AlignOf ||
6264           UE->getKind() == UETT_PreferredAlignOf)
6265         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6266             << Arg->getSourceRange();
6267 
6268     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6269 
6270     if (!Result.isPowerOf2())
6271       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6272              << Arg->getSourceRange();
6273 
6274     if (Result < Context.getCharWidth())
6275       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6276              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6277 
6278     if (Result > std::numeric_limits<int32_t>::max())
6279       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6280              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6281   }
6282 
6283   return false;
6284 }
6285 
6286 /// Handle __builtin_assume_aligned. This is declared
6287 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6288 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6289   unsigned NumArgs = TheCall->getNumArgs();
6290 
6291   if (NumArgs > 3)
6292     return Diag(TheCall->getEndLoc(),
6293                 diag::err_typecheck_call_too_many_args_at_most)
6294            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6295 
6296   // The alignment must be a constant integer.
6297   Expr *Arg = TheCall->getArg(1);
6298 
6299   // We can't check the value of a dependent argument.
6300   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6301     llvm::APSInt Result;
6302     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6303       return true;
6304 
6305     if (!Result.isPowerOf2())
6306       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6307              << Arg->getSourceRange();
6308 
6309     if (Result > Sema::MaximumAlignment)
6310       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6311           << Arg->getSourceRange() << Sema::MaximumAlignment;
6312   }
6313 
6314   if (NumArgs > 2) {
6315     ExprResult Arg(TheCall->getArg(2));
6316     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6317       Context.getSizeType(), false);
6318     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6319     if (Arg.isInvalid()) return true;
6320     TheCall->setArg(2, Arg.get());
6321   }
6322 
6323   return false;
6324 }
6325 
6326 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6327   unsigned BuiltinID =
6328       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6329   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6330 
6331   unsigned NumArgs = TheCall->getNumArgs();
6332   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6333   if (NumArgs < NumRequiredArgs) {
6334     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6335            << 0 /* function call */ << NumRequiredArgs << NumArgs
6336            << TheCall->getSourceRange();
6337   }
6338   if (NumArgs >= NumRequiredArgs + 0x100) {
6339     return Diag(TheCall->getEndLoc(),
6340                 diag::err_typecheck_call_too_many_args_at_most)
6341            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6342            << TheCall->getSourceRange();
6343   }
6344   unsigned i = 0;
6345 
6346   // For formatting call, check buffer arg.
6347   if (!IsSizeCall) {
6348     ExprResult Arg(TheCall->getArg(i));
6349     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6350         Context, Context.VoidPtrTy, false);
6351     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6352     if (Arg.isInvalid())
6353       return true;
6354     TheCall->setArg(i, Arg.get());
6355     i++;
6356   }
6357 
6358   // Check string literal arg.
6359   unsigned FormatIdx = i;
6360   {
6361     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6362     if (Arg.isInvalid())
6363       return true;
6364     TheCall->setArg(i, Arg.get());
6365     i++;
6366   }
6367 
6368   // Make sure variadic args are scalar.
6369   unsigned FirstDataArg = i;
6370   while (i < NumArgs) {
6371     ExprResult Arg = DefaultVariadicArgumentPromotion(
6372         TheCall->getArg(i), VariadicFunction, nullptr);
6373     if (Arg.isInvalid())
6374       return true;
6375     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6376     if (ArgSize.getQuantity() >= 0x100) {
6377       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6378              << i << (int)ArgSize.getQuantity() << 0xff
6379              << TheCall->getSourceRange();
6380     }
6381     TheCall->setArg(i, Arg.get());
6382     i++;
6383   }
6384 
6385   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6386   // call to avoid duplicate diagnostics.
6387   if (!IsSizeCall) {
6388     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6389     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6390     bool Success = CheckFormatArguments(
6391         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6392         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6393         CheckedVarArgs);
6394     if (!Success)
6395       return true;
6396   }
6397 
6398   if (IsSizeCall) {
6399     TheCall->setType(Context.getSizeType());
6400   } else {
6401     TheCall->setType(Context.VoidPtrTy);
6402   }
6403   return false;
6404 }
6405 
6406 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6407 /// TheCall is a constant expression.
6408 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6409                                   llvm::APSInt &Result) {
6410   Expr *Arg = TheCall->getArg(ArgNum);
6411   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6412   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6413 
6414   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6415 
6416   Optional<llvm::APSInt> R;
6417   if (!(R = Arg->getIntegerConstantExpr(Context)))
6418     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6419            << FDecl->getDeclName() << Arg->getSourceRange();
6420   Result = *R;
6421   return false;
6422 }
6423 
6424 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6425 /// TheCall is a constant expression in the range [Low, High].
6426 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6427                                        int Low, int High, bool RangeIsError) {
6428   if (isConstantEvaluated())
6429     return false;
6430   llvm::APSInt Result;
6431 
6432   // We can't check the value of a dependent argument.
6433   Expr *Arg = TheCall->getArg(ArgNum);
6434   if (Arg->isTypeDependent() || Arg->isValueDependent())
6435     return false;
6436 
6437   // Check constant-ness first.
6438   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6439     return true;
6440 
6441   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6442     if (RangeIsError)
6443       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6444              << Result.toString(10) << Low << High << Arg->getSourceRange();
6445     else
6446       // Defer the warning until we know if the code will be emitted so that
6447       // dead code can ignore this.
6448       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6449                           PDiag(diag::warn_argument_invalid_range)
6450                               << Result.toString(10) << Low << High
6451                               << Arg->getSourceRange());
6452   }
6453 
6454   return false;
6455 }
6456 
6457 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6458 /// TheCall is a constant expression is a multiple of Num..
6459 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6460                                           unsigned Num) {
6461   llvm::APSInt Result;
6462 
6463   // We can't check the value of a dependent argument.
6464   Expr *Arg = TheCall->getArg(ArgNum);
6465   if (Arg->isTypeDependent() || Arg->isValueDependent())
6466     return false;
6467 
6468   // Check constant-ness first.
6469   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6470     return true;
6471 
6472   if (Result.getSExtValue() % Num != 0)
6473     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6474            << Num << Arg->getSourceRange();
6475 
6476   return false;
6477 }
6478 
6479 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6480 /// constant expression representing a power of 2.
6481 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6482   llvm::APSInt Result;
6483 
6484   // We can't check the value of a dependent argument.
6485   Expr *Arg = TheCall->getArg(ArgNum);
6486   if (Arg->isTypeDependent() || Arg->isValueDependent())
6487     return false;
6488 
6489   // Check constant-ness first.
6490   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6491     return true;
6492 
6493   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6494   // and only if x is a power of 2.
6495   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6496     return false;
6497 
6498   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6499          << Arg->getSourceRange();
6500 }
6501 
6502 static bool IsShiftedByte(llvm::APSInt Value) {
6503   if (Value.isNegative())
6504     return false;
6505 
6506   // Check if it's a shifted byte, by shifting it down
6507   while (true) {
6508     // If the value fits in the bottom byte, the check passes.
6509     if (Value < 0x100)
6510       return true;
6511 
6512     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6513     // fails.
6514     if ((Value & 0xFF) != 0)
6515       return false;
6516 
6517     // If the bottom 8 bits are all 0, but something above that is nonzero,
6518     // then shifting the value right by 8 bits won't affect whether it's a
6519     // shifted byte or not. So do that, and go round again.
6520     Value >>= 8;
6521   }
6522 }
6523 
6524 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6525 /// a constant expression representing an arbitrary byte value shifted left by
6526 /// a multiple of 8 bits.
6527 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6528                                              unsigned ArgBits) {
6529   llvm::APSInt Result;
6530 
6531   // We can't check the value of a dependent argument.
6532   Expr *Arg = TheCall->getArg(ArgNum);
6533   if (Arg->isTypeDependent() || Arg->isValueDependent())
6534     return false;
6535 
6536   // Check constant-ness first.
6537   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6538     return true;
6539 
6540   // Truncate to the given size.
6541   Result = Result.getLoBits(ArgBits);
6542   Result.setIsUnsigned(true);
6543 
6544   if (IsShiftedByte(Result))
6545     return false;
6546 
6547   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6548          << Arg->getSourceRange();
6549 }
6550 
6551 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6552 /// TheCall is a constant expression representing either a shifted byte value,
6553 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6554 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6555 /// Arm MVE intrinsics.
6556 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6557                                                    int ArgNum,
6558                                                    unsigned ArgBits) {
6559   llvm::APSInt Result;
6560 
6561   // We can't check the value of a dependent argument.
6562   Expr *Arg = TheCall->getArg(ArgNum);
6563   if (Arg->isTypeDependent() || Arg->isValueDependent())
6564     return false;
6565 
6566   // Check constant-ness first.
6567   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6568     return true;
6569 
6570   // Truncate to the given size.
6571   Result = Result.getLoBits(ArgBits);
6572   Result.setIsUnsigned(true);
6573 
6574   // Check to see if it's in either of the required forms.
6575   if (IsShiftedByte(Result) ||
6576       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6577     return false;
6578 
6579   return Diag(TheCall->getBeginLoc(),
6580               diag::err_argument_not_shifted_byte_or_xxff)
6581          << Arg->getSourceRange();
6582 }
6583 
6584 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6585 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6586   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6587     if (checkArgCount(*this, TheCall, 2))
6588       return true;
6589     Expr *Arg0 = TheCall->getArg(0);
6590     Expr *Arg1 = TheCall->getArg(1);
6591 
6592     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6593     if (FirstArg.isInvalid())
6594       return true;
6595     QualType FirstArgType = FirstArg.get()->getType();
6596     if (!FirstArgType->isAnyPointerType())
6597       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6598                << "first" << FirstArgType << Arg0->getSourceRange();
6599     TheCall->setArg(0, FirstArg.get());
6600 
6601     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6602     if (SecArg.isInvalid())
6603       return true;
6604     QualType SecArgType = SecArg.get()->getType();
6605     if (!SecArgType->isIntegerType())
6606       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6607                << "second" << SecArgType << Arg1->getSourceRange();
6608 
6609     // Derive the return type from the pointer argument.
6610     TheCall->setType(FirstArgType);
6611     return false;
6612   }
6613 
6614   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6615     if (checkArgCount(*this, TheCall, 2))
6616       return true;
6617 
6618     Expr *Arg0 = TheCall->getArg(0);
6619     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6620     if (FirstArg.isInvalid())
6621       return true;
6622     QualType FirstArgType = FirstArg.get()->getType();
6623     if (!FirstArgType->isAnyPointerType())
6624       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6625                << "first" << FirstArgType << Arg0->getSourceRange();
6626     TheCall->setArg(0, FirstArg.get());
6627 
6628     // Derive the return type from the pointer argument.
6629     TheCall->setType(FirstArgType);
6630 
6631     // Second arg must be an constant in range [0,15]
6632     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6633   }
6634 
6635   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6636     if (checkArgCount(*this, TheCall, 2))
6637       return true;
6638     Expr *Arg0 = TheCall->getArg(0);
6639     Expr *Arg1 = TheCall->getArg(1);
6640 
6641     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6642     if (FirstArg.isInvalid())
6643       return true;
6644     QualType FirstArgType = FirstArg.get()->getType();
6645     if (!FirstArgType->isAnyPointerType())
6646       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6647                << "first" << FirstArgType << Arg0->getSourceRange();
6648 
6649     QualType SecArgType = Arg1->getType();
6650     if (!SecArgType->isIntegerType())
6651       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6652                << "second" << SecArgType << Arg1->getSourceRange();
6653     TheCall->setType(Context.IntTy);
6654     return false;
6655   }
6656 
6657   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6658       BuiltinID == AArch64::BI__builtin_arm_stg) {
6659     if (checkArgCount(*this, TheCall, 1))
6660       return true;
6661     Expr *Arg0 = TheCall->getArg(0);
6662     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6663     if (FirstArg.isInvalid())
6664       return true;
6665 
6666     QualType FirstArgType = FirstArg.get()->getType();
6667     if (!FirstArgType->isAnyPointerType())
6668       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6669                << "first" << FirstArgType << Arg0->getSourceRange();
6670     TheCall->setArg(0, FirstArg.get());
6671 
6672     // Derive the return type from the pointer argument.
6673     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6674       TheCall->setType(FirstArgType);
6675     return false;
6676   }
6677 
6678   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6679     Expr *ArgA = TheCall->getArg(0);
6680     Expr *ArgB = TheCall->getArg(1);
6681 
6682     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6683     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6684 
6685     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6686       return true;
6687 
6688     QualType ArgTypeA = ArgExprA.get()->getType();
6689     QualType ArgTypeB = ArgExprB.get()->getType();
6690 
6691     auto isNull = [&] (Expr *E) -> bool {
6692       return E->isNullPointerConstant(
6693                         Context, Expr::NPC_ValueDependentIsNotNull); };
6694 
6695     // argument should be either a pointer or null
6696     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6697       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6698         << "first" << ArgTypeA << ArgA->getSourceRange();
6699 
6700     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6701       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6702         << "second" << ArgTypeB << ArgB->getSourceRange();
6703 
6704     // Ensure Pointee types are compatible
6705     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6706         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6707       QualType pointeeA = ArgTypeA->getPointeeType();
6708       QualType pointeeB = ArgTypeB->getPointeeType();
6709       if (!Context.typesAreCompatible(
6710              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6711              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6712         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6713           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6714           << ArgB->getSourceRange();
6715       }
6716     }
6717 
6718     // at least one argument should be pointer type
6719     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6720       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6721         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6722 
6723     if (isNull(ArgA)) // adopt type of the other pointer
6724       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6725 
6726     if (isNull(ArgB))
6727       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6728 
6729     TheCall->setArg(0, ArgExprA.get());
6730     TheCall->setArg(1, ArgExprB.get());
6731     TheCall->setType(Context.LongLongTy);
6732     return false;
6733   }
6734   assert(false && "Unhandled ARM MTE intrinsic");
6735   return true;
6736 }
6737 
6738 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6739 /// TheCall is an ARM/AArch64 special register string literal.
6740 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6741                                     int ArgNum, unsigned ExpectedFieldNum,
6742                                     bool AllowName) {
6743   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6744                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6745                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6746                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6747                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6748                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6749   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6750                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6751                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6752                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6753                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6754                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6755   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6756 
6757   // We can't check the value of a dependent argument.
6758   Expr *Arg = TheCall->getArg(ArgNum);
6759   if (Arg->isTypeDependent() || Arg->isValueDependent())
6760     return false;
6761 
6762   // Check if the argument is a string literal.
6763   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6764     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6765            << Arg->getSourceRange();
6766 
6767   // Check the type of special register given.
6768   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6769   SmallVector<StringRef, 6> Fields;
6770   Reg.split(Fields, ":");
6771 
6772   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6773     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6774            << Arg->getSourceRange();
6775 
6776   // If the string is the name of a register then we cannot check that it is
6777   // valid here but if the string is of one the forms described in ACLE then we
6778   // can check that the supplied fields are integers and within the valid
6779   // ranges.
6780   if (Fields.size() > 1) {
6781     bool FiveFields = Fields.size() == 5;
6782 
6783     bool ValidString = true;
6784     if (IsARMBuiltin) {
6785       ValidString &= Fields[0].startswith_lower("cp") ||
6786                      Fields[0].startswith_lower("p");
6787       if (ValidString)
6788         Fields[0] =
6789           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6790 
6791       ValidString &= Fields[2].startswith_lower("c");
6792       if (ValidString)
6793         Fields[2] = Fields[2].drop_front(1);
6794 
6795       if (FiveFields) {
6796         ValidString &= Fields[3].startswith_lower("c");
6797         if (ValidString)
6798           Fields[3] = Fields[3].drop_front(1);
6799       }
6800     }
6801 
6802     SmallVector<int, 5> Ranges;
6803     if (FiveFields)
6804       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6805     else
6806       Ranges.append({15, 7, 15});
6807 
6808     for (unsigned i=0; i<Fields.size(); ++i) {
6809       int IntField;
6810       ValidString &= !Fields[i].getAsInteger(10, IntField);
6811       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6812     }
6813 
6814     if (!ValidString)
6815       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6816              << Arg->getSourceRange();
6817   } else if (IsAArch64Builtin && Fields.size() == 1) {
6818     // If the register name is one of those that appear in the condition below
6819     // and the special register builtin being used is one of the write builtins,
6820     // then we require that the argument provided for writing to the register
6821     // is an integer constant expression. This is because it will be lowered to
6822     // an MSR (immediate) instruction, so we need to know the immediate at
6823     // compile time.
6824     if (TheCall->getNumArgs() != 2)
6825       return false;
6826 
6827     std::string RegLower = Reg.lower();
6828     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6829         RegLower != "pan" && RegLower != "uao")
6830       return false;
6831 
6832     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6833   }
6834 
6835   return false;
6836 }
6837 
6838 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
6839 /// Emit an error and return true on failure; return false on success.
6840 /// TypeStr is a string containing the type descriptor of the value returned by
6841 /// the builtin and the descriptors of the expected type of the arguments.
6842 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
6843 
6844   assert((TypeStr[0] != '\0') &&
6845          "Invalid types in PPC MMA builtin declaration");
6846 
6847   unsigned Mask = 0;
6848   unsigned ArgNum = 0;
6849 
6850   // The first type in TypeStr is the type of the value returned by the
6851   // builtin. So we first read that type and change the type of TheCall.
6852   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6853   TheCall->setType(type);
6854 
6855   while (*TypeStr != '\0') {
6856     Mask = 0;
6857     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6858     if (ArgNum >= TheCall->getNumArgs()) {
6859       ArgNum++;
6860       break;
6861     }
6862 
6863     Expr *Arg = TheCall->getArg(ArgNum);
6864     QualType ArgType = Arg->getType();
6865 
6866     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
6867         (!ExpectedType->isVoidPointerType() &&
6868            ArgType.getCanonicalType() != ExpectedType))
6869       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6870              << ArgType << ExpectedType << 1 << 0 << 0;
6871 
6872     // If the value of the Mask is not 0, we have a constraint in the size of
6873     // the integer argument so here we ensure the argument is a constant that
6874     // is in the valid range.
6875     if (Mask != 0 &&
6876         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
6877       return true;
6878 
6879     ArgNum++;
6880   }
6881 
6882   // In case we exited early from the previous loop, there are other types to
6883   // read from TypeStr. So we need to read them all to ensure we have the right
6884   // number of arguments in TheCall and if it is not the case, to display a
6885   // better error message.
6886   while (*TypeStr != '\0') {
6887     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6888     ArgNum++;
6889   }
6890   if (checkArgCount(*this, TheCall, ArgNum))
6891     return true;
6892 
6893   return false;
6894 }
6895 
6896 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6897 /// This checks that the target supports __builtin_longjmp and
6898 /// that val is a constant 1.
6899 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6900   if (!Context.getTargetInfo().hasSjLjLowering())
6901     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6902            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6903 
6904   Expr *Arg = TheCall->getArg(1);
6905   llvm::APSInt Result;
6906 
6907   // TODO: This is less than ideal. Overload this to take a value.
6908   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6909     return true;
6910 
6911   if (Result != 1)
6912     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6913            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6914 
6915   return false;
6916 }
6917 
6918 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6919 /// This checks that the target supports __builtin_setjmp.
6920 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6921   if (!Context.getTargetInfo().hasSjLjLowering())
6922     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6923            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6924   return false;
6925 }
6926 
6927 namespace {
6928 
6929 class UncoveredArgHandler {
6930   enum { Unknown = -1, AllCovered = -2 };
6931 
6932   signed FirstUncoveredArg = Unknown;
6933   SmallVector<const Expr *, 4> DiagnosticExprs;
6934 
6935 public:
6936   UncoveredArgHandler() = default;
6937 
6938   bool hasUncoveredArg() const {
6939     return (FirstUncoveredArg >= 0);
6940   }
6941 
6942   unsigned getUncoveredArg() const {
6943     assert(hasUncoveredArg() && "no uncovered argument");
6944     return FirstUncoveredArg;
6945   }
6946 
6947   void setAllCovered() {
6948     // A string has been found with all arguments covered, so clear out
6949     // the diagnostics.
6950     DiagnosticExprs.clear();
6951     FirstUncoveredArg = AllCovered;
6952   }
6953 
6954   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6955     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6956 
6957     // Don't update if a previous string covers all arguments.
6958     if (FirstUncoveredArg == AllCovered)
6959       return;
6960 
6961     // UncoveredArgHandler tracks the highest uncovered argument index
6962     // and with it all the strings that match this index.
6963     if (NewFirstUncoveredArg == FirstUncoveredArg)
6964       DiagnosticExprs.push_back(StrExpr);
6965     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6966       DiagnosticExprs.clear();
6967       DiagnosticExprs.push_back(StrExpr);
6968       FirstUncoveredArg = NewFirstUncoveredArg;
6969     }
6970   }
6971 
6972   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6973 };
6974 
6975 enum StringLiteralCheckType {
6976   SLCT_NotALiteral,
6977   SLCT_UncheckedLiteral,
6978   SLCT_CheckedLiteral
6979 };
6980 
6981 } // namespace
6982 
6983 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6984                                      BinaryOperatorKind BinOpKind,
6985                                      bool AddendIsRight) {
6986   unsigned BitWidth = Offset.getBitWidth();
6987   unsigned AddendBitWidth = Addend.getBitWidth();
6988   // There might be negative interim results.
6989   if (Addend.isUnsigned()) {
6990     Addend = Addend.zext(++AddendBitWidth);
6991     Addend.setIsSigned(true);
6992   }
6993   // Adjust the bit width of the APSInts.
6994   if (AddendBitWidth > BitWidth) {
6995     Offset = Offset.sext(AddendBitWidth);
6996     BitWidth = AddendBitWidth;
6997   } else if (BitWidth > AddendBitWidth) {
6998     Addend = Addend.sext(BitWidth);
6999   }
7000 
7001   bool Ov = false;
7002   llvm::APSInt ResOffset = Offset;
7003   if (BinOpKind == BO_Add)
7004     ResOffset = Offset.sadd_ov(Addend, Ov);
7005   else {
7006     assert(AddendIsRight && BinOpKind == BO_Sub &&
7007            "operator must be add or sub with addend on the right");
7008     ResOffset = Offset.ssub_ov(Addend, Ov);
7009   }
7010 
7011   // We add an offset to a pointer here so we should support an offset as big as
7012   // possible.
7013   if (Ov) {
7014     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7015            "index (intermediate) result too big");
7016     Offset = Offset.sext(2 * BitWidth);
7017     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7018     return;
7019   }
7020 
7021   Offset = ResOffset;
7022 }
7023 
7024 namespace {
7025 
7026 // This is a wrapper class around StringLiteral to support offsetted string
7027 // literals as format strings. It takes the offset into account when returning
7028 // the string and its length or the source locations to display notes correctly.
7029 class FormatStringLiteral {
7030   const StringLiteral *FExpr;
7031   int64_t Offset;
7032 
7033  public:
7034   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7035       : FExpr(fexpr), Offset(Offset) {}
7036 
7037   StringRef getString() const {
7038     return FExpr->getString().drop_front(Offset);
7039   }
7040 
7041   unsigned getByteLength() const {
7042     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7043   }
7044 
7045   unsigned getLength() const { return FExpr->getLength() - Offset; }
7046   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7047 
7048   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7049 
7050   QualType getType() const { return FExpr->getType(); }
7051 
7052   bool isAscii() const { return FExpr->isAscii(); }
7053   bool isWide() const { return FExpr->isWide(); }
7054   bool isUTF8() const { return FExpr->isUTF8(); }
7055   bool isUTF16() const { return FExpr->isUTF16(); }
7056   bool isUTF32() const { return FExpr->isUTF32(); }
7057   bool isPascal() const { return FExpr->isPascal(); }
7058 
7059   SourceLocation getLocationOfByte(
7060       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7061       const TargetInfo &Target, unsigned *StartToken = nullptr,
7062       unsigned *StartTokenByteOffset = nullptr) const {
7063     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7064                                     StartToken, StartTokenByteOffset);
7065   }
7066 
7067   SourceLocation getBeginLoc() const LLVM_READONLY {
7068     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7069   }
7070 
7071   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7072 };
7073 
7074 }  // namespace
7075 
7076 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7077                               const Expr *OrigFormatExpr,
7078                               ArrayRef<const Expr *> Args,
7079                               bool HasVAListArg, unsigned format_idx,
7080                               unsigned firstDataArg,
7081                               Sema::FormatStringType Type,
7082                               bool inFunctionCall,
7083                               Sema::VariadicCallType CallType,
7084                               llvm::SmallBitVector &CheckedVarArgs,
7085                               UncoveredArgHandler &UncoveredArg,
7086                               bool IgnoreStringsWithoutSpecifiers);
7087 
7088 // Determine if an expression is a string literal or constant string.
7089 // If this function returns false on the arguments to a function expecting a
7090 // format string, we will usually need to emit a warning.
7091 // True string literals are then checked by CheckFormatString.
7092 static StringLiteralCheckType
7093 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7094                       bool HasVAListArg, unsigned format_idx,
7095                       unsigned firstDataArg, Sema::FormatStringType Type,
7096                       Sema::VariadicCallType CallType, bool InFunctionCall,
7097                       llvm::SmallBitVector &CheckedVarArgs,
7098                       UncoveredArgHandler &UncoveredArg,
7099                       llvm::APSInt Offset,
7100                       bool IgnoreStringsWithoutSpecifiers = false) {
7101   if (S.isConstantEvaluated())
7102     return SLCT_NotALiteral;
7103  tryAgain:
7104   assert(Offset.isSigned() && "invalid offset");
7105 
7106   if (E->isTypeDependent() || E->isValueDependent())
7107     return SLCT_NotALiteral;
7108 
7109   E = E->IgnoreParenCasts();
7110 
7111   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7112     // Technically -Wformat-nonliteral does not warn about this case.
7113     // The behavior of printf and friends in this case is implementation
7114     // dependent.  Ideally if the format string cannot be null then
7115     // it should have a 'nonnull' attribute in the function prototype.
7116     return SLCT_UncheckedLiteral;
7117 
7118   switch (E->getStmtClass()) {
7119   case Stmt::BinaryConditionalOperatorClass:
7120   case Stmt::ConditionalOperatorClass: {
7121     // The expression is a literal if both sub-expressions were, and it was
7122     // completely checked only if both sub-expressions were checked.
7123     const AbstractConditionalOperator *C =
7124         cast<AbstractConditionalOperator>(E);
7125 
7126     // Determine whether it is necessary to check both sub-expressions, for
7127     // example, because the condition expression is a constant that can be
7128     // evaluated at compile time.
7129     bool CheckLeft = true, CheckRight = true;
7130 
7131     bool Cond;
7132     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7133                                                  S.isConstantEvaluated())) {
7134       if (Cond)
7135         CheckRight = false;
7136       else
7137         CheckLeft = false;
7138     }
7139 
7140     // We need to maintain the offsets for the right and the left hand side
7141     // separately to check if every possible indexed expression is a valid
7142     // string literal. They might have different offsets for different string
7143     // literals in the end.
7144     StringLiteralCheckType Left;
7145     if (!CheckLeft)
7146       Left = SLCT_UncheckedLiteral;
7147     else {
7148       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7149                                    HasVAListArg, format_idx, firstDataArg,
7150                                    Type, CallType, InFunctionCall,
7151                                    CheckedVarArgs, UncoveredArg, Offset,
7152                                    IgnoreStringsWithoutSpecifiers);
7153       if (Left == SLCT_NotALiteral || !CheckRight) {
7154         return Left;
7155       }
7156     }
7157 
7158     StringLiteralCheckType Right = checkFormatStringExpr(
7159         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7160         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7161         IgnoreStringsWithoutSpecifiers);
7162 
7163     return (CheckLeft && Left < Right) ? Left : Right;
7164   }
7165 
7166   case Stmt::ImplicitCastExprClass:
7167     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7168     goto tryAgain;
7169 
7170   case Stmt::OpaqueValueExprClass:
7171     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7172       E = src;
7173       goto tryAgain;
7174     }
7175     return SLCT_NotALiteral;
7176 
7177   case Stmt::PredefinedExprClass:
7178     // While __func__, etc., are technically not string literals, they
7179     // cannot contain format specifiers and thus are not a security
7180     // liability.
7181     return SLCT_UncheckedLiteral;
7182 
7183   case Stmt::DeclRefExprClass: {
7184     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7185 
7186     // As an exception, do not flag errors for variables binding to
7187     // const string literals.
7188     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7189       bool isConstant = false;
7190       QualType T = DR->getType();
7191 
7192       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7193         isConstant = AT->getElementType().isConstant(S.Context);
7194       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7195         isConstant = T.isConstant(S.Context) &&
7196                      PT->getPointeeType().isConstant(S.Context);
7197       } else if (T->isObjCObjectPointerType()) {
7198         // In ObjC, there is usually no "const ObjectPointer" type,
7199         // so don't check if the pointee type is constant.
7200         isConstant = T.isConstant(S.Context);
7201       }
7202 
7203       if (isConstant) {
7204         if (const Expr *Init = VD->getAnyInitializer()) {
7205           // Look through initializers like const char c[] = { "foo" }
7206           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7207             if (InitList->isStringLiteralInit())
7208               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7209           }
7210           return checkFormatStringExpr(S, Init, Args,
7211                                        HasVAListArg, format_idx,
7212                                        firstDataArg, Type, CallType,
7213                                        /*InFunctionCall*/ false, CheckedVarArgs,
7214                                        UncoveredArg, Offset);
7215         }
7216       }
7217 
7218       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7219       // special check to see if the format string is a function parameter
7220       // of the function calling the printf function.  If the function
7221       // has an attribute indicating it is a printf-like function, then we
7222       // should suppress warnings concerning non-literals being used in a call
7223       // to a vprintf function.  For example:
7224       //
7225       // void
7226       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7227       //      va_list ap;
7228       //      va_start(ap, fmt);
7229       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7230       //      ...
7231       // }
7232       if (HasVAListArg) {
7233         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7234           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7235             int PVIndex = PV->getFunctionScopeIndex() + 1;
7236             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7237               // adjust for implicit parameter
7238               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7239                 if (MD->isInstance())
7240                   ++PVIndex;
7241               // We also check if the formats are compatible.
7242               // We can't pass a 'scanf' string to a 'printf' function.
7243               if (PVIndex == PVFormat->getFormatIdx() &&
7244                   Type == S.GetFormatStringType(PVFormat))
7245                 return SLCT_UncheckedLiteral;
7246             }
7247           }
7248         }
7249       }
7250     }
7251 
7252     return SLCT_NotALiteral;
7253   }
7254 
7255   case Stmt::CallExprClass:
7256   case Stmt::CXXMemberCallExprClass: {
7257     const CallExpr *CE = cast<CallExpr>(E);
7258     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7259       bool IsFirst = true;
7260       StringLiteralCheckType CommonResult;
7261       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7262         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7263         StringLiteralCheckType Result = checkFormatStringExpr(
7264             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7265             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7266             IgnoreStringsWithoutSpecifiers);
7267         if (IsFirst) {
7268           CommonResult = Result;
7269           IsFirst = false;
7270         }
7271       }
7272       if (!IsFirst)
7273         return CommonResult;
7274 
7275       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7276         unsigned BuiltinID = FD->getBuiltinID();
7277         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7278             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7279           const Expr *Arg = CE->getArg(0);
7280           return checkFormatStringExpr(S, Arg, Args,
7281                                        HasVAListArg, format_idx,
7282                                        firstDataArg, Type, CallType,
7283                                        InFunctionCall, CheckedVarArgs,
7284                                        UncoveredArg, Offset,
7285                                        IgnoreStringsWithoutSpecifiers);
7286         }
7287       }
7288     }
7289 
7290     return SLCT_NotALiteral;
7291   }
7292   case Stmt::ObjCMessageExprClass: {
7293     const auto *ME = cast<ObjCMessageExpr>(E);
7294     if (const auto *MD = ME->getMethodDecl()) {
7295       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7296         // As a special case heuristic, if we're using the method -[NSBundle
7297         // localizedStringForKey:value:table:], ignore any key strings that lack
7298         // format specifiers. The idea is that if the key doesn't have any
7299         // format specifiers then its probably just a key to map to the
7300         // localized strings. If it does have format specifiers though, then its
7301         // likely that the text of the key is the format string in the
7302         // programmer's language, and should be checked.
7303         const ObjCInterfaceDecl *IFace;
7304         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7305             IFace->getIdentifier()->isStr("NSBundle") &&
7306             MD->getSelector().isKeywordSelector(
7307                 {"localizedStringForKey", "value", "table"})) {
7308           IgnoreStringsWithoutSpecifiers = true;
7309         }
7310 
7311         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7312         return checkFormatStringExpr(
7313             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7314             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7315             IgnoreStringsWithoutSpecifiers);
7316       }
7317     }
7318 
7319     return SLCT_NotALiteral;
7320   }
7321   case Stmt::ObjCStringLiteralClass:
7322   case Stmt::StringLiteralClass: {
7323     const StringLiteral *StrE = nullptr;
7324 
7325     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7326       StrE = ObjCFExpr->getString();
7327     else
7328       StrE = cast<StringLiteral>(E);
7329 
7330     if (StrE) {
7331       if (Offset.isNegative() || Offset > StrE->getLength()) {
7332         // TODO: It would be better to have an explicit warning for out of
7333         // bounds literals.
7334         return SLCT_NotALiteral;
7335       }
7336       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7337       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7338                         firstDataArg, Type, InFunctionCall, CallType,
7339                         CheckedVarArgs, UncoveredArg,
7340                         IgnoreStringsWithoutSpecifiers);
7341       return SLCT_CheckedLiteral;
7342     }
7343 
7344     return SLCT_NotALiteral;
7345   }
7346   case Stmt::BinaryOperatorClass: {
7347     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7348 
7349     // A string literal + an int offset is still a string literal.
7350     if (BinOp->isAdditiveOp()) {
7351       Expr::EvalResult LResult, RResult;
7352 
7353       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7354           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7355       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7356           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7357 
7358       if (LIsInt != RIsInt) {
7359         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7360 
7361         if (LIsInt) {
7362           if (BinOpKind == BO_Add) {
7363             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7364             E = BinOp->getRHS();
7365             goto tryAgain;
7366           }
7367         } else {
7368           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7369           E = BinOp->getLHS();
7370           goto tryAgain;
7371         }
7372       }
7373     }
7374 
7375     return SLCT_NotALiteral;
7376   }
7377   case Stmt::UnaryOperatorClass: {
7378     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7379     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7380     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7381       Expr::EvalResult IndexResult;
7382       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7383                                        Expr::SE_NoSideEffects,
7384                                        S.isConstantEvaluated())) {
7385         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7386                    /*RHS is int*/ true);
7387         E = ASE->getBase();
7388         goto tryAgain;
7389       }
7390     }
7391 
7392     return SLCT_NotALiteral;
7393   }
7394 
7395   default:
7396     return SLCT_NotALiteral;
7397   }
7398 }
7399 
7400 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7401   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7402       .Case("scanf", FST_Scanf)
7403       .Cases("printf", "printf0", FST_Printf)
7404       .Cases("NSString", "CFString", FST_NSString)
7405       .Case("strftime", FST_Strftime)
7406       .Case("strfmon", FST_Strfmon)
7407       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7408       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7409       .Case("os_trace", FST_OSLog)
7410       .Case("os_log", FST_OSLog)
7411       .Default(FST_Unknown);
7412 }
7413 
7414 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7415 /// functions) for correct use of format strings.
7416 /// Returns true if a format string has been fully checked.
7417 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7418                                 ArrayRef<const Expr *> Args,
7419                                 bool IsCXXMember,
7420                                 VariadicCallType CallType,
7421                                 SourceLocation Loc, SourceRange Range,
7422                                 llvm::SmallBitVector &CheckedVarArgs) {
7423   FormatStringInfo FSI;
7424   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7425     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7426                                 FSI.FirstDataArg, GetFormatStringType(Format),
7427                                 CallType, Loc, Range, CheckedVarArgs);
7428   return false;
7429 }
7430 
7431 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7432                                 bool HasVAListArg, unsigned format_idx,
7433                                 unsigned firstDataArg, FormatStringType Type,
7434                                 VariadicCallType CallType,
7435                                 SourceLocation Loc, SourceRange Range,
7436                                 llvm::SmallBitVector &CheckedVarArgs) {
7437   // CHECK: printf/scanf-like function is called with no format string.
7438   if (format_idx >= Args.size()) {
7439     Diag(Loc, diag::warn_missing_format_string) << Range;
7440     return false;
7441   }
7442 
7443   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7444 
7445   // CHECK: format string is not a string literal.
7446   //
7447   // Dynamically generated format strings are difficult to
7448   // automatically vet at compile time.  Requiring that format strings
7449   // are string literals: (1) permits the checking of format strings by
7450   // the compiler and thereby (2) can practically remove the source of
7451   // many format string exploits.
7452 
7453   // Format string can be either ObjC string (e.g. @"%d") or
7454   // C string (e.g. "%d")
7455   // ObjC string uses the same format specifiers as C string, so we can use
7456   // the same format string checking logic for both ObjC and C strings.
7457   UncoveredArgHandler UncoveredArg;
7458   StringLiteralCheckType CT =
7459       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7460                             format_idx, firstDataArg, Type, CallType,
7461                             /*IsFunctionCall*/ true, CheckedVarArgs,
7462                             UncoveredArg,
7463                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7464 
7465   // Generate a diagnostic where an uncovered argument is detected.
7466   if (UncoveredArg.hasUncoveredArg()) {
7467     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7468     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7469     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7470   }
7471 
7472   if (CT != SLCT_NotALiteral)
7473     // Literal format string found, check done!
7474     return CT == SLCT_CheckedLiteral;
7475 
7476   // Strftime is particular as it always uses a single 'time' argument,
7477   // so it is safe to pass a non-literal string.
7478   if (Type == FST_Strftime)
7479     return false;
7480 
7481   // Do not emit diag when the string param is a macro expansion and the
7482   // format is either NSString or CFString. This is a hack to prevent
7483   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7484   // which are usually used in place of NS and CF string literals.
7485   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7486   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7487     return false;
7488 
7489   // If there are no arguments specified, warn with -Wformat-security, otherwise
7490   // warn only with -Wformat-nonliteral.
7491   if (Args.size() == firstDataArg) {
7492     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7493       << OrigFormatExpr->getSourceRange();
7494     switch (Type) {
7495     default:
7496       break;
7497     case FST_Kprintf:
7498     case FST_FreeBSDKPrintf:
7499     case FST_Printf:
7500       Diag(FormatLoc, diag::note_format_security_fixit)
7501         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7502       break;
7503     case FST_NSString:
7504       Diag(FormatLoc, diag::note_format_security_fixit)
7505         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7506       break;
7507     }
7508   } else {
7509     Diag(FormatLoc, diag::warn_format_nonliteral)
7510       << OrigFormatExpr->getSourceRange();
7511   }
7512   return false;
7513 }
7514 
7515 namespace {
7516 
7517 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7518 protected:
7519   Sema &S;
7520   const FormatStringLiteral *FExpr;
7521   const Expr *OrigFormatExpr;
7522   const Sema::FormatStringType FSType;
7523   const unsigned FirstDataArg;
7524   const unsigned NumDataArgs;
7525   const char *Beg; // Start of format string.
7526   const bool HasVAListArg;
7527   ArrayRef<const Expr *> Args;
7528   unsigned FormatIdx;
7529   llvm::SmallBitVector CoveredArgs;
7530   bool usesPositionalArgs = false;
7531   bool atFirstArg = true;
7532   bool inFunctionCall;
7533   Sema::VariadicCallType CallType;
7534   llvm::SmallBitVector &CheckedVarArgs;
7535   UncoveredArgHandler &UncoveredArg;
7536 
7537 public:
7538   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7539                      const Expr *origFormatExpr,
7540                      const Sema::FormatStringType type, unsigned firstDataArg,
7541                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7542                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7543                      bool inFunctionCall, Sema::VariadicCallType callType,
7544                      llvm::SmallBitVector &CheckedVarArgs,
7545                      UncoveredArgHandler &UncoveredArg)
7546       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7547         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7548         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7549         inFunctionCall(inFunctionCall), CallType(callType),
7550         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7551     CoveredArgs.resize(numDataArgs);
7552     CoveredArgs.reset();
7553   }
7554 
7555   void DoneProcessing();
7556 
7557   void HandleIncompleteSpecifier(const char *startSpecifier,
7558                                  unsigned specifierLen) override;
7559 
7560   void HandleInvalidLengthModifier(
7561                            const analyze_format_string::FormatSpecifier &FS,
7562                            const analyze_format_string::ConversionSpecifier &CS,
7563                            const char *startSpecifier, unsigned specifierLen,
7564                            unsigned DiagID);
7565 
7566   void HandleNonStandardLengthModifier(
7567                     const analyze_format_string::FormatSpecifier &FS,
7568                     const char *startSpecifier, unsigned specifierLen);
7569 
7570   void HandleNonStandardConversionSpecifier(
7571                     const analyze_format_string::ConversionSpecifier &CS,
7572                     const char *startSpecifier, unsigned specifierLen);
7573 
7574   void HandlePosition(const char *startPos, unsigned posLen) override;
7575 
7576   void HandleInvalidPosition(const char *startSpecifier,
7577                              unsigned specifierLen,
7578                              analyze_format_string::PositionContext p) override;
7579 
7580   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7581 
7582   void HandleNullChar(const char *nullCharacter) override;
7583 
7584   template <typename Range>
7585   static void
7586   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7587                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7588                        bool IsStringLocation, Range StringRange,
7589                        ArrayRef<FixItHint> Fixit = None);
7590 
7591 protected:
7592   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7593                                         const char *startSpec,
7594                                         unsigned specifierLen,
7595                                         const char *csStart, unsigned csLen);
7596 
7597   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7598                                          const char *startSpec,
7599                                          unsigned specifierLen);
7600 
7601   SourceRange getFormatStringRange();
7602   CharSourceRange getSpecifierRange(const char *startSpecifier,
7603                                     unsigned specifierLen);
7604   SourceLocation getLocationOfByte(const char *x);
7605 
7606   const Expr *getDataArg(unsigned i) const;
7607 
7608   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7609                     const analyze_format_string::ConversionSpecifier &CS,
7610                     const char *startSpecifier, unsigned specifierLen,
7611                     unsigned argIndex);
7612 
7613   template <typename Range>
7614   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7615                             bool IsStringLocation, Range StringRange,
7616                             ArrayRef<FixItHint> Fixit = None);
7617 };
7618 
7619 } // namespace
7620 
7621 SourceRange CheckFormatHandler::getFormatStringRange() {
7622   return OrigFormatExpr->getSourceRange();
7623 }
7624 
7625 CharSourceRange CheckFormatHandler::
7626 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7627   SourceLocation Start = getLocationOfByte(startSpecifier);
7628   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7629 
7630   // Advance the end SourceLocation by one due to half-open ranges.
7631   End = End.getLocWithOffset(1);
7632 
7633   return CharSourceRange::getCharRange(Start, End);
7634 }
7635 
7636 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7637   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7638                                   S.getLangOpts(), S.Context.getTargetInfo());
7639 }
7640 
7641 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7642                                                    unsigned specifierLen){
7643   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7644                        getLocationOfByte(startSpecifier),
7645                        /*IsStringLocation*/true,
7646                        getSpecifierRange(startSpecifier, specifierLen));
7647 }
7648 
7649 void CheckFormatHandler::HandleInvalidLengthModifier(
7650     const analyze_format_string::FormatSpecifier &FS,
7651     const analyze_format_string::ConversionSpecifier &CS,
7652     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7653   using namespace analyze_format_string;
7654 
7655   const LengthModifier &LM = FS.getLengthModifier();
7656   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7657 
7658   // See if we know how to fix this length modifier.
7659   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7660   if (FixedLM) {
7661     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7662                          getLocationOfByte(LM.getStart()),
7663                          /*IsStringLocation*/true,
7664                          getSpecifierRange(startSpecifier, specifierLen));
7665 
7666     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7667       << FixedLM->toString()
7668       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7669 
7670   } else {
7671     FixItHint Hint;
7672     if (DiagID == diag::warn_format_nonsensical_length)
7673       Hint = FixItHint::CreateRemoval(LMRange);
7674 
7675     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7676                          getLocationOfByte(LM.getStart()),
7677                          /*IsStringLocation*/true,
7678                          getSpecifierRange(startSpecifier, specifierLen),
7679                          Hint);
7680   }
7681 }
7682 
7683 void CheckFormatHandler::HandleNonStandardLengthModifier(
7684     const analyze_format_string::FormatSpecifier &FS,
7685     const char *startSpecifier, unsigned specifierLen) {
7686   using namespace analyze_format_string;
7687 
7688   const LengthModifier &LM = FS.getLengthModifier();
7689   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7690 
7691   // See if we know how to fix this length modifier.
7692   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7693   if (FixedLM) {
7694     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7695                            << LM.toString() << 0,
7696                          getLocationOfByte(LM.getStart()),
7697                          /*IsStringLocation*/true,
7698                          getSpecifierRange(startSpecifier, specifierLen));
7699 
7700     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7701       << FixedLM->toString()
7702       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7703 
7704   } else {
7705     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7706                            << LM.toString() << 0,
7707                          getLocationOfByte(LM.getStart()),
7708                          /*IsStringLocation*/true,
7709                          getSpecifierRange(startSpecifier, specifierLen));
7710   }
7711 }
7712 
7713 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7714     const analyze_format_string::ConversionSpecifier &CS,
7715     const char *startSpecifier, unsigned specifierLen) {
7716   using namespace analyze_format_string;
7717 
7718   // See if we know how to fix this conversion specifier.
7719   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7720   if (FixedCS) {
7721     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7722                           << CS.toString() << /*conversion specifier*/1,
7723                          getLocationOfByte(CS.getStart()),
7724                          /*IsStringLocation*/true,
7725                          getSpecifierRange(startSpecifier, specifierLen));
7726 
7727     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7728     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7729       << FixedCS->toString()
7730       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7731   } else {
7732     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7733                           << CS.toString() << /*conversion specifier*/1,
7734                          getLocationOfByte(CS.getStart()),
7735                          /*IsStringLocation*/true,
7736                          getSpecifierRange(startSpecifier, specifierLen));
7737   }
7738 }
7739 
7740 void CheckFormatHandler::HandlePosition(const char *startPos,
7741                                         unsigned posLen) {
7742   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7743                                getLocationOfByte(startPos),
7744                                /*IsStringLocation*/true,
7745                                getSpecifierRange(startPos, posLen));
7746 }
7747 
7748 void
7749 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7750                                      analyze_format_string::PositionContext p) {
7751   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7752                          << (unsigned) p,
7753                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7754                        getSpecifierRange(startPos, posLen));
7755 }
7756 
7757 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7758                                             unsigned posLen) {
7759   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7760                                getLocationOfByte(startPos),
7761                                /*IsStringLocation*/true,
7762                                getSpecifierRange(startPos, posLen));
7763 }
7764 
7765 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7766   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7767     // The presence of a null character is likely an error.
7768     EmitFormatDiagnostic(
7769       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7770       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7771       getFormatStringRange());
7772   }
7773 }
7774 
7775 // Note that this may return NULL if there was an error parsing or building
7776 // one of the argument expressions.
7777 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7778   return Args[FirstDataArg + i];
7779 }
7780 
7781 void CheckFormatHandler::DoneProcessing() {
7782   // Does the number of data arguments exceed the number of
7783   // format conversions in the format string?
7784   if (!HasVAListArg) {
7785       // Find any arguments that weren't covered.
7786     CoveredArgs.flip();
7787     signed notCoveredArg = CoveredArgs.find_first();
7788     if (notCoveredArg >= 0) {
7789       assert((unsigned)notCoveredArg < NumDataArgs);
7790       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7791     } else {
7792       UncoveredArg.setAllCovered();
7793     }
7794   }
7795 }
7796 
7797 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7798                                    const Expr *ArgExpr) {
7799   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7800          "Invalid state");
7801 
7802   if (!ArgExpr)
7803     return;
7804 
7805   SourceLocation Loc = ArgExpr->getBeginLoc();
7806 
7807   if (S.getSourceManager().isInSystemMacro(Loc))
7808     return;
7809 
7810   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7811   for (auto E : DiagnosticExprs)
7812     PDiag << E->getSourceRange();
7813 
7814   CheckFormatHandler::EmitFormatDiagnostic(
7815                                   S, IsFunctionCall, DiagnosticExprs[0],
7816                                   PDiag, Loc, /*IsStringLocation*/false,
7817                                   DiagnosticExprs[0]->getSourceRange());
7818 }
7819 
7820 bool
7821 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7822                                                      SourceLocation Loc,
7823                                                      const char *startSpec,
7824                                                      unsigned specifierLen,
7825                                                      const char *csStart,
7826                                                      unsigned csLen) {
7827   bool keepGoing = true;
7828   if (argIndex < NumDataArgs) {
7829     // Consider the argument coverered, even though the specifier doesn't
7830     // make sense.
7831     CoveredArgs.set(argIndex);
7832   }
7833   else {
7834     // If argIndex exceeds the number of data arguments we
7835     // don't issue a warning because that is just a cascade of warnings (and
7836     // they may have intended '%%' anyway). We don't want to continue processing
7837     // the format string after this point, however, as we will like just get
7838     // gibberish when trying to match arguments.
7839     keepGoing = false;
7840   }
7841 
7842   StringRef Specifier(csStart, csLen);
7843 
7844   // If the specifier in non-printable, it could be the first byte of a UTF-8
7845   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7846   // hex value.
7847   std::string CodePointStr;
7848   if (!llvm::sys::locale::isPrint(*csStart)) {
7849     llvm::UTF32 CodePoint;
7850     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7851     const llvm::UTF8 *E =
7852         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7853     llvm::ConversionResult Result =
7854         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7855 
7856     if (Result != llvm::conversionOK) {
7857       unsigned char FirstChar = *csStart;
7858       CodePoint = (llvm::UTF32)FirstChar;
7859     }
7860 
7861     llvm::raw_string_ostream OS(CodePointStr);
7862     if (CodePoint < 256)
7863       OS << "\\x" << llvm::format("%02x", CodePoint);
7864     else if (CodePoint <= 0xFFFF)
7865       OS << "\\u" << llvm::format("%04x", CodePoint);
7866     else
7867       OS << "\\U" << llvm::format("%08x", CodePoint);
7868     OS.flush();
7869     Specifier = CodePointStr;
7870   }
7871 
7872   EmitFormatDiagnostic(
7873       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7874       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7875 
7876   return keepGoing;
7877 }
7878 
7879 void
7880 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7881                                                       const char *startSpec,
7882                                                       unsigned specifierLen) {
7883   EmitFormatDiagnostic(
7884     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7885     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7886 }
7887 
7888 bool
7889 CheckFormatHandler::CheckNumArgs(
7890   const analyze_format_string::FormatSpecifier &FS,
7891   const analyze_format_string::ConversionSpecifier &CS,
7892   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7893 
7894   if (argIndex >= NumDataArgs) {
7895     PartialDiagnostic PDiag = FS.usesPositionalArg()
7896       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7897            << (argIndex+1) << NumDataArgs)
7898       : S.PDiag(diag::warn_printf_insufficient_data_args);
7899     EmitFormatDiagnostic(
7900       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7901       getSpecifierRange(startSpecifier, specifierLen));
7902 
7903     // Since more arguments than conversion tokens are given, by extension
7904     // all arguments are covered, so mark this as so.
7905     UncoveredArg.setAllCovered();
7906     return false;
7907   }
7908   return true;
7909 }
7910 
7911 template<typename Range>
7912 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7913                                               SourceLocation Loc,
7914                                               bool IsStringLocation,
7915                                               Range StringRange,
7916                                               ArrayRef<FixItHint> FixIt) {
7917   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7918                        Loc, IsStringLocation, StringRange, FixIt);
7919 }
7920 
7921 /// If the format string is not within the function call, emit a note
7922 /// so that the function call and string are in diagnostic messages.
7923 ///
7924 /// \param InFunctionCall if true, the format string is within the function
7925 /// call and only one diagnostic message will be produced.  Otherwise, an
7926 /// extra note will be emitted pointing to location of the format string.
7927 ///
7928 /// \param ArgumentExpr the expression that is passed as the format string
7929 /// argument in the function call.  Used for getting locations when two
7930 /// diagnostics are emitted.
7931 ///
7932 /// \param PDiag the callee should already have provided any strings for the
7933 /// diagnostic message.  This function only adds locations and fixits
7934 /// to diagnostics.
7935 ///
7936 /// \param Loc primary location for diagnostic.  If two diagnostics are
7937 /// required, one will be at Loc and a new SourceLocation will be created for
7938 /// the other one.
7939 ///
7940 /// \param IsStringLocation if true, Loc points to the format string should be
7941 /// used for the note.  Otherwise, Loc points to the argument list and will
7942 /// be used with PDiag.
7943 ///
7944 /// \param StringRange some or all of the string to highlight.  This is
7945 /// templated so it can accept either a CharSourceRange or a SourceRange.
7946 ///
7947 /// \param FixIt optional fix it hint for the format string.
7948 template <typename Range>
7949 void CheckFormatHandler::EmitFormatDiagnostic(
7950     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7951     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7952     Range StringRange, ArrayRef<FixItHint> FixIt) {
7953   if (InFunctionCall) {
7954     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7955     D << StringRange;
7956     D << FixIt;
7957   } else {
7958     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7959       << ArgumentExpr->getSourceRange();
7960 
7961     const Sema::SemaDiagnosticBuilder &Note =
7962       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7963              diag::note_format_string_defined);
7964 
7965     Note << StringRange;
7966     Note << FixIt;
7967   }
7968 }
7969 
7970 //===--- CHECK: Printf format string checking ------------------------------===//
7971 
7972 namespace {
7973 
7974 class CheckPrintfHandler : public CheckFormatHandler {
7975 public:
7976   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7977                      const Expr *origFormatExpr,
7978                      const Sema::FormatStringType type, unsigned firstDataArg,
7979                      unsigned numDataArgs, bool isObjC, const char *beg,
7980                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7981                      unsigned formatIdx, bool inFunctionCall,
7982                      Sema::VariadicCallType CallType,
7983                      llvm::SmallBitVector &CheckedVarArgs,
7984                      UncoveredArgHandler &UncoveredArg)
7985       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7986                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7987                            inFunctionCall, CallType, CheckedVarArgs,
7988                            UncoveredArg) {}
7989 
7990   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7991 
7992   /// Returns true if '%@' specifiers are allowed in the format string.
7993   bool allowsObjCArg() const {
7994     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7995            FSType == Sema::FST_OSTrace;
7996   }
7997 
7998   bool HandleInvalidPrintfConversionSpecifier(
7999                                       const analyze_printf::PrintfSpecifier &FS,
8000                                       const char *startSpecifier,
8001                                       unsigned specifierLen) override;
8002 
8003   void handleInvalidMaskType(StringRef MaskType) override;
8004 
8005   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8006                              const char *startSpecifier,
8007                              unsigned specifierLen) override;
8008   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8009                        const char *StartSpecifier,
8010                        unsigned SpecifierLen,
8011                        const Expr *E);
8012 
8013   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8014                     const char *startSpecifier, unsigned specifierLen);
8015   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8016                            const analyze_printf::OptionalAmount &Amt,
8017                            unsigned type,
8018                            const char *startSpecifier, unsigned specifierLen);
8019   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8020                   const analyze_printf::OptionalFlag &flag,
8021                   const char *startSpecifier, unsigned specifierLen);
8022   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8023                          const analyze_printf::OptionalFlag &ignoredFlag,
8024                          const analyze_printf::OptionalFlag &flag,
8025                          const char *startSpecifier, unsigned specifierLen);
8026   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8027                            const Expr *E);
8028 
8029   void HandleEmptyObjCModifierFlag(const char *startFlag,
8030                                    unsigned flagLen) override;
8031 
8032   void HandleInvalidObjCModifierFlag(const char *startFlag,
8033                                             unsigned flagLen) override;
8034 
8035   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8036                                            const char *flagsEnd,
8037                                            const char *conversionPosition)
8038                                              override;
8039 };
8040 
8041 } // namespace
8042 
8043 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8044                                       const analyze_printf::PrintfSpecifier &FS,
8045                                       const char *startSpecifier,
8046                                       unsigned specifierLen) {
8047   const analyze_printf::PrintfConversionSpecifier &CS =
8048     FS.getConversionSpecifier();
8049 
8050   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8051                                           getLocationOfByte(CS.getStart()),
8052                                           startSpecifier, specifierLen,
8053                                           CS.getStart(), CS.getLength());
8054 }
8055 
8056 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8057   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8058 }
8059 
8060 bool CheckPrintfHandler::HandleAmount(
8061                                const analyze_format_string::OptionalAmount &Amt,
8062                                unsigned k, const char *startSpecifier,
8063                                unsigned specifierLen) {
8064   if (Amt.hasDataArgument()) {
8065     if (!HasVAListArg) {
8066       unsigned argIndex = Amt.getArgIndex();
8067       if (argIndex >= NumDataArgs) {
8068         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8069                                << k,
8070                              getLocationOfByte(Amt.getStart()),
8071                              /*IsStringLocation*/true,
8072                              getSpecifierRange(startSpecifier, specifierLen));
8073         // Don't do any more checking.  We will just emit
8074         // spurious errors.
8075         return false;
8076       }
8077 
8078       // Type check the data argument.  It should be an 'int'.
8079       // Although not in conformance with C99, we also allow the argument to be
8080       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8081       // doesn't emit a warning for that case.
8082       CoveredArgs.set(argIndex);
8083       const Expr *Arg = getDataArg(argIndex);
8084       if (!Arg)
8085         return false;
8086 
8087       QualType T = Arg->getType();
8088 
8089       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8090       assert(AT.isValid());
8091 
8092       if (!AT.matchesType(S.Context, T)) {
8093         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8094                                << k << AT.getRepresentativeTypeName(S.Context)
8095                                << T << Arg->getSourceRange(),
8096                              getLocationOfByte(Amt.getStart()),
8097                              /*IsStringLocation*/true,
8098                              getSpecifierRange(startSpecifier, specifierLen));
8099         // Don't do any more checking.  We will just emit
8100         // spurious errors.
8101         return false;
8102       }
8103     }
8104   }
8105   return true;
8106 }
8107 
8108 void CheckPrintfHandler::HandleInvalidAmount(
8109                                       const analyze_printf::PrintfSpecifier &FS,
8110                                       const analyze_printf::OptionalAmount &Amt,
8111                                       unsigned type,
8112                                       const char *startSpecifier,
8113                                       unsigned specifierLen) {
8114   const analyze_printf::PrintfConversionSpecifier &CS =
8115     FS.getConversionSpecifier();
8116 
8117   FixItHint fixit =
8118     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8119       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8120                                  Amt.getConstantLength()))
8121       : FixItHint();
8122 
8123   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8124                          << type << CS.toString(),
8125                        getLocationOfByte(Amt.getStart()),
8126                        /*IsStringLocation*/true,
8127                        getSpecifierRange(startSpecifier, specifierLen),
8128                        fixit);
8129 }
8130 
8131 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8132                                     const analyze_printf::OptionalFlag &flag,
8133                                     const char *startSpecifier,
8134                                     unsigned specifierLen) {
8135   // Warn about pointless flag with a fixit removal.
8136   const analyze_printf::PrintfConversionSpecifier &CS =
8137     FS.getConversionSpecifier();
8138   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8139                          << flag.toString() << CS.toString(),
8140                        getLocationOfByte(flag.getPosition()),
8141                        /*IsStringLocation*/true,
8142                        getSpecifierRange(startSpecifier, specifierLen),
8143                        FixItHint::CreateRemoval(
8144                          getSpecifierRange(flag.getPosition(), 1)));
8145 }
8146 
8147 void CheckPrintfHandler::HandleIgnoredFlag(
8148                                 const analyze_printf::PrintfSpecifier &FS,
8149                                 const analyze_printf::OptionalFlag &ignoredFlag,
8150                                 const analyze_printf::OptionalFlag &flag,
8151                                 const char *startSpecifier,
8152                                 unsigned specifierLen) {
8153   // Warn about ignored flag with a fixit removal.
8154   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8155                          << ignoredFlag.toString() << flag.toString(),
8156                        getLocationOfByte(ignoredFlag.getPosition()),
8157                        /*IsStringLocation*/true,
8158                        getSpecifierRange(startSpecifier, specifierLen),
8159                        FixItHint::CreateRemoval(
8160                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8161 }
8162 
8163 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8164                                                      unsigned flagLen) {
8165   // Warn about an empty flag.
8166   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8167                        getLocationOfByte(startFlag),
8168                        /*IsStringLocation*/true,
8169                        getSpecifierRange(startFlag, flagLen));
8170 }
8171 
8172 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8173                                                        unsigned flagLen) {
8174   // Warn about an invalid flag.
8175   auto Range = getSpecifierRange(startFlag, flagLen);
8176   StringRef flag(startFlag, flagLen);
8177   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8178                       getLocationOfByte(startFlag),
8179                       /*IsStringLocation*/true,
8180                       Range, FixItHint::CreateRemoval(Range));
8181 }
8182 
8183 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8184     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8185     // Warn about using '[...]' without a '@' conversion.
8186     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8187     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8188     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8189                          getLocationOfByte(conversionPosition),
8190                          /*IsStringLocation*/true,
8191                          Range, FixItHint::CreateRemoval(Range));
8192 }
8193 
8194 // Determines if the specified is a C++ class or struct containing
8195 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8196 // "c_str()").
8197 template<typename MemberKind>
8198 static llvm::SmallPtrSet<MemberKind*, 1>
8199 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8200   const RecordType *RT = Ty->getAs<RecordType>();
8201   llvm::SmallPtrSet<MemberKind*, 1> Results;
8202 
8203   if (!RT)
8204     return Results;
8205   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8206   if (!RD || !RD->getDefinition())
8207     return Results;
8208 
8209   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8210                  Sema::LookupMemberName);
8211   R.suppressDiagnostics();
8212 
8213   // We just need to include all members of the right kind turned up by the
8214   // filter, at this point.
8215   if (S.LookupQualifiedName(R, RT->getDecl()))
8216     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8217       NamedDecl *decl = (*I)->getUnderlyingDecl();
8218       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8219         Results.insert(FK);
8220     }
8221   return Results;
8222 }
8223 
8224 /// Check if we could call '.c_str()' on an object.
8225 ///
8226 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8227 /// allow the call, or if it would be ambiguous).
8228 bool Sema::hasCStrMethod(const Expr *E) {
8229   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8230 
8231   MethodSet Results =
8232       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8233   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8234        MI != ME; ++MI)
8235     if ((*MI)->getMinRequiredArguments() == 0)
8236       return true;
8237   return false;
8238 }
8239 
8240 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8241 // better diagnostic if so. AT is assumed to be valid.
8242 // Returns true when a c_str() conversion method is found.
8243 bool CheckPrintfHandler::checkForCStrMembers(
8244     const analyze_printf::ArgType &AT, const Expr *E) {
8245   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8246 
8247   MethodSet Results =
8248       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8249 
8250   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8251        MI != ME; ++MI) {
8252     const CXXMethodDecl *Method = *MI;
8253     if (Method->getMinRequiredArguments() == 0 &&
8254         AT.matchesType(S.Context, Method->getReturnType())) {
8255       // FIXME: Suggest parens if the expression needs them.
8256       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8257       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8258           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8259       return true;
8260     }
8261   }
8262 
8263   return false;
8264 }
8265 
8266 bool
8267 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8268                                             &FS,
8269                                           const char *startSpecifier,
8270                                           unsigned specifierLen) {
8271   using namespace analyze_format_string;
8272   using namespace analyze_printf;
8273 
8274   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8275 
8276   if (FS.consumesDataArgument()) {
8277     if (atFirstArg) {
8278         atFirstArg = false;
8279         usesPositionalArgs = FS.usesPositionalArg();
8280     }
8281     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8282       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8283                                         startSpecifier, specifierLen);
8284       return false;
8285     }
8286   }
8287 
8288   // First check if the field width, precision, and conversion specifier
8289   // have matching data arguments.
8290   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8291                     startSpecifier, specifierLen)) {
8292     return false;
8293   }
8294 
8295   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8296                     startSpecifier, specifierLen)) {
8297     return false;
8298   }
8299 
8300   if (!CS.consumesDataArgument()) {
8301     // FIXME: Technically specifying a precision or field width here
8302     // makes no sense.  Worth issuing a warning at some point.
8303     return true;
8304   }
8305 
8306   // Consume the argument.
8307   unsigned argIndex = FS.getArgIndex();
8308   if (argIndex < NumDataArgs) {
8309     // The check to see if the argIndex is valid will come later.
8310     // We set the bit here because we may exit early from this
8311     // function if we encounter some other error.
8312     CoveredArgs.set(argIndex);
8313   }
8314 
8315   // FreeBSD kernel extensions.
8316   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8317       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8318     // We need at least two arguments.
8319     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8320       return false;
8321 
8322     // Claim the second argument.
8323     CoveredArgs.set(argIndex + 1);
8324 
8325     // Type check the first argument (int for %b, pointer for %D)
8326     const Expr *Ex = getDataArg(argIndex);
8327     const analyze_printf::ArgType &AT =
8328       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8329         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8330     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8331       EmitFormatDiagnostic(
8332           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8333               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8334               << false << Ex->getSourceRange(),
8335           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8336           getSpecifierRange(startSpecifier, specifierLen));
8337 
8338     // Type check the second argument (char * for both %b and %D)
8339     Ex = getDataArg(argIndex + 1);
8340     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8341     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8342       EmitFormatDiagnostic(
8343           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8344               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8345               << false << Ex->getSourceRange(),
8346           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8347           getSpecifierRange(startSpecifier, specifierLen));
8348 
8349      return true;
8350   }
8351 
8352   // Check for using an Objective-C specific conversion specifier
8353   // in a non-ObjC literal.
8354   if (!allowsObjCArg() && CS.isObjCArg()) {
8355     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8356                                                   specifierLen);
8357   }
8358 
8359   // %P can only be used with os_log.
8360   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8361     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8362                                                   specifierLen);
8363   }
8364 
8365   // %n is not allowed with os_log.
8366   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8367     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8368                          getLocationOfByte(CS.getStart()),
8369                          /*IsStringLocation*/ false,
8370                          getSpecifierRange(startSpecifier, specifierLen));
8371 
8372     return true;
8373   }
8374 
8375   // Only scalars are allowed for os_trace.
8376   if (FSType == Sema::FST_OSTrace &&
8377       (CS.getKind() == ConversionSpecifier::PArg ||
8378        CS.getKind() == ConversionSpecifier::sArg ||
8379        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8380     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8381                                                   specifierLen);
8382   }
8383 
8384   // Check for use of public/private annotation outside of os_log().
8385   if (FSType != Sema::FST_OSLog) {
8386     if (FS.isPublic().isSet()) {
8387       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8388                                << "public",
8389                            getLocationOfByte(FS.isPublic().getPosition()),
8390                            /*IsStringLocation*/ false,
8391                            getSpecifierRange(startSpecifier, specifierLen));
8392     }
8393     if (FS.isPrivate().isSet()) {
8394       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8395                                << "private",
8396                            getLocationOfByte(FS.isPrivate().getPosition()),
8397                            /*IsStringLocation*/ false,
8398                            getSpecifierRange(startSpecifier, specifierLen));
8399     }
8400   }
8401 
8402   // Check for invalid use of field width
8403   if (!FS.hasValidFieldWidth()) {
8404     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8405         startSpecifier, specifierLen);
8406   }
8407 
8408   // Check for invalid use of precision
8409   if (!FS.hasValidPrecision()) {
8410     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8411         startSpecifier, specifierLen);
8412   }
8413 
8414   // Precision is mandatory for %P specifier.
8415   if (CS.getKind() == ConversionSpecifier::PArg &&
8416       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8417     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8418                          getLocationOfByte(startSpecifier),
8419                          /*IsStringLocation*/ false,
8420                          getSpecifierRange(startSpecifier, specifierLen));
8421   }
8422 
8423   // Check each flag does not conflict with any other component.
8424   if (!FS.hasValidThousandsGroupingPrefix())
8425     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8426   if (!FS.hasValidLeadingZeros())
8427     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8428   if (!FS.hasValidPlusPrefix())
8429     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8430   if (!FS.hasValidSpacePrefix())
8431     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8432   if (!FS.hasValidAlternativeForm())
8433     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8434   if (!FS.hasValidLeftJustified())
8435     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8436 
8437   // Check that flags are not ignored by another flag
8438   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8439     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8440         startSpecifier, specifierLen);
8441   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8442     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8443             startSpecifier, specifierLen);
8444 
8445   // Check the length modifier is valid with the given conversion specifier.
8446   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8447                                  S.getLangOpts()))
8448     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8449                                 diag::warn_format_nonsensical_length);
8450   else if (!FS.hasStandardLengthModifier())
8451     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8452   else if (!FS.hasStandardLengthConversionCombination())
8453     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8454                                 diag::warn_format_non_standard_conversion_spec);
8455 
8456   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8457     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8458 
8459   // The remaining checks depend on the data arguments.
8460   if (HasVAListArg)
8461     return true;
8462 
8463   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8464     return false;
8465 
8466   const Expr *Arg = getDataArg(argIndex);
8467   if (!Arg)
8468     return true;
8469 
8470   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8471 }
8472 
8473 static bool requiresParensToAddCast(const Expr *E) {
8474   // FIXME: We should have a general way to reason about operator
8475   // precedence and whether parens are actually needed here.
8476   // Take care of a few common cases where they aren't.
8477   const Expr *Inside = E->IgnoreImpCasts();
8478   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8479     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8480 
8481   switch (Inside->getStmtClass()) {
8482   case Stmt::ArraySubscriptExprClass:
8483   case Stmt::CallExprClass:
8484   case Stmt::CharacterLiteralClass:
8485   case Stmt::CXXBoolLiteralExprClass:
8486   case Stmt::DeclRefExprClass:
8487   case Stmt::FloatingLiteralClass:
8488   case Stmt::IntegerLiteralClass:
8489   case Stmt::MemberExprClass:
8490   case Stmt::ObjCArrayLiteralClass:
8491   case Stmt::ObjCBoolLiteralExprClass:
8492   case Stmt::ObjCBoxedExprClass:
8493   case Stmt::ObjCDictionaryLiteralClass:
8494   case Stmt::ObjCEncodeExprClass:
8495   case Stmt::ObjCIvarRefExprClass:
8496   case Stmt::ObjCMessageExprClass:
8497   case Stmt::ObjCPropertyRefExprClass:
8498   case Stmt::ObjCStringLiteralClass:
8499   case Stmt::ObjCSubscriptRefExprClass:
8500   case Stmt::ParenExprClass:
8501   case Stmt::StringLiteralClass:
8502   case Stmt::UnaryOperatorClass:
8503     return false;
8504   default:
8505     return true;
8506   }
8507 }
8508 
8509 static std::pair<QualType, StringRef>
8510 shouldNotPrintDirectly(const ASTContext &Context,
8511                        QualType IntendedTy,
8512                        const Expr *E) {
8513   // Use a 'while' to peel off layers of typedefs.
8514   QualType TyTy = IntendedTy;
8515   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8516     StringRef Name = UserTy->getDecl()->getName();
8517     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8518       .Case("CFIndex", Context.getNSIntegerType())
8519       .Case("NSInteger", Context.getNSIntegerType())
8520       .Case("NSUInteger", Context.getNSUIntegerType())
8521       .Case("SInt32", Context.IntTy)
8522       .Case("UInt32", Context.UnsignedIntTy)
8523       .Default(QualType());
8524 
8525     if (!CastTy.isNull())
8526       return std::make_pair(CastTy, Name);
8527 
8528     TyTy = UserTy->desugar();
8529   }
8530 
8531   // Strip parens if necessary.
8532   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8533     return shouldNotPrintDirectly(Context,
8534                                   PE->getSubExpr()->getType(),
8535                                   PE->getSubExpr());
8536 
8537   // If this is a conditional expression, then its result type is constructed
8538   // via usual arithmetic conversions and thus there might be no necessary
8539   // typedef sugar there.  Recurse to operands to check for NSInteger &
8540   // Co. usage condition.
8541   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8542     QualType TrueTy, FalseTy;
8543     StringRef TrueName, FalseName;
8544 
8545     std::tie(TrueTy, TrueName) =
8546       shouldNotPrintDirectly(Context,
8547                              CO->getTrueExpr()->getType(),
8548                              CO->getTrueExpr());
8549     std::tie(FalseTy, FalseName) =
8550       shouldNotPrintDirectly(Context,
8551                              CO->getFalseExpr()->getType(),
8552                              CO->getFalseExpr());
8553 
8554     if (TrueTy == FalseTy)
8555       return std::make_pair(TrueTy, TrueName);
8556     else if (TrueTy.isNull())
8557       return std::make_pair(FalseTy, FalseName);
8558     else if (FalseTy.isNull())
8559       return std::make_pair(TrueTy, TrueName);
8560   }
8561 
8562   return std::make_pair(QualType(), StringRef());
8563 }
8564 
8565 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8566 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8567 /// type do not count.
8568 static bool
8569 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8570   QualType From = ICE->getSubExpr()->getType();
8571   QualType To = ICE->getType();
8572   // It's an integer promotion if the destination type is the promoted
8573   // source type.
8574   if (ICE->getCastKind() == CK_IntegralCast &&
8575       From->isPromotableIntegerType() &&
8576       S.Context.getPromotedIntegerType(From) == To)
8577     return true;
8578   // Look through vector types, since we do default argument promotion for
8579   // those in OpenCL.
8580   if (const auto *VecTy = From->getAs<ExtVectorType>())
8581     From = VecTy->getElementType();
8582   if (const auto *VecTy = To->getAs<ExtVectorType>())
8583     To = VecTy->getElementType();
8584   // It's a floating promotion if the source type is a lower rank.
8585   return ICE->getCastKind() == CK_FloatingCast &&
8586          S.Context.getFloatingTypeOrder(From, To) < 0;
8587 }
8588 
8589 bool
8590 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8591                                     const char *StartSpecifier,
8592                                     unsigned SpecifierLen,
8593                                     const Expr *E) {
8594   using namespace analyze_format_string;
8595   using namespace analyze_printf;
8596 
8597   // Now type check the data expression that matches the
8598   // format specifier.
8599   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8600   if (!AT.isValid())
8601     return true;
8602 
8603   QualType ExprTy = E->getType();
8604   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8605     ExprTy = TET->getUnderlyingExpr()->getType();
8606   }
8607 
8608   // Diagnose attempts to print a boolean value as a character. Unlike other
8609   // -Wformat diagnostics, this is fine from a type perspective, but it still
8610   // doesn't make sense.
8611   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8612       E->isKnownToHaveBooleanValue()) {
8613     const CharSourceRange &CSR =
8614         getSpecifierRange(StartSpecifier, SpecifierLen);
8615     SmallString<4> FSString;
8616     llvm::raw_svector_ostream os(FSString);
8617     FS.toString(os);
8618     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8619                              << FSString,
8620                          E->getExprLoc(), false, CSR);
8621     return true;
8622   }
8623 
8624   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8625   if (Match == analyze_printf::ArgType::Match)
8626     return true;
8627 
8628   // Look through argument promotions for our error message's reported type.
8629   // This includes the integral and floating promotions, but excludes array
8630   // and function pointer decay (seeing that an argument intended to be a
8631   // string has type 'char [6]' is probably more confusing than 'char *') and
8632   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8633   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8634     if (isArithmeticArgumentPromotion(S, ICE)) {
8635       E = ICE->getSubExpr();
8636       ExprTy = E->getType();
8637 
8638       // Check if we didn't match because of an implicit cast from a 'char'
8639       // or 'short' to an 'int'.  This is done because printf is a varargs
8640       // function.
8641       if (ICE->getType() == S.Context.IntTy ||
8642           ICE->getType() == S.Context.UnsignedIntTy) {
8643         // All further checking is done on the subexpression
8644         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8645             AT.matchesType(S.Context, ExprTy);
8646         if (ImplicitMatch == analyze_printf::ArgType::Match)
8647           return true;
8648         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8649             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8650           Match = ImplicitMatch;
8651       }
8652     }
8653   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8654     // Special case for 'a', which has type 'int' in C.
8655     // Note, however, that we do /not/ want to treat multibyte constants like
8656     // 'MooV' as characters! This form is deprecated but still exists.
8657     if (ExprTy == S.Context.IntTy)
8658       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8659         ExprTy = S.Context.CharTy;
8660   }
8661 
8662   // Look through enums to their underlying type.
8663   bool IsEnum = false;
8664   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8665     ExprTy = EnumTy->getDecl()->getIntegerType();
8666     IsEnum = true;
8667   }
8668 
8669   // %C in an Objective-C context prints a unichar, not a wchar_t.
8670   // If the argument is an integer of some kind, believe the %C and suggest
8671   // a cast instead of changing the conversion specifier.
8672   QualType IntendedTy = ExprTy;
8673   if (isObjCContext() &&
8674       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8675     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8676         !ExprTy->isCharType()) {
8677       // 'unichar' is defined as a typedef of unsigned short, but we should
8678       // prefer using the typedef if it is visible.
8679       IntendedTy = S.Context.UnsignedShortTy;
8680 
8681       // While we are here, check if the value is an IntegerLiteral that happens
8682       // to be within the valid range.
8683       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8684         const llvm::APInt &V = IL->getValue();
8685         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8686           return true;
8687       }
8688 
8689       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8690                           Sema::LookupOrdinaryName);
8691       if (S.LookupName(Result, S.getCurScope())) {
8692         NamedDecl *ND = Result.getFoundDecl();
8693         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8694           if (TD->getUnderlyingType() == IntendedTy)
8695             IntendedTy = S.Context.getTypedefType(TD);
8696       }
8697     }
8698   }
8699 
8700   // Special-case some of Darwin's platform-independence types by suggesting
8701   // casts to primitive types that are known to be large enough.
8702   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8703   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8704     QualType CastTy;
8705     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8706     if (!CastTy.isNull()) {
8707       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8708       // (long in ASTContext). Only complain to pedants.
8709       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8710           (AT.isSizeT() || AT.isPtrdiffT()) &&
8711           AT.matchesType(S.Context, CastTy))
8712         Match = ArgType::NoMatchPedantic;
8713       IntendedTy = CastTy;
8714       ShouldNotPrintDirectly = true;
8715     }
8716   }
8717 
8718   // We may be able to offer a FixItHint if it is a supported type.
8719   PrintfSpecifier fixedFS = FS;
8720   bool Success =
8721       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8722 
8723   if (Success) {
8724     // Get the fix string from the fixed format specifier
8725     SmallString<16> buf;
8726     llvm::raw_svector_ostream os(buf);
8727     fixedFS.toString(os);
8728 
8729     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8730 
8731     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8732       unsigned Diag;
8733       switch (Match) {
8734       case ArgType::Match: llvm_unreachable("expected non-matching");
8735       case ArgType::NoMatchPedantic:
8736         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8737         break;
8738       case ArgType::NoMatchTypeConfusion:
8739         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8740         break;
8741       case ArgType::NoMatch:
8742         Diag = diag::warn_format_conversion_argument_type_mismatch;
8743         break;
8744       }
8745 
8746       // In this case, the specifier is wrong and should be changed to match
8747       // the argument.
8748       EmitFormatDiagnostic(S.PDiag(Diag)
8749                                << AT.getRepresentativeTypeName(S.Context)
8750                                << IntendedTy << IsEnum << E->getSourceRange(),
8751                            E->getBeginLoc(),
8752                            /*IsStringLocation*/ false, SpecRange,
8753                            FixItHint::CreateReplacement(SpecRange, os.str()));
8754     } else {
8755       // The canonical type for formatting this value is different from the
8756       // actual type of the expression. (This occurs, for example, with Darwin's
8757       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8758       // should be printed as 'long' for 64-bit compatibility.)
8759       // Rather than emitting a normal format/argument mismatch, we want to
8760       // add a cast to the recommended type (and correct the format string
8761       // if necessary).
8762       SmallString<16> CastBuf;
8763       llvm::raw_svector_ostream CastFix(CastBuf);
8764       CastFix << "(";
8765       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8766       CastFix << ")";
8767 
8768       SmallVector<FixItHint,4> Hints;
8769       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8770         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8771 
8772       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8773         // If there's already a cast present, just replace it.
8774         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8775         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8776 
8777       } else if (!requiresParensToAddCast(E)) {
8778         // If the expression has high enough precedence,
8779         // just write the C-style cast.
8780         Hints.push_back(
8781             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8782       } else {
8783         // Otherwise, add parens around the expression as well as the cast.
8784         CastFix << "(";
8785         Hints.push_back(
8786             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8787 
8788         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8789         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8790       }
8791 
8792       if (ShouldNotPrintDirectly) {
8793         // The expression has a type that should not be printed directly.
8794         // We extract the name from the typedef because we don't want to show
8795         // the underlying type in the diagnostic.
8796         StringRef Name;
8797         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8798           Name = TypedefTy->getDecl()->getName();
8799         else
8800           Name = CastTyName;
8801         unsigned Diag = Match == ArgType::NoMatchPedantic
8802                             ? diag::warn_format_argument_needs_cast_pedantic
8803                             : diag::warn_format_argument_needs_cast;
8804         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8805                                            << E->getSourceRange(),
8806                              E->getBeginLoc(), /*IsStringLocation=*/false,
8807                              SpecRange, Hints);
8808       } else {
8809         // In this case, the expression could be printed using a different
8810         // specifier, but we've decided that the specifier is probably correct
8811         // and we should cast instead. Just use the normal warning message.
8812         EmitFormatDiagnostic(
8813             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8814                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8815                 << E->getSourceRange(),
8816             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8817       }
8818     }
8819   } else {
8820     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8821                                                    SpecifierLen);
8822     // Since the warning for passing non-POD types to variadic functions
8823     // was deferred until now, we emit a warning for non-POD
8824     // arguments here.
8825     switch (S.isValidVarArgType(ExprTy)) {
8826     case Sema::VAK_Valid:
8827     case Sema::VAK_ValidInCXX11: {
8828       unsigned Diag;
8829       switch (Match) {
8830       case ArgType::Match: llvm_unreachable("expected non-matching");
8831       case ArgType::NoMatchPedantic:
8832         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8833         break;
8834       case ArgType::NoMatchTypeConfusion:
8835         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8836         break;
8837       case ArgType::NoMatch:
8838         Diag = diag::warn_format_conversion_argument_type_mismatch;
8839         break;
8840       }
8841 
8842       EmitFormatDiagnostic(
8843           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8844                         << IsEnum << CSR << E->getSourceRange(),
8845           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8846       break;
8847     }
8848     case Sema::VAK_Undefined:
8849     case Sema::VAK_MSVCUndefined:
8850       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8851                                << S.getLangOpts().CPlusPlus11 << ExprTy
8852                                << CallType
8853                                << AT.getRepresentativeTypeName(S.Context) << CSR
8854                                << E->getSourceRange(),
8855                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8856       checkForCStrMembers(AT, E);
8857       break;
8858 
8859     case Sema::VAK_Invalid:
8860       if (ExprTy->isObjCObjectType())
8861         EmitFormatDiagnostic(
8862             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8863                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8864                 << AT.getRepresentativeTypeName(S.Context) << CSR
8865                 << E->getSourceRange(),
8866             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8867       else
8868         // FIXME: If this is an initializer list, suggest removing the braces
8869         // or inserting a cast to the target type.
8870         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8871             << isa<InitListExpr>(E) << ExprTy << CallType
8872             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8873       break;
8874     }
8875 
8876     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8877            "format string specifier index out of range");
8878     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8879   }
8880 
8881   return true;
8882 }
8883 
8884 //===--- CHECK: Scanf format string checking ------------------------------===//
8885 
8886 namespace {
8887 
8888 class CheckScanfHandler : public CheckFormatHandler {
8889 public:
8890   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8891                     const Expr *origFormatExpr, Sema::FormatStringType type,
8892                     unsigned firstDataArg, unsigned numDataArgs,
8893                     const char *beg, bool hasVAListArg,
8894                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8895                     bool inFunctionCall, Sema::VariadicCallType CallType,
8896                     llvm::SmallBitVector &CheckedVarArgs,
8897                     UncoveredArgHandler &UncoveredArg)
8898       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8899                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8900                            inFunctionCall, CallType, CheckedVarArgs,
8901                            UncoveredArg) {}
8902 
8903   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8904                             const char *startSpecifier,
8905                             unsigned specifierLen) override;
8906 
8907   bool HandleInvalidScanfConversionSpecifier(
8908           const analyze_scanf::ScanfSpecifier &FS,
8909           const char *startSpecifier,
8910           unsigned specifierLen) override;
8911 
8912   void HandleIncompleteScanList(const char *start, const char *end) override;
8913 };
8914 
8915 } // namespace
8916 
8917 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8918                                                  const char *end) {
8919   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8920                        getLocationOfByte(end), /*IsStringLocation*/true,
8921                        getSpecifierRange(start, end - start));
8922 }
8923 
8924 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8925                                         const analyze_scanf::ScanfSpecifier &FS,
8926                                         const char *startSpecifier,
8927                                         unsigned specifierLen) {
8928   const analyze_scanf::ScanfConversionSpecifier &CS =
8929     FS.getConversionSpecifier();
8930 
8931   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8932                                           getLocationOfByte(CS.getStart()),
8933                                           startSpecifier, specifierLen,
8934                                           CS.getStart(), CS.getLength());
8935 }
8936 
8937 bool CheckScanfHandler::HandleScanfSpecifier(
8938                                        const analyze_scanf::ScanfSpecifier &FS,
8939                                        const char *startSpecifier,
8940                                        unsigned specifierLen) {
8941   using namespace analyze_scanf;
8942   using namespace analyze_format_string;
8943 
8944   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8945 
8946   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8947   // be used to decide if we are using positional arguments consistently.
8948   if (FS.consumesDataArgument()) {
8949     if (atFirstArg) {
8950       atFirstArg = false;
8951       usesPositionalArgs = FS.usesPositionalArg();
8952     }
8953     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8954       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8955                                         startSpecifier, specifierLen);
8956       return false;
8957     }
8958   }
8959 
8960   // Check if the field with is non-zero.
8961   const OptionalAmount &Amt = FS.getFieldWidth();
8962   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8963     if (Amt.getConstantAmount() == 0) {
8964       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8965                                                    Amt.getConstantLength());
8966       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8967                            getLocationOfByte(Amt.getStart()),
8968                            /*IsStringLocation*/true, R,
8969                            FixItHint::CreateRemoval(R));
8970     }
8971   }
8972 
8973   if (!FS.consumesDataArgument()) {
8974     // FIXME: Technically specifying a precision or field width here
8975     // makes no sense.  Worth issuing a warning at some point.
8976     return true;
8977   }
8978 
8979   // Consume the argument.
8980   unsigned argIndex = FS.getArgIndex();
8981   if (argIndex < NumDataArgs) {
8982       // The check to see if the argIndex is valid will come later.
8983       // We set the bit here because we may exit early from this
8984       // function if we encounter some other error.
8985     CoveredArgs.set(argIndex);
8986   }
8987 
8988   // Check the length modifier is valid with the given conversion specifier.
8989   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8990                                  S.getLangOpts()))
8991     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8992                                 diag::warn_format_nonsensical_length);
8993   else if (!FS.hasStandardLengthModifier())
8994     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8995   else if (!FS.hasStandardLengthConversionCombination())
8996     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8997                                 diag::warn_format_non_standard_conversion_spec);
8998 
8999   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9000     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9001 
9002   // The remaining checks depend on the data arguments.
9003   if (HasVAListArg)
9004     return true;
9005 
9006   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9007     return false;
9008 
9009   // Check that the argument type matches the format specifier.
9010   const Expr *Ex = getDataArg(argIndex);
9011   if (!Ex)
9012     return true;
9013 
9014   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9015 
9016   if (!AT.isValid()) {
9017     return true;
9018   }
9019 
9020   analyze_format_string::ArgType::MatchKind Match =
9021       AT.matchesType(S.Context, Ex->getType());
9022   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9023   if (Match == analyze_format_string::ArgType::Match)
9024     return true;
9025 
9026   ScanfSpecifier fixedFS = FS;
9027   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9028                                  S.getLangOpts(), S.Context);
9029 
9030   unsigned Diag =
9031       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9032                : diag::warn_format_conversion_argument_type_mismatch;
9033 
9034   if (Success) {
9035     // Get the fix string from the fixed format specifier.
9036     SmallString<128> buf;
9037     llvm::raw_svector_ostream os(buf);
9038     fixedFS.toString(os);
9039 
9040     EmitFormatDiagnostic(
9041         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9042                       << Ex->getType() << false << Ex->getSourceRange(),
9043         Ex->getBeginLoc(),
9044         /*IsStringLocation*/ false,
9045         getSpecifierRange(startSpecifier, specifierLen),
9046         FixItHint::CreateReplacement(
9047             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9048   } else {
9049     EmitFormatDiagnostic(S.PDiag(Diag)
9050                              << AT.getRepresentativeTypeName(S.Context)
9051                              << Ex->getType() << false << Ex->getSourceRange(),
9052                          Ex->getBeginLoc(),
9053                          /*IsStringLocation*/ false,
9054                          getSpecifierRange(startSpecifier, specifierLen));
9055   }
9056 
9057   return true;
9058 }
9059 
9060 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9061                               const Expr *OrigFormatExpr,
9062                               ArrayRef<const Expr *> Args,
9063                               bool HasVAListArg, unsigned format_idx,
9064                               unsigned firstDataArg,
9065                               Sema::FormatStringType Type,
9066                               bool inFunctionCall,
9067                               Sema::VariadicCallType CallType,
9068                               llvm::SmallBitVector &CheckedVarArgs,
9069                               UncoveredArgHandler &UncoveredArg,
9070                               bool IgnoreStringsWithoutSpecifiers) {
9071   // CHECK: is the format string a wide literal?
9072   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9073     CheckFormatHandler::EmitFormatDiagnostic(
9074         S, inFunctionCall, Args[format_idx],
9075         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9076         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9077     return;
9078   }
9079 
9080   // Str - The format string.  NOTE: this is NOT null-terminated!
9081   StringRef StrRef = FExpr->getString();
9082   const char *Str = StrRef.data();
9083   // Account for cases where the string literal is truncated in a declaration.
9084   const ConstantArrayType *T =
9085     S.Context.getAsConstantArrayType(FExpr->getType());
9086   assert(T && "String literal not of constant array type!");
9087   size_t TypeSize = T->getSize().getZExtValue();
9088   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9089   const unsigned numDataArgs = Args.size() - firstDataArg;
9090 
9091   if (IgnoreStringsWithoutSpecifiers &&
9092       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9093           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9094     return;
9095 
9096   // Emit a warning if the string literal is truncated and does not contain an
9097   // embedded null character.
9098   if (TypeSize <= StrRef.size() &&
9099       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9100     CheckFormatHandler::EmitFormatDiagnostic(
9101         S, inFunctionCall, Args[format_idx],
9102         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9103         FExpr->getBeginLoc(),
9104         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9105     return;
9106   }
9107 
9108   // CHECK: empty format string?
9109   if (StrLen == 0 && numDataArgs > 0) {
9110     CheckFormatHandler::EmitFormatDiagnostic(
9111         S, inFunctionCall, Args[format_idx],
9112         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9113         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9114     return;
9115   }
9116 
9117   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9118       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9119       Type == Sema::FST_OSTrace) {
9120     CheckPrintfHandler H(
9121         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9122         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9123         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9124         CheckedVarArgs, UncoveredArg);
9125 
9126     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9127                                                   S.getLangOpts(),
9128                                                   S.Context.getTargetInfo(),
9129                                             Type == Sema::FST_FreeBSDKPrintf))
9130       H.DoneProcessing();
9131   } else if (Type == Sema::FST_Scanf) {
9132     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9133                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9134                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9135 
9136     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9137                                                  S.getLangOpts(),
9138                                                  S.Context.getTargetInfo()))
9139       H.DoneProcessing();
9140   } // TODO: handle other formats
9141 }
9142 
9143 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9144   // Str - The format string.  NOTE: this is NOT null-terminated!
9145   StringRef StrRef = FExpr->getString();
9146   const char *Str = StrRef.data();
9147   // Account for cases where the string literal is truncated in a declaration.
9148   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9149   assert(T && "String literal not of constant array type!");
9150   size_t TypeSize = T->getSize().getZExtValue();
9151   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9152   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9153                                                          getLangOpts(),
9154                                                          Context.getTargetInfo());
9155 }
9156 
9157 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9158 
9159 // Returns the related absolute value function that is larger, of 0 if one
9160 // does not exist.
9161 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9162   switch (AbsFunction) {
9163   default:
9164     return 0;
9165 
9166   case Builtin::BI__builtin_abs:
9167     return Builtin::BI__builtin_labs;
9168   case Builtin::BI__builtin_labs:
9169     return Builtin::BI__builtin_llabs;
9170   case Builtin::BI__builtin_llabs:
9171     return 0;
9172 
9173   case Builtin::BI__builtin_fabsf:
9174     return Builtin::BI__builtin_fabs;
9175   case Builtin::BI__builtin_fabs:
9176     return Builtin::BI__builtin_fabsl;
9177   case Builtin::BI__builtin_fabsl:
9178     return 0;
9179 
9180   case Builtin::BI__builtin_cabsf:
9181     return Builtin::BI__builtin_cabs;
9182   case Builtin::BI__builtin_cabs:
9183     return Builtin::BI__builtin_cabsl;
9184   case Builtin::BI__builtin_cabsl:
9185     return 0;
9186 
9187   case Builtin::BIabs:
9188     return Builtin::BIlabs;
9189   case Builtin::BIlabs:
9190     return Builtin::BIllabs;
9191   case Builtin::BIllabs:
9192     return 0;
9193 
9194   case Builtin::BIfabsf:
9195     return Builtin::BIfabs;
9196   case Builtin::BIfabs:
9197     return Builtin::BIfabsl;
9198   case Builtin::BIfabsl:
9199     return 0;
9200 
9201   case Builtin::BIcabsf:
9202    return Builtin::BIcabs;
9203   case Builtin::BIcabs:
9204     return Builtin::BIcabsl;
9205   case Builtin::BIcabsl:
9206     return 0;
9207   }
9208 }
9209 
9210 // Returns the argument type of the absolute value function.
9211 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9212                                              unsigned AbsType) {
9213   if (AbsType == 0)
9214     return QualType();
9215 
9216   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9217   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9218   if (Error != ASTContext::GE_None)
9219     return QualType();
9220 
9221   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9222   if (!FT)
9223     return QualType();
9224 
9225   if (FT->getNumParams() != 1)
9226     return QualType();
9227 
9228   return FT->getParamType(0);
9229 }
9230 
9231 // Returns the best absolute value function, or zero, based on type and
9232 // current absolute value function.
9233 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9234                                    unsigned AbsFunctionKind) {
9235   unsigned BestKind = 0;
9236   uint64_t ArgSize = Context.getTypeSize(ArgType);
9237   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9238        Kind = getLargerAbsoluteValueFunction(Kind)) {
9239     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9240     if (Context.getTypeSize(ParamType) >= ArgSize) {
9241       if (BestKind == 0)
9242         BestKind = Kind;
9243       else if (Context.hasSameType(ParamType, ArgType)) {
9244         BestKind = Kind;
9245         break;
9246       }
9247     }
9248   }
9249   return BestKind;
9250 }
9251 
9252 enum AbsoluteValueKind {
9253   AVK_Integer,
9254   AVK_Floating,
9255   AVK_Complex
9256 };
9257 
9258 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9259   if (T->isIntegralOrEnumerationType())
9260     return AVK_Integer;
9261   if (T->isRealFloatingType())
9262     return AVK_Floating;
9263   if (T->isAnyComplexType())
9264     return AVK_Complex;
9265 
9266   llvm_unreachable("Type not integer, floating, or complex");
9267 }
9268 
9269 // Changes the absolute value function to a different type.  Preserves whether
9270 // the function is a builtin.
9271 static unsigned changeAbsFunction(unsigned AbsKind,
9272                                   AbsoluteValueKind ValueKind) {
9273   switch (ValueKind) {
9274   case AVK_Integer:
9275     switch (AbsKind) {
9276     default:
9277       return 0;
9278     case Builtin::BI__builtin_fabsf:
9279     case Builtin::BI__builtin_fabs:
9280     case Builtin::BI__builtin_fabsl:
9281     case Builtin::BI__builtin_cabsf:
9282     case Builtin::BI__builtin_cabs:
9283     case Builtin::BI__builtin_cabsl:
9284       return Builtin::BI__builtin_abs;
9285     case Builtin::BIfabsf:
9286     case Builtin::BIfabs:
9287     case Builtin::BIfabsl:
9288     case Builtin::BIcabsf:
9289     case Builtin::BIcabs:
9290     case Builtin::BIcabsl:
9291       return Builtin::BIabs;
9292     }
9293   case AVK_Floating:
9294     switch (AbsKind) {
9295     default:
9296       return 0;
9297     case Builtin::BI__builtin_abs:
9298     case Builtin::BI__builtin_labs:
9299     case Builtin::BI__builtin_llabs:
9300     case Builtin::BI__builtin_cabsf:
9301     case Builtin::BI__builtin_cabs:
9302     case Builtin::BI__builtin_cabsl:
9303       return Builtin::BI__builtin_fabsf;
9304     case Builtin::BIabs:
9305     case Builtin::BIlabs:
9306     case Builtin::BIllabs:
9307     case Builtin::BIcabsf:
9308     case Builtin::BIcabs:
9309     case Builtin::BIcabsl:
9310       return Builtin::BIfabsf;
9311     }
9312   case AVK_Complex:
9313     switch (AbsKind) {
9314     default:
9315       return 0;
9316     case Builtin::BI__builtin_abs:
9317     case Builtin::BI__builtin_labs:
9318     case Builtin::BI__builtin_llabs:
9319     case Builtin::BI__builtin_fabsf:
9320     case Builtin::BI__builtin_fabs:
9321     case Builtin::BI__builtin_fabsl:
9322       return Builtin::BI__builtin_cabsf;
9323     case Builtin::BIabs:
9324     case Builtin::BIlabs:
9325     case Builtin::BIllabs:
9326     case Builtin::BIfabsf:
9327     case Builtin::BIfabs:
9328     case Builtin::BIfabsl:
9329       return Builtin::BIcabsf;
9330     }
9331   }
9332   llvm_unreachable("Unable to convert function");
9333 }
9334 
9335 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9336   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9337   if (!FnInfo)
9338     return 0;
9339 
9340   switch (FDecl->getBuiltinID()) {
9341   default:
9342     return 0;
9343   case Builtin::BI__builtin_abs:
9344   case Builtin::BI__builtin_fabs:
9345   case Builtin::BI__builtin_fabsf:
9346   case Builtin::BI__builtin_fabsl:
9347   case Builtin::BI__builtin_labs:
9348   case Builtin::BI__builtin_llabs:
9349   case Builtin::BI__builtin_cabs:
9350   case Builtin::BI__builtin_cabsf:
9351   case Builtin::BI__builtin_cabsl:
9352   case Builtin::BIabs:
9353   case Builtin::BIlabs:
9354   case Builtin::BIllabs:
9355   case Builtin::BIfabs:
9356   case Builtin::BIfabsf:
9357   case Builtin::BIfabsl:
9358   case Builtin::BIcabs:
9359   case Builtin::BIcabsf:
9360   case Builtin::BIcabsl:
9361     return FDecl->getBuiltinID();
9362   }
9363   llvm_unreachable("Unknown Builtin type");
9364 }
9365 
9366 // If the replacement is valid, emit a note with replacement function.
9367 // Additionally, suggest including the proper header if not already included.
9368 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9369                             unsigned AbsKind, QualType ArgType) {
9370   bool EmitHeaderHint = true;
9371   const char *HeaderName = nullptr;
9372   const char *FunctionName = nullptr;
9373   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9374     FunctionName = "std::abs";
9375     if (ArgType->isIntegralOrEnumerationType()) {
9376       HeaderName = "cstdlib";
9377     } else if (ArgType->isRealFloatingType()) {
9378       HeaderName = "cmath";
9379     } else {
9380       llvm_unreachable("Invalid Type");
9381     }
9382 
9383     // Lookup all std::abs
9384     if (NamespaceDecl *Std = S.getStdNamespace()) {
9385       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9386       R.suppressDiagnostics();
9387       S.LookupQualifiedName(R, Std);
9388 
9389       for (const auto *I : R) {
9390         const FunctionDecl *FDecl = nullptr;
9391         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9392           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9393         } else {
9394           FDecl = dyn_cast<FunctionDecl>(I);
9395         }
9396         if (!FDecl)
9397           continue;
9398 
9399         // Found std::abs(), check that they are the right ones.
9400         if (FDecl->getNumParams() != 1)
9401           continue;
9402 
9403         // Check that the parameter type can handle the argument.
9404         QualType ParamType = FDecl->getParamDecl(0)->getType();
9405         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9406             S.Context.getTypeSize(ArgType) <=
9407                 S.Context.getTypeSize(ParamType)) {
9408           // Found a function, don't need the header hint.
9409           EmitHeaderHint = false;
9410           break;
9411         }
9412       }
9413     }
9414   } else {
9415     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9416     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9417 
9418     if (HeaderName) {
9419       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9420       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9421       R.suppressDiagnostics();
9422       S.LookupName(R, S.getCurScope());
9423 
9424       if (R.isSingleResult()) {
9425         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9426         if (FD && FD->getBuiltinID() == AbsKind) {
9427           EmitHeaderHint = false;
9428         } else {
9429           return;
9430         }
9431       } else if (!R.empty()) {
9432         return;
9433       }
9434     }
9435   }
9436 
9437   S.Diag(Loc, diag::note_replace_abs_function)
9438       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9439 
9440   if (!HeaderName)
9441     return;
9442 
9443   if (!EmitHeaderHint)
9444     return;
9445 
9446   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9447                                                     << FunctionName;
9448 }
9449 
9450 template <std::size_t StrLen>
9451 static bool IsStdFunction(const FunctionDecl *FDecl,
9452                           const char (&Str)[StrLen]) {
9453   if (!FDecl)
9454     return false;
9455   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9456     return false;
9457   if (!FDecl->isInStdNamespace())
9458     return false;
9459 
9460   return true;
9461 }
9462 
9463 // Warn when using the wrong abs() function.
9464 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9465                                       const FunctionDecl *FDecl) {
9466   if (Call->getNumArgs() != 1)
9467     return;
9468 
9469   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9470   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9471   if (AbsKind == 0 && !IsStdAbs)
9472     return;
9473 
9474   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9475   QualType ParamType = Call->getArg(0)->getType();
9476 
9477   // Unsigned types cannot be negative.  Suggest removing the absolute value
9478   // function call.
9479   if (ArgType->isUnsignedIntegerType()) {
9480     const char *FunctionName =
9481         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9482     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9483     Diag(Call->getExprLoc(), diag::note_remove_abs)
9484         << FunctionName
9485         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9486     return;
9487   }
9488 
9489   // Taking the absolute value of a pointer is very suspicious, they probably
9490   // wanted to index into an array, dereference a pointer, call a function, etc.
9491   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9492     unsigned DiagType = 0;
9493     if (ArgType->isFunctionType())
9494       DiagType = 1;
9495     else if (ArgType->isArrayType())
9496       DiagType = 2;
9497 
9498     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9499     return;
9500   }
9501 
9502   // std::abs has overloads which prevent most of the absolute value problems
9503   // from occurring.
9504   if (IsStdAbs)
9505     return;
9506 
9507   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9508   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9509 
9510   // The argument and parameter are the same kind.  Check if they are the right
9511   // size.
9512   if (ArgValueKind == ParamValueKind) {
9513     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9514       return;
9515 
9516     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9517     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9518         << FDecl << ArgType << ParamType;
9519 
9520     if (NewAbsKind == 0)
9521       return;
9522 
9523     emitReplacement(*this, Call->getExprLoc(),
9524                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9525     return;
9526   }
9527 
9528   // ArgValueKind != ParamValueKind
9529   // The wrong type of absolute value function was used.  Attempt to find the
9530   // proper one.
9531   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9532   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9533   if (NewAbsKind == 0)
9534     return;
9535 
9536   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9537       << FDecl << ParamValueKind << ArgValueKind;
9538 
9539   emitReplacement(*this, Call->getExprLoc(),
9540                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9541 }
9542 
9543 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9544 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9545                                 const FunctionDecl *FDecl) {
9546   if (!Call || !FDecl) return;
9547 
9548   // Ignore template specializations and macros.
9549   if (inTemplateInstantiation()) return;
9550   if (Call->getExprLoc().isMacroID()) return;
9551 
9552   // Only care about the one template argument, two function parameter std::max
9553   if (Call->getNumArgs() != 2) return;
9554   if (!IsStdFunction(FDecl, "max")) return;
9555   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9556   if (!ArgList) return;
9557   if (ArgList->size() != 1) return;
9558 
9559   // Check that template type argument is unsigned integer.
9560   const auto& TA = ArgList->get(0);
9561   if (TA.getKind() != TemplateArgument::Type) return;
9562   QualType ArgType = TA.getAsType();
9563   if (!ArgType->isUnsignedIntegerType()) return;
9564 
9565   // See if either argument is a literal zero.
9566   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9567     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9568     if (!MTE) return false;
9569     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9570     if (!Num) return false;
9571     if (Num->getValue() != 0) return false;
9572     return true;
9573   };
9574 
9575   const Expr *FirstArg = Call->getArg(0);
9576   const Expr *SecondArg = Call->getArg(1);
9577   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9578   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9579 
9580   // Only warn when exactly one argument is zero.
9581   if (IsFirstArgZero == IsSecondArgZero) return;
9582 
9583   SourceRange FirstRange = FirstArg->getSourceRange();
9584   SourceRange SecondRange = SecondArg->getSourceRange();
9585 
9586   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9587 
9588   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9589       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9590 
9591   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9592   SourceRange RemovalRange;
9593   if (IsFirstArgZero) {
9594     RemovalRange = SourceRange(FirstRange.getBegin(),
9595                                SecondRange.getBegin().getLocWithOffset(-1));
9596   } else {
9597     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9598                                SecondRange.getEnd());
9599   }
9600 
9601   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9602         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9603         << FixItHint::CreateRemoval(RemovalRange);
9604 }
9605 
9606 //===--- CHECK: Standard memory functions ---------------------------------===//
9607 
9608 /// Takes the expression passed to the size_t parameter of functions
9609 /// such as memcmp, strncat, etc and warns if it's a comparison.
9610 ///
9611 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9612 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9613                                            IdentifierInfo *FnName,
9614                                            SourceLocation FnLoc,
9615                                            SourceLocation RParenLoc) {
9616   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9617   if (!Size)
9618     return false;
9619 
9620   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9621   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9622     return false;
9623 
9624   SourceRange SizeRange = Size->getSourceRange();
9625   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9626       << SizeRange << FnName;
9627   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9628       << FnName
9629       << FixItHint::CreateInsertion(
9630              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9631       << FixItHint::CreateRemoval(RParenLoc);
9632   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9633       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9634       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9635                                     ")");
9636 
9637   return true;
9638 }
9639 
9640 /// Determine whether the given type is or contains a dynamic class type
9641 /// (e.g., whether it has a vtable).
9642 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9643                                                      bool &IsContained) {
9644   // Look through array types while ignoring qualifiers.
9645   const Type *Ty = T->getBaseElementTypeUnsafe();
9646   IsContained = false;
9647 
9648   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9649   RD = RD ? RD->getDefinition() : nullptr;
9650   if (!RD || RD->isInvalidDecl())
9651     return nullptr;
9652 
9653   if (RD->isDynamicClass())
9654     return RD;
9655 
9656   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9657   // It's impossible for a class to transitively contain itself by value, so
9658   // infinite recursion is impossible.
9659   for (auto *FD : RD->fields()) {
9660     bool SubContained;
9661     if (const CXXRecordDecl *ContainedRD =
9662             getContainedDynamicClass(FD->getType(), SubContained)) {
9663       IsContained = true;
9664       return ContainedRD;
9665     }
9666   }
9667 
9668   return nullptr;
9669 }
9670 
9671 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9672   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9673     if (Unary->getKind() == UETT_SizeOf)
9674       return Unary;
9675   return nullptr;
9676 }
9677 
9678 /// If E is a sizeof expression, returns its argument expression,
9679 /// otherwise returns NULL.
9680 static const Expr *getSizeOfExprArg(const Expr *E) {
9681   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9682     if (!SizeOf->isArgumentType())
9683       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9684   return nullptr;
9685 }
9686 
9687 /// If E is a sizeof expression, returns its argument type.
9688 static QualType getSizeOfArgType(const Expr *E) {
9689   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9690     return SizeOf->getTypeOfArgument();
9691   return QualType();
9692 }
9693 
9694 namespace {
9695 
9696 struct SearchNonTrivialToInitializeField
9697     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9698   using Super =
9699       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9700 
9701   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9702 
9703   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9704                      SourceLocation SL) {
9705     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9706       asDerived().visitArray(PDIK, AT, SL);
9707       return;
9708     }
9709 
9710     Super::visitWithKind(PDIK, FT, SL);
9711   }
9712 
9713   void visitARCStrong(QualType FT, SourceLocation SL) {
9714     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9715   }
9716   void visitARCWeak(QualType FT, SourceLocation SL) {
9717     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9718   }
9719   void visitStruct(QualType FT, SourceLocation SL) {
9720     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9721       visit(FD->getType(), FD->getLocation());
9722   }
9723   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9724                   const ArrayType *AT, SourceLocation SL) {
9725     visit(getContext().getBaseElementType(AT), SL);
9726   }
9727   void visitTrivial(QualType FT, SourceLocation SL) {}
9728 
9729   static void diag(QualType RT, const Expr *E, Sema &S) {
9730     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9731   }
9732 
9733   ASTContext &getContext() { return S.getASTContext(); }
9734 
9735   const Expr *E;
9736   Sema &S;
9737 };
9738 
9739 struct SearchNonTrivialToCopyField
9740     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9741   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9742 
9743   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9744 
9745   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9746                      SourceLocation SL) {
9747     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9748       asDerived().visitArray(PCK, AT, SL);
9749       return;
9750     }
9751 
9752     Super::visitWithKind(PCK, FT, SL);
9753   }
9754 
9755   void visitARCStrong(QualType FT, SourceLocation SL) {
9756     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9757   }
9758   void visitARCWeak(QualType FT, SourceLocation SL) {
9759     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9760   }
9761   void visitStruct(QualType FT, SourceLocation SL) {
9762     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9763       visit(FD->getType(), FD->getLocation());
9764   }
9765   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9766                   SourceLocation SL) {
9767     visit(getContext().getBaseElementType(AT), SL);
9768   }
9769   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9770                 SourceLocation SL) {}
9771   void visitTrivial(QualType FT, SourceLocation SL) {}
9772   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9773 
9774   static void diag(QualType RT, const Expr *E, Sema &S) {
9775     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9776   }
9777 
9778   ASTContext &getContext() { return S.getASTContext(); }
9779 
9780   const Expr *E;
9781   Sema &S;
9782 };
9783 
9784 }
9785 
9786 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9787 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9788   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9789 
9790   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9791     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9792       return false;
9793 
9794     return doesExprLikelyComputeSize(BO->getLHS()) ||
9795            doesExprLikelyComputeSize(BO->getRHS());
9796   }
9797 
9798   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9799 }
9800 
9801 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9802 ///
9803 /// \code
9804 ///   #define MACRO 0
9805 ///   foo(MACRO);
9806 ///   foo(0);
9807 /// \endcode
9808 ///
9809 /// This should return true for the first call to foo, but not for the second
9810 /// (regardless of whether foo is a macro or function).
9811 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9812                                         SourceLocation CallLoc,
9813                                         SourceLocation ArgLoc) {
9814   if (!CallLoc.isMacroID())
9815     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9816 
9817   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9818          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9819 }
9820 
9821 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9822 /// last two arguments transposed.
9823 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9824   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9825     return;
9826 
9827   const Expr *SizeArg =
9828     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9829 
9830   auto isLiteralZero = [](const Expr *E) {
9831     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9832   };
9833 
9834   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9835   SourceLocation CallLoc = Call->getRParenLoc();
9836   SourceManager &SM = S.getSourceManager();
9837   if (isLiteralZero(SizeArg) &&
9838       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9839 
9840     SourceLocation DiagLoc = SizeArg->getExprLoc();
9841 
9842     // Some platforms #define bzero to __builtin_memset. See if this is the
9843     // case, and if so, emit a better diagnostic.
9844     if (BId == Builtin::BIbzero ||
9845         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9846                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9847       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9848       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9849     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9850       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9851       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9852     }
9853     return;
9854   }
9855 
9856   // If the second argument to a memset is a sizeof expression and the third
9857   // isn't, this is also likely an error. This should catch
9858   // 'memset(buf, sizeof(buf), 0xff)'.
9859   if (BId == Builtin::BImemset &&
9860       doesExprLikelyComputeSize(Call->getArg(1)) &&
9861       !doesExprLikelyComputeSize(Call->getArg(2))) {
9862     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9863     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9864     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9865     return;
9866   }
9867 }
9868 
9869 /// Check for dangerous or invalid arguments to memset().
9870 ///
9871 /// This issues warnings on known problematic, dangerous or unspecified
9872 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9873 /// function calls.
9874 ///
9875 /// \param Call The call expression to diagnose.
9876 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9877                                    unsigned BId,
9878                                    IdentifierInfo *FnName) {
9879   assert(BId != 0);
9880 
9881   // It is possible to have a non-standard definition of memset.  Validate
9882   // we have enough arguments, and if not, abort further checking.
9883   unsigned ExpectedNumArgs =
9884       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9885   if (Call->getNumArgs() < ExpectedNumArgs)
9886     return;
9887 
9888   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9889                       BId == Builtin::BIstrndup ? 1 : 2);
9890   unsigned LenArg =
9891       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9892   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9893 
9894   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9895                                      Call->getBeginLoc(), Call->getRParenLoc()))
9896     return;
9897 
9898   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9899   CheckMemaccessSize(*this, BId, Call);
9900 
9901   // We have special checking when the length is a sizeof expression.
9902   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9903   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9904   llvm::FoldingSetNodeID SizeOfArgID;
9905 
9906   // Although widely used, 'bzero' is not a standard function. Be more strict
9907   // with the argument types before allowing diagnostics and only allow the
9908   // form bzero(ptr, sizeof(...)).
9909   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9910   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9911     return;
9912 
9913   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9914     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9915     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9916 
9917     QualType DestTy = Dest->getType();
9918     QualType PointeeTy;
9919     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9920       PointeeTy = DestPtrTy->getPointeeType();
9921 
9922       // Never warn about void type pointers. This can be used to suppress
9923       // false positives.
9924       if (PointeeTy->isVoidType())
9925         continue;
9926 
9927       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9928       // actually comparing the expressions for equality. Because computing the
9929       // expression IDs can be expensive, we only do this if the diagnostic is
9930       // enabled.
9931       if (SizeOfArg &&
9932           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9933                            SizeOfArg->getExprLoc())) {
9934         // We only compute IDs for expressions if the warning is enabled, and
9935         // cache the sizeof arg's ID.
9936         if (SizeOfArgID == llvm::FoldingSetNodeID())
9937           SizeOfArg->Profile(SizeOfArgID, Context, true);
9938         llvm::FoldingSetNodeID DestID;
9939         Dest->Profile(DestID, Context, true);
9940         if (DestID == SizeOfArgID) {
9941           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9942           //       over sizeof(src) as well.
9943           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9944           StringRef ReadableName = FnName->getName();
9945 
9946           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9947             if (UnaryOp->getOpcode() == UO_AddrOf)
9948               ActionIdx = 1; // If its an address-of operator, just remove it.
9949           if (!PointeeTy->isIncompleteType() &&
9950               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9951             ActionIdx = 2; // If the pointee's size is sizeof(char),
9952                            // suggest an explicit length.
9953 
9954           // If the function is defined as a builtin macro, do not show macro
9955           // expansion.
9956           SourceLocation SL = SizeOfArg->getExprLoc();
9957           SourceRange DSR = Dest->getSourceRange();
9958           SourceRange SSR = SizeOfArg->getSourceRange();
9959           SourceManager &SM = getSourceManager();
9960 
9961           if (SM.isMacroArgExpansion(SL)) {
9962             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9963             SL = SM.getSpellingLoc(SL);
9964             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9965                              SM.getSpellingLoc(DSR.getEnd()));
9966             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9967                              SM.getSpellingLoc(SSR.getEnd()));
9968           }
9969 
9970           DiagRuntimeBehavior(SL, SizeOfArg,
9971                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9972                                 << ReadableName
9973                                 << PointeeTy
9974                                 << DestTy
9975                                 << DSR
9976                                 << SSR);
9977           DiagRuntimeBehavior(SL, SizeOfArg,
9978                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9979                                 << ActionIdx
9980                                 << SSR);
9981 
9982           break;
9983         }
9984       }
9985 
9986       // Also check for cases where the sizeof argument is the exact same
9987       // type as the memory argument, and where it points to a user-defined
9988       // record type.
9989       if (SizeOfArgTy != QualType()) {
9990         if (PointeeTy->isRecordType() &&
9991             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9992           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9993                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9994                                 << FnName << SizeOfArgTy << ArgIdx
9995                                 << PointeeTy << Dest->getSourceRange()
9996                                 << LenExpr->getSourceRange());
9997           break;
9998         }
9999       }
10000     } else if (DestTy->isArrayType()) {
10001       PointeeTy = DestTy;
10002     }
10003 
10004     if (PointeeTy == QualType())
10005       continue;
10006 
10007     // Always complain about dynamic classes.
10008     bool IsContained;
10009     if (const CXXRecordDecl *ContainedRD =
10010             getContainedDynamicClass(PointeeTy, IsContained)) {
10011 
10012       unsigned OperationType = 0;
10013       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10014       // "overwritten" if we're warning about the destination for any call
10015       // but memcmp; otherwise a verb appropriate to the call.
10016       if (ArgIdx != 0 || IsCmp) {
10017         if (BId == Builtin::BImemcpy)
10018           OperationType = 1;
10019         else if(BId == Builtin::BImemmove)
10020           OperationType = 2;
10021         else if (IsCmp)
10022           OperationType = 3;
10023       }
10024 
10025       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10026                           PDiag(diag::warn_dyn_class_memaccess)
10027                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10028                               << IsContained << ContainedRD << OperationType
10029                               << Call->getCallee()->getSourceRange());
10030     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10031              BId != Builtin::BImemset)
10032       DiagRuntimeBehavior(
10033         Dest->getExprLoc(), Dest,
10034         PDiag(diag::warn_arc_object_memaccess)
10035           << ArgIdx << FnName << PointeeTy
10036           << Call->getCallee()->getSourceRange());
10037     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10038       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10039           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10040         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10041                             PDiag(diag::warn_cstruct_memaccess)
10042                                 << ArgIdx << FnName << PointeeTy << 0);
10043         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10044       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10045                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10046         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10047                             PDiag(diag::warn_cstruct_memaccess)
10048                                 << ArgIdx << FnName << PointeeTy << 1);
10049         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10050       } else {
10051         continue;
10052       }
10053     } else
10054       continue;
10055 
10056     DiagRuntimeBehavior(
10057       Dest->getExprLoc(), Dest,
10058       PDiag(diag::note_bad_memaccess_silence)
10059         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10060     break;
10061   }
10062 }
10063 
10064 // A little helper routine: ignore addition and subtraction of integer literals.
10065 // This intentionally does not ignore all integer constant expressions because
10066 // we don't want to remove sizeof().
10067 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10068   Ex = Ex->IgnoreParenCasts();
10069 
10070   while (true) {
10071     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10072     if (!BO || !BO->isAdditiveOp())
10073       break;
10074 
10075     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10076     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10077 
10078     if (isa<IntegerLiteral>(RHS))
10079       Ex = LHS;
10080     else if (isa<IntegerLiteral>(LHS))
10081       Ex = RHS;
10082     else
10083       break;
10084   }
10085 
10086   return Ex;
10087 }
10088 
10089 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10090                                                       ASTContext &Context) {
10091   // Only handle constant-sized or VLAs, but not flexible members.
10092   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10093     // Only issue the FIXIT for arrays of size > 1.
10094     if (CAT->getSize().getSExtValue() <= 1)
10095       return false;
10096   } else if (!Ty->isVariableArrayType()) {
10097     return false;
10098   }
10099   return true;
10100 }
10101 
10102 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10103 // be the size of the source, instead of the destination.
10104 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10105                                     IdentifierInfo *FnName) {
10106 
10107   // Don't crash if the user has the wrong number of arguments
10108   unsigned NumArgs = Call->getNumArgs();
10109   if ((NumArgs != 3) && (NumArgs != 4))
10110     return;
10111 
10112   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10113   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10114   const Expr *CompareWithSrc = nullptr;
10115 
10116   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10117                                      Call->getBeginLoc(), Call->getRParenLoc()))
10118     return;
10119 
10120   // Look for 'strlcpy(dst, x, sizeof(x))'
10121   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10122     CompareWithSrc = Ex;
10123   else {
10124     // Look for 'strlcpy(dst, x, strlen(x))'
10125     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10126       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10127           SizeCall->getNumArgs() == 1)
10128         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10129     }
10130   }
10131 
10132   if (!CompareWithSrc)
10133     return;
10134 
10135   // Determine if the argument to sizeof/strlen is equal to the source
10136   // argument.  In principle there's all kinds of things you could do
10137   // here, for instance creating an == expression and evaluating it with
10138   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10139   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10140   if (!SrcArgDRE)
10141     return;
10142 
10143   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10144   if (!CompareWithSrcDRE ||
10145       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10146     return;
10147 
10148   const Expr *OriginalSizeArg = Call->getArg(2);
10149   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10150       << OriginalSizeArg->getSourceRange() << FnName;
10151 
10152   // Output a FIXIT hint if the destination is an array (rather than a
10153   // pointer to an array).  This could be enhanced to handle some
10154   // pointers if we know the actual size, like if DstArg is 'array+2'
10155   // we could say 'sizeof(array)-2'.
10156   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10157   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10158     return;
10159 
10160   SmallString<128> sizeString;
10161   llvm::raw_svector_ostream OS(sizeString);
10162   OS << "sizeof(";
10163   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10164   OS << ")";
10165 
10166   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10167       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10168                                       OS.str());
10169 }
10170 
10171 /// Check if two expressions refer to the same declaration.
10172 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10173   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10174     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10175       return D1->getDecl() == D2->getDecl();
10176   return false;
10177 }
10178 
10179 static const Expr *getStrlenExprArg(const Expr *E) {
10180   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10181     const FunctionDecl *FD = CE->getDirectCallee();
10182     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10183       return nullptr;
10184     return CE->getArg(0)->IgnoreParenCasts();
10185   }
10186   return nullptr;
10187 }
10188 
10189 // Warn on anti-patterns as the 'size' argument to strncat.
10190 // The correct size argument should look like following:
10191 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10192 void Sema::CheckStrncatArguments(const CallExpr *CE,
10193                                  IdentifierInfo *FnName) {
10194   // Don't crash if the user has the wrong number of arguments.
10195   if (CE->getNumArgs() < 3)
10196     return;
10197   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10198   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10199   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10200 
10201   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10202                                      CE->getRParenLoc()))
10203     return;
10204 
10205   // Identify common expressions, which are wrongly used as the size argument
10206   // to strncat and may lead to buffer overflows.
10207   unsigned PatternType = 0;
10208   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10209     // - sizeof(dst)
10210     if (referToTheSameDecl(SizeOfArg, DstArg))
10211       PatternType = 1;
10212     // - sizeof(src)
10213     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10214       PatternType = 2;
10215   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10216     if (BE->getOpcode() == BO_Sub) {
10217       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10218       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10219       // - sizeof(dst) - strlen(dst)
10220       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10221           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10222         PatternType = 1;
10223       // - sizeof(src) - (anything)
10224       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10225         PatternType = 2;
10226     }
10227   }
10228 
10229   if (PatternType == 0)
10230     return;
10231 
10232   // Generate the diagnostic.
10233   SourceLocation SL = LenArg->getBeginLoc();
10234   SourceRange SR = LenArg->getSourceRange();
10235   SourceManager &SM = getSourceManager();
10236 
10237   // If the function is defined as a builtin macro, do not show macro expansion.
10238   if (SM.isMacroArgExpansion(SL)) {
10239     SL = SM.getSpellingLoc(SL);
10240     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10241                      SM.getSpellingLoc(SR.getEnd()));
10242   }
10243 
10244   // Check if the destination is an array (rather than a pointer to an array).
10245   QualType DstTy = DstArg->getType();
10246   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10247                                                                     Context);
10248   if (!isKnownSizeArray) {
10249     if (PatternType == 1)
10250       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10251     else
10252       Diag(SL, diag::warn_strncat_src_size) << SR;
10253     return;
10254   }
10255 
10256   if (PatternType == 1)
10257     Diag(SL, diag::warn_strncat_large_size) << SR;
10258   else
10259     Diag(SL, diag::warn_strncat_src_size) << SR;
10260 
10261   SmallString<128> sizeString;
10262   llvm::raw_svector_ostream OS(sizeString);
10263   OS << "sizeof(";
10264   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10265   OS << ") - ";
10266   OS << "strlen(";
10267   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10268   OS << ") - 1";
10269 
10270   Diag(SL, diag::note_strncat_wrong_size)
10271     << FixItHint::CreateReplacement(SR, OS.str());
10272 }
10273 
10274 namespace {
10275 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10276                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10277   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10278     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10279         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10280     return;
10281   }
10282 }
10283 
10284 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10285                                  const UnaryOperator *UnaryExpr) {
10286   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10287     const Decl *D = Lvalue->getDecl();
10288     if (isa<VarDecl, FunctionDecl>(D))
10289       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10290   }
10291 
10292   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10293     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10294                                       Lvalue->getMemberDecl());
10295 }
10296 
10297 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10298                             const UnaryOperator *UnaryExpr) {
10299   const auto *Lambda = dyn_cast<LambdaExpr>(
10300       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10301   if (!Lambda)
10302     return;
10303 
10304   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10305       << CalleeName << 2 /*object: lambda expression*/;
10306 }
10307 
10308 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10309                                   const DeclRefExpr *Lvalue) {
10310   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10311   if (Var == nullptr)
10312     return;
10313 
10314   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10315       << CalleeName << 0 /*object: */ << Var;
10316 }
10317 
10318 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10319                             const CastExpr *Cast) {
10320   SmallString<128> SizeString;
10321   llvm::raw_svector_ostream OS(SizeString);
10322   switch (Cast->getCastKind()) {
10323   case clang::CK_BitCast:
10324     if (!Cast->getSubExpr()->getType()->isFunctionPointerType())
10325       return;
10326     LLVM_FALLTHROUGH;
10327   case clang::CK_IntegralToPointer:
10328   case clang::CK_FunctionToPointerDecay:
10329     OS << '\'';
10330     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10331     OS << '\'';
10332     break;
10333   default:
10334     return;
10335   }
10336 
10337   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10338       << CalleeName << 0 /*object: */ << OS.str();
10339 }
10340 } // namespace
10341 
10342 /// Alerts the user that they are attempting to free a non-malloc'd object.
10343 void Sema::CheckFreeArguments(const CallExpr *E) {
10344   const std::string CalleeName =
10345       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10346 
10347   { // Prefer something that doesn't involve a cast to make things simpler.
10348     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10349     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10350       switch (UnaryExpr->getOpcode()) {
10351       case UnaryOperator::Opcode::UO_AddrOf:
10352         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10353       case UnaryOperator::Opcode::UO_Plus:
10354         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10355       default:
10356         break;
10357       }
10358 
10359     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10360       if (Lvalue->getType()->isArrayType())
10361         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10362 
10363     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10364       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10365           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10366       return;
10367     }
10368 
10369     if (isa<BlockExpr>(Arg)) {
10370       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10371           << CalleeName << 1 /*object: block*/;
10372       return;
10373     }
10374   }
10375   // Maybe the cast was important, check after the other cases.
10376   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10377     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10378 }
10379 
10380 void
10381 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10382                          SourceLocation ReturnLoc,
10383                          bool isObjCMethod,
10384                          const AttrVec *Attrs,
10385                          const FunctionDecl *FD) {
10386   // Check if the return value is null but should not be.
10387   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10388        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10389       CheckNonNullExpr(*this, RetValExp))
10390     Diag(ReturnLoc, diag::warn_null_ret)
10391       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10392 
10393   // C++11 [basic.stc.dynamic.allocation]p4:
10394   //   If an allocation function declared with a non-throwing
10395   //   exception-specification fails to allocate storage, it shall return
10396   //   a null pointer. Any other allocation function that fails to allocate
10397   //   storage shall indicate failure only by throwing an exception [...]
10398   if (FD) {
10399     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10400     if (Op == OO_New || Op == OO_Array_New) {
10401       const FunctionProtoType *Proto
10402         = FD->getType()->castAs<FunctionProtoType>();
10403       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10404           CheckNonNullExpr(*this, RetValExp))
10405         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10406           << FD << getLangOpts().CPlusPlus11;
10407     }
10408   }
10409 
10410   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10411   // here prevent the user from using a PPC MMA type as trailing return type.
10412   if (Context.getTargetInfo().getTriple().isPPC64())
10413     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10414 }
10415 
10416 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10417 
10418 /// Check for comparisons of floating point operands using != and ==.
10419 /// Issue a warning if these are no self-comparisons, as they are not likely
10420 /// to do what the programmer intended.
10421 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10422   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10423   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10424 
10425   // Special case: check for x == x (which is OK).
10426   // Do not emit warnings for such cases.
10427   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10428     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10429       if (DRL->getDecl() == DRR->getDecl())
10430         return;
10431 
10432   // Special case: check for comparisons against literals that can be exactly
10433   //  represented by APFloat.  In such cases, do not emit a warning.  This
10434   //  is a heuristic: often comparison against such literals are used to
10435   //  detect if a value in a variable has not changed.  This clearly can
10436   //  lead to false negatives.
10437   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10438     if (FLL->isExact())
10439       return;
10440   } else
10441     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10442       if (FLR->isExact())
10443         return;
10444 
10445   // Check for comparisons with builtin types.
10446   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10447     if (CL->getBuiltinCallee())
10448       return;
10449 
10450   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10451     if (CR->getBuiltinCallee())
10452       return;
10453 
10454   // Emit the diagnostic.
10455   Diag(Loc, diag::warn_floatingpoint_eq)
10456     << LHS->getSourceRange() << RHS->getSourceRange();
10457 }
10458 
10459 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10460 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10461 
10462 namespace {
10463 
10464 /// Structure recording the 'active' range of an integer-valued
10465 /// expression.
10466 struct IntRange {
10467   /// The number of bits active in the int. Note that this includes exactly one
10468   /// sign bit if !NonNegative.
10469   unsigned Width;
10470 
10471   /// True if the int is known not to have negative values. If so, all leading
10472   /// bits before Width are known zero, otherwise they are known to be the
10473   /// same as the MSB within Width.
10474   bool NonNegative;
10475 
10476   IntRange(unsigned Width, bool NonNegative)
10477       : Width(Width), NonNegative(NonNegative) {}
10478 
10479   /// Number of bits excluding the sign bit.
10480   unsigned valueBits() const {
10481     return NonNegative ? Width : Width - 1;
10482   }
10483 
10484   /// Returns the range of the bool type.
10485   static IntRange forBoolType() {
10486     return IntRange(1, true);
10487   }
10488 
10489   /// Returns the range of an opaque value of the given integral type.
10490   static IntRange forValueOfType(ASTContext &C, QualType T) {
10491     return forValueOfCanonicalType(C,
10492                           T->getCanonicalTypeInternal().getTypePtr());
10493   }
10494 
10495   /// Returns the range of an opaque value of a canonical integral type.
10496   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10497     assert(T->isCanonicalUnqualified());
10498 
10499     if (const VectorType *VT = dyn_cast<VectorType>(T))
10500       T = VT->getElementType().getTypePtr();
10501     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10502       T = CT->getElementType().getTypePtr();
10503     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10504       T = AT->getValueType().getTypePtr();
10505 
10506     if (!C.getLangOpts().CPlusPlus) {
10507       // For enum types in C code, use the underlying datatype.
10508       if (const EnumType *ET = dyn_cast<EnumType>(T))
10509         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10510     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10511       // For enum types in C++, use the known bit width of the enumerators.
10512       EnumDecl *Enum = ET->getDecl();
10513       // In C++11, enums can have a fixed underlying type. Use this type to
10514       // compute the range.
10515       if (Enum->isFixed()) {
10516         return IntRange(C.getIntWidth(QualType(T, 0)),
10517                         !ET->isSignedIntegerOrEnumerationType());
10518       }
10519 
10520       unsigned NumPositive = Enum->getNumPositiveBits();
10521       unsigned NumNegative = Enum->getNumNegativeBits();
10522 
10523       if (NumNegative == 0)
10524         return IntRange(NumPositive, true/*NonNegative*/);
10525       else
10526         return IntRange(std::max(NumPositive + 1, NumNegative),
10527                         false/*NonNegative*/);
10528     }
10529 
10530     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10531       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10532 
10533     const BuiltinType *BT = cast<BuiltinType>(T);
10534     assert(BT->isInteger());
10535 
10536     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10537   }
10538 
10539   /// Returns the "target" range of a canonical integral type, i.e.
10540   /// the range of values expressible in the type.
10541   ///
10542   /// This matches forValueOfCanonicalType except that enums have the
10543   /// full range of their type, not the range of their enumerators.
10544   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10545     assert(T->isCanonicalUnqualified());
10546 
10547     if (const VectorType *VT = dyn_cast<VectorType>(T))
10548       T = VT->getElementType().getTypePtr();
10549     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10550       T = CT->getElementType().getTypePtr();
10551     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10552       T = AT->getValueType().getTypePtr();
10553     if (const EnumType *ET = dyn_cast<EnumType>(T))
10554       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10555 
10556     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10557       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10558 
10559     const BuiltinType *BT = cast<BuiltinType>(T);
10560     assert(BT->isInteger());
10561 
10562     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10563   }
10564 
10565   /// Returns the supremum of two ranges: i.e. their conservative merge.
10566   static IntRange join(IntRange L, IntRange R) {
10567     bool Unsigned = L.NonNegative && R.NonNegative;
10568     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10569                     L.NonNegative && R.NonNegative);
10570   }
10571 
10572   /// Return the range of a bitwise-AND of the two ranges.
10573   static IntRange bit_and(IntRange L, IntRange R) {
10574     unsigned Bits = std::max(L.Width, R.Width);
10575     bool NonNegative = false;
10576     if (L.NonNegative) {
10577       Bits = std::min(Bits, L.Width);
10578       NonNegative = true;
10579     }
10580     if (R.NonNegative) {
10581       Bits = std::min(Bits, R.Width);
10582       NonNegative = true;
10583     }
10584     return IntRange(Bits, NonNegative);
10585   }
10586 
10587   /// Return the range of a sum of the two ranges.
10588   static IntRange sum(IntRange L, IntRange R) {
10589     bool Unsigned = L.NonNegative && R.NonNegative;
10590     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10591                     Unsigned);
10592   }
10593 
10594   /// Return the range of a difference of the two ranges.
10595   static IntRange difference(IntRange L, IntRange R) {
10596     // We need a 1-bit-wider range if:
10597     //   1) LHS can be negative: least value can be reduced.
10598     //   2) RHS can be negative: greatest value can be increased.
10599     bool CanWiden = !L.NonNegative || !R.NonNegative;
10600     bool Unsigned = L.NonNegative && R.Width == 0;
10601     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10602                         !Unsigned,
10603                     Unsigned);
10604   }
10605 
10606   /// Return the range of a product of the two ranges.
10607   static IntRange product(IntRange L, IntRange R) {
10608     // If both LHS and RHS can be negative, we can form
10609     //   -2^L * -2^R = 2^(L + R)
10610     // which requires L + R + 1 value bits to represent.
10611     bool CanWiden = !L.NonNegative && !R.NonNegative;
10612     bool Unsigned = L.NonNegative && R.NonNegative;
10613     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10614                     Unsigned);
10615   }
10616 
10617   /// Return the range of a remainder operation between the two ranges.
10618   static IntRange rem(IntRange L, IntRange R) {
10619     // The result of a remainder can't be larger than the result of
10620     // either side. The sign of the result is the sign of the LHS.
10621     bool Unsigned = L.NonNegative;
10622     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10623                     Unsigned);
10624   }
10625 };
10626 
10627 } // namespace
10628 
10629 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10630                               unsigned MaxWidth) {
10631   if (value.isSigned() && value.isNegative())
10632     return IntRange(value.getMinSignedBits(), false);
10633 
10634   if (value.getBitWidth() > MaxWidth)
10635     value = value.trunc(MaxWidth);
10636 
10637   // isNonNegative() just checks the sign bit without considering
10638   // signedness.
10639   return IntRange(value.getActiveBits(), true);
10640 }
10641 
10642 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10643                               unsigned MaxWidth) {
10644   if (result.isInt())
10645     return GetValueRange(C, result.getInt(), MaxWidth);
10646 
10647   if (result.isVector()) {
10648     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10649     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10650       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10651       R = IntRange::join(R, El);
10652     }
10653     return R;
10654   }
10655 
10656   if (result.isComplexInt()) {
10657     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10658     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10659     return IntRange::join(R, I);
10660   }
10661 
10662   // This can happen with lossless casts to intptr_t of "based" lvalues.
10663   // Assume it might use arbitrary bits.
10664   // FIXME: The only reason we need to pass the type in here is to get
10665   // the sign right on this one case.  It would be nice if APValue
10666   // preserved this.
10667   assert(result.isLValue() || result.isAddrLabelDiff());
10668   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10669 }
10670 
10671 static QualType GetExprType(const Expr *E) {
10672   QualType Ty = E->getType();
10673   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10674     Ty = AtomicRHS->getValueType();
10675   return Ty;
10676 }
10677 
10678 /// Pseudo-evaluate the given integer expression, estimating the
10679 /// range of values it might take.
10680 ///
10681 /// \param MaxWidth The width to which the value will be truncated.
10682 /// \param Approximate If \c true, return a likely range for the result: in
10683 ///        particular, assume that aritmetic on narrower types doesn't leave
10684 ///        those types. If \c false, return a range including all possible
10685 ///        result values.
10686 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10687                              bool InConstantContext, bool Approximate) {
10688   E = E->IgnoreParens();
10689 
10690   // Try a full evaluation first.
10691   Expr::EvalResult result;
10692   if (E->EvaluateAsRValue(result, C, InConstantContext))
10693     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10694 
10695   // I think we only want to look through implicit casts here; if the
10696   // user has an explicit widening cast, we should treat the value as
10697   // being of the new, wider type.
10698   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10699     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10700       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10701                           Approximate);
10702 
10703     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10704 
10705     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10706                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10707 
10708     // Assume that non-integer casts can span the full range of the type.
10709     if (!isIntegerCast)
10710       return OutputTypeRange;
10711 
10712     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10713                                      std::min(MaxWidth, OutputTypeRange.Width),
10714                                      InConstantContext, Approximate);
10715 
10716     // Bail out if the subexpr's range is as wide as the cast type.
10717     if (SubRange.Width >= OutputTypeRange.Width)
10718       return OutputTypeRange;
10719 
10720     // Otherwise, we take the smaller width, and we're non-negative if
10721     // either the output type or the subexpr is.
10722     return IntRange(SubRange.Width,
10723                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10724   }
10725 
10726   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10727     // If we can fold the condition, just take that operand.
10728     bool CondResult;
10729     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10730       return GetExprRange(C,
10731                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10732                           MaxWidth, InConstantContext, Approximate);
10733 
10734     // Otherwise, conservatively merge.
10735     // GetExprRange requires an integer expression, but a throw expression
10736     // results in a void type.
10737     Expr *E = CO->getTrueExpr();
10738     IntRange L = E->getType()->isVoidType()
10739                      ? IntRange{0, true}
10740                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10741     E = CO->getFalseExpr();
10742     IntRange R = E->getType()->isVoidType()
10743                      ? IntRange{0, true}
10744                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10745     return IntRange::join(L, R);
10746   }
10747 
10748   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10749     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10750 
10751     switch (BO->getOpcode()) {
10752     case BO_Cmp:
10753       llvm_unreachable("builtin <=> should have class type");
10754 
10755     // Boolean-valued operations are single-bit and positive.
10756     case BO_LAnd:
10757     case BO_LOr:
10758     case BO_LT:
10759     case BO_GT:
10760     case BO_LE:
10761     case BO_GE:
10762     case BO_EQ:
10763     case BO_NE:
10764       return IntRange::forBoolType();
10765 
10766     // The type of the assignments is the type of the LHS, so the RHS
10767     // is not necessarily the same type.
10768     case BO_MulAssign:
10769     case BO_DivAssign:
10770     case BO_RemAssign:
10771     case BO_AddAssign:
10772     case BO_SubAssign:
10773     case BO_XorAssign:
10774     case BO_OrAssign:
10775       // TODO: bitfields?
10776       return IntRange::forValueOfType(C, GetExprType(E));
10777 
10778     // Simple assignments just pass through the RHS, which will have
10779     // been coerced to the LHS type.
10780     case BO_Assign:
10781       // TODO: bitfields?
10782       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10783                           Approximate);
10784 
10785     // Operations with opaque sources are black-listed.
10786     case BO_PtrMemD:
10787     case BO_PtrMemI:
10788       return IntRange::forValueOfType(C, GetExprType(E));
10789 
10790     // Bitwise-and uses the *infinum* of the two source ranges.
10791     case BO_And:
10792     case BO_AndAssign:
10793       Combine = IntRange::bit_and;
10794       break;
10795 
10796     // Left shift gets black-listed based on a judgement call.
10797     case BO_Shl:
10798       // ...except that we want to treat '1 << (blah)' as logically
10799       // positive.  It's an important idiom.
10800       if (IntegerLiteral *I
10801             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10802         if (I->getValue() == 1) {
10803           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10804           return IntRange(R.Width, /*NonNegative*/ true);
10805         }
10806       }
10807       LLVM_FALLTHROUGH;
10808 
10809     case BO_ShlAssign:
10810       return IntRange::forValueOfType(C, GetExprType(E));
10811 
10812     // Right shift by a constant can narrow its left argument.
10813     case BO_Shr:
10814     case BO_ShrAssign: {
10815       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
10816                                 Approximate);
10817 
10818       // If the shift amount is a positive constant, drop the width by
10819       // that much.
10820       if (Optional<llvm::APSInt> shift =
10821               BO->getRHS()->getIntegerConstantExpr(C)) {
10822         if (shift->isNonNegative()) {
10823           unsigned zext = shift->getZExtValue();
10824           if (zext >= L.Width)
10825             L.Width = (L.NonNegative ? 0 : 1);
10826           else
10827             L.Width -= zext;
10828         }
10829       }
10830 
10831       return L;
10832     }
10833 
10834     // Comma acts as its right operand.
10835     case BO_Comma:
10836       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10837                           Approximate);
10838 
10839     case BO_Add:
10840       if (!Approximate)
10841         Combine = IntRange::sum;
10842       break;
10843 
10844     case BO_Sub:
10845       if (BO->getLHS()->getType()->isPointerType())
10846         return IntRange::forValueOfType(C, GetExprType(E));
10847       if (!Approximate)
10848         Combine = IntRange::difference;
10849       break;
10850 
10851     case BO_Mul:
10852       if (!Approximate)
10853         Combine = IntRange::product;
10854       break;
10855 
10856     // The width of a division result is mostly determined by the size
10857     // of the LHS.
10858     case BO_Div: {
10859       // Don't 'pre-truncate' the operands.
10860       unsigned opWidth = C.getIntWidth(GetExprType(E));
10861       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
10862                                 Approximate);
10863 
10864       // If the divisor is constant, use that.
10865       if (Optional<llvm::APSInt> divisor =
10866               BO->getRHS()->getIntegerConstantExpr(C)) {
10867         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10868         if (log2 >= L.Width)
10869           L.Width = (L.NonNegative ? 0 : 1);
10870         else
10871           L.Width = std::min(L.Width - log2, MaxWidth);
10872         return L;
10873       }
10874 
10875       // Otherwise, just use the LHS's width.
10876       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
10877       // could be -1.
10878       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
10879                                 Approximate);
10880       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10881     }
10882 
10883     case BO_Rem:
10884       Combine = IntRange::rem;
10885       break;
10886 
10887     // The default behavior is okay for these.
10888     case BO_Xor:
10889     case BO_Or:
10890       break;
10891     }
10892 
10893     // Combine the two ranges, but limit the result to the type in which we
10894     // performed the computation.
10895     QualType T = GetExprType(E);
10896     unsigned opWidth = C.getIntWidth(T);
10897     IntRange L =
10898         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
10899     IntRange R =
10900         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
10901     IntRange C = Combine(L, R);
10902     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
10903     C.Width = std::min(C.Width, MaxWidth);
10904     return C;
10905   }
10906 
10907   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10908     switch (UO->getOpcode()) {
10909     // Boolean-valued operations are white-listed.
10910     case UO_LNot:
10911       return IntRange::forBoolType();
10912 
10913     // Operations with opaque sources are black-listed.
10914     case UO_Deref:
10915     case UO_AddrOf: // should be impossible
10916       return IntRange::forValueOfType(C, GetExprType(E));
10917 
10918     default:
10919       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
10920                           Approximate);
10921     }
10922   }
10923 
10924   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10925     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
10926                         Approximate);
10927 
10928   if (const auto *BitField = E->getSourceBitField())
10929     return IntRange(BitField->getBitWidthValue(C),
10930                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10931 
10932   return IntRange::forValueOfType(C, GetExprType(E));
10933 }
10934 
10935 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10936                              bool InConstantContext, bool Approximate) {
10937   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
10938                       Approximate);
10939 }
10940 
10941 /// Checks whether the given value, which currently has the given
10942 /// source semantics, has the same value when coerced through the
10943 /// target semantics.
10944 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10945                                  const llvm::fltSemantics &Src,
10946                                  const llvm::fltSemantics &Tgt) {
10947   llvm::APFloat truncated = value;
10948 
10949   bool ignored;
10950   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10951   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10952 
10953   return truncated.bitwiseIsEqual(value);
10954 }
10955 
10956 /// Checks whether the given value, which currently has the given
10957 /// source semantics, has the same value when coerced through the
10958 /// target semantics.
10959 ///
10960 /// The value might be a vector of floats (or a complex number).
10961 static bool IsSameFloatAfterCast(const APValue &value,
10962                                  const llvm::fltSemantics &Src,
10963                                  const llvm::fltSemantics &Tgt) {
10964   if (value.isFloat())
10965     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10966 
10967   if (value.isVector()) {
10968     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10969       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10970         return false;
10971     return true;
10972   }
10973 
10974   assert(value.isComplexFloat());
10975   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10976           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10977 }
10978 
10979 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10980                                        bool IsListInit = false);
10981 
10982 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10983   // Suppress cases where we are comparing against an enum constant.
10984   if (const DeclRefExpr *DR =
10985       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10986     if (isa<EnumConstantDecl>(DR->getDecl()))
10987       return true;
10988 
10989   // Suppress cases where the value is expanded from a macro, unless that macro
10990   // is how a language represents a boolean literal. This is the case in both C
10991   // and Objective-C.
10992   SourceLocation BeginLoc = E->getBeginLoc();
10993   if (BeginLoc.isMacroID()) {
10994     StringRef MacroName = Lexer::getImmediateMacroName(
10995         BeginLoc, S.getSourceManager(), S.getLangOpts());
10996     return MacroName != "YES" && MacroName != "NO" &&
10997            MacroName != "true" && MacroName != "false";
10998   }
10999 
11000   return false;
11001 }
11002 
11003 static bool isKnownToHaveUnsignedValue(Expr *E) {
11004   return E->getType()->isIntegerType() &&
11005          (!E->getType()->isSignedIntegerType() ||
11006           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11007 }
11008 
11009 namespace {
11010 /// The promoted range of values of a type. In general this has the
11011 /// following structure:
11012 ///
11013 ///     |-----------| . . . |-----------|
11014 ///     ^           ^       ^           ^
11015 ///    Min       HoleMin  HoleMax      Max
11016 ///
11017 /// ... where there is only a hole if a signed type is promoted to unsigned
11018 /// (in which case Min and Max are the smallest and largest representable
11019 /// values).
11020 struct PromotedRange {
11021   // Min, or HoleMax if there is a hole.
11022   llvm::APSInt PromotedMin;
11023   // Max, or HoleMin if there is a hole.
11024   llvm::APSInt PromotedMax;
11025 
11026   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11027     if (R.Width == 0)
11028       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11029     else if (R.Width >= BitWidth && !Unsigned) {
11030       // Promotion made the type *narrower*. This happens when promoting
11031       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11032       // Treat all values of 'signed int' as being in range for now.
11033       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11034       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11035     } else {
11036       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11037                         .extOrTrunc(BitWidth);
11038       PromotedMin.setIsUnsigned(Unsigned);
11039 
11040       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11041                         .extOrTrunc(BitWidth);
11042       PromotedMax.setIsUnsigned(Unsigned);
11043     }
11044   }
11045 
11046   // Determine whether this range is contiguous (has no hole).
11047   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11048 
11049   // Where a constant value is within the range.
11050   enum ComparisonResult {
11051     LT = 0x1,
11052     LE = 0x2,
11053     GT = 0x4,
11054     GE = 0x8,
11055     EQ = 0x10,
11056     NE = 0x20,
11057     InRangeFlag = 0x40,
11058 
11059     Less = LE | LT | NE,
11060     Min = LE | InRangeFlag,
11061     InRange = InRangeFlag,
11062     Max = GE | InRangeFlag,
11063     Greater = GE | GT | NE,
11064 
11065     OnlyValue = LE | GE | EQ | InRangeFlag,
11066     InHole = NE
11067   };
11068 
11069   ComparisonResult compare(const llvm::APSInt &Value) const {
11070     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11071            Value.isUnsigned() == PromotedMin.isUnsigned());
11072     if (!isContiguous()) {
11073       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11074       if (Value.isMinValue()) return Min;
11075       if (Value.isMaxValue()) return Max;
11076       if (Value >= PromotedMin) return InRange;
11077       if (Value <= PromotedMax) return InRange;
11078       return InHole;
11079     }
11080 
11081     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11082     case -1: return Less;
11083     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11084     case 1:
11085       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11086       case -1: return InRange;
11087       case 0: return Max;
11088       case 1: return Greater;
11089       }
11090     }
11091 
11092     llvm_unreachable("impossible compare result");
11093   }
11094 
11095   static llvm::Optional<StringRef>
11096   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11097     if (Op == BO_Cmp) {
11098       ComparisonResult LTFlag = LT, GTFlag = GT;
11099       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11100 
11101       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11102       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11103       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11104       return llvm::None;
11105     }
11106 
11107     ComparisonResult TrueFlag, FalseFlag;
11108     if (Op == BO_EQ) {
11109       TrueFlag = EQ;
11110       FalseFlag = NE;
11111     } else if (Op == BO_NE) {
11112       TrueFlag = NE;
11113       FalseFlag = EQ;
11114     } else {
11115       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11116         TrueFlag = LT;
11117         FalseFlag = GE;
11118       } else {
11119         TrueFlag = GT;
11120         FalseFlag = LE;
11121       }
11122       if (Op == BO_GE || Op == BO_LE)
11123         std::swap(TrueFlag, FalseFlag);
11124     }
11125     if (R & TrueFlag)
11126       return StringRef("true");
11127     if (R & FalseFlag)
11128       return StringRef("false");
11129     return llvm::None;
11130   }
11131 };
11132 }
11133 
11134 static bool HasEnumType(Expr *E) {
11135   // Strip off implicit integral promotions.
11136   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11137     if (ICE->getCastKind() != CK_IntegralCast &&
11138         ICE->getCastKind() != CK_NoOp)
11139       break;
11140     E = ICE->getSubExpr();
11141   }
11142 
11143   return E->getType()->isEnumeralType();
11144 }
11145 
11146 static int classifyConstantValue(Expr *Constant) {
11147   // The values of this enumeration are used in the diagnostics
11148   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11149   enum ConstantValueKind {
11150     Miscellaneous = 0,
11151     LiteralTrue,
11152     LiteralFalse
11153   };
11154   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11155     return BL->getValue() ? ConstantValueKind::LiteralTrue
11156                           : ConstantValueKind::LiteralFalse;
11157   return ConstantValueKind::Miscellaneous;
11158 }
11159 
11160 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11161                                         Expr *Constant, Expr *Other,
11162                                         const llvm::APSInt &Value,
11163                                         bool RhsConstant) {
11164   if (S.inTemplateInstantiation())
11165     return false;
11166 
11167   Expr *OriginalOther = Other;
11168 
11169   Constant = Constant->IgnoreParenImpCasts();
11170   Other = Other->IgnoreParenImpCasts();
11171 
11172   // Suppress warnings on tautological comparisons between values of the same
11173   // enumeration type. There are only two ways we could warn on this:
11174   //  - If the constant is outside the range of representable values of
11175   //    the enumeration. In such a case, we should warn about the cast
11176   //    to enumeration type, not about the comparison.
11177   //  - If the constant is the maximum / minimum in-range value. For an
11178   //    enumeratin type, such comparisons can be meaningful and useful.
11179   if (Constant->getType()->isEnumeralType() &&
11180       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11181     return false;
11182 
11183   IntRange OtherValueRange = GetExprRange(
11184       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11185 
11186   QualType OtherT = Other->getType();
11187   if (const auto *AT = OtherT->getAs<AtomicType>())
11188     OtherT = AT->getValueType();
11189   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11190 
11191   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11192   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11193   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11194                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11195                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11196 
11197   // Whether we're treating Other as being a bool because of the form of
11198   // expression despite it having another type (typically 'int' in C).
11199   bool OtherIsBooleanDespiteType =
11200       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11201   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11202     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11203 
11204   // Check if all values in the range of possible values of this expression
11205   // lead to the same comparison outcome.
11206   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11207                                         Value.isUnsigned());
11208   auto Cmp = OtherPromotedValueRange.compare(Value);
11209   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11210   if (!Result)
11211     return false;
11212 
11213   // Also consider the range determined by the type alone. This allows us to
11214   // classify the warning under the proper diagnostic group.
11215   bool TautologicalTypeCompare = false;
11216   {
11217     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11218                                          Value.isUnsigned());
11219     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11220     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11221                                                        RhsConstant)) {
11222       TautologicalTypeCompare = true;
11223       Cmp = TypeCmp;
11224       Result = TypeResult;
11225     }
11226   }
11227 
11228   // Don't warn if the non-constant operand actually always evaluates to the
11229   // same value.
11230   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11231     return false;
11232 
11233   // Suppress the diagnostic for an in-range comparison if the constant comes
11234   // from a macro or enumerator. We don't want to diagnose
11235   //
11236   //   some_long_value <= INT_MAX
11237   //
11238   // when sizeof(int) == sizeof(long).
11239   bool InRange = Cmp & PromotedRange::InRangeFlag;
11240   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11241     return false;
11242 
11243   // A comparison of an unsigned bit-field against 0 is really a type problem,
11244   // even though at the type level the bit-field might promote to 'signed int'.
11245   if (Other->refersToBitField() && InRange && Value == 0 &&
11246       Other->getType()->isUnsignedIntegerOrEnumerationType())
11247     TautologicalTypeCompare = true;
11248 
11249   // If this is a comparison to an enum constant, include that
11250   // constant in the diagnostic.
11251   const EnumConstantDecl *ED = nullptr;
11252   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11253     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11254 
11255   // Should be enough for uint128 (39 decimal digits)
11256   SmallString<64> PrettySourceValue;
11257   llvm::raw_svector_ostream OS(PrettySourceValue);
11258   if (ED) {
11259     OS << '\'' << *ED << "' (" << Value << ")";
11260   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11261                Constant->IgnoreParenImpCasts())) {
11262     OS << (BL->getValue() ? "YES" : "NO");
11263   } else {
11264     OS << Value;
11265   }
11266 
11267   if (!TautologicalTypeCompare) {
11268     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11269         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11270         << E->getOpcodeStr() << OS.str() << *Result
11271         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11272     return true;
11273   }
11274 
11275   if (IsObjCSignedCharBool) {
11276     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11277                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11278                               << OS.str() << *Result);
11279     return true;
11280   }
11281 
11282   // FIXME: We use a somewhat different formatting for the in-range cases and
11283   // cases involving boolean values for historical reasons. We should pick a
11284   // consistent way of presenting these diagnostics.
11285   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11286 
11287     S.DiagRuntimeBehavior(
11288         E->getOperatorLoc(), E,
11289         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11290                          : diag::warn_tautological_bool_compare)
11291             << OS.str() << classifyConstantValue(Constant) << OtherT
11292             << OtherIsBooleanDespiteType << *Result
11293             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11294   } else {
11295     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11296                         ? (HasEnumType(OriginalOther)
11297                                ? diag::warn_unsigned_enum_always_true_comparison
11298                                : diag::warn_unsigned_always_true_comparison)
11299                         : diag::warn_tautological_constant_compare;
11300 
11301     S.Diag(E->getOperatorLoc(), Diag)
11302         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11303         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11304   }
11305 
11306   return true;
11307 }
11308 
11309 /// Analyze the operands of the given comparison.  Implements the
11310 /// fallback case from AnalyzeComparison.
11311 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11312   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11313   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11314 }
11315 
11316 /// Implements -Wsign-compare.
11317 ///
11318 /// \param E the binary operator to check for warnings
11319 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11320   // The type the comparison is being performed in.
11321   QualType T = E->getLHS()->getType();
11322 
11323   // Only analyze comparison operators where both sides have been converted to
11324   // the same type.
11325   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11326     return AnalyzeImpConvsInComparison(S, E);
11327 
11328   // Don't analyze value-dependent comparisons directly.
11329   if (E->isValueDependent())
11330     return AnalyzeImpConvsInComparison(S, E);
11331 
11332   Expr *LHS = E->getLHS();
11333   Expr *RHS = E->getRHS();
11334 
11335   if (T->isIntegralType(S.Context)) {
11336     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11337     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11338 
11339     // We don't care about expressions whose result is a constant.
11340     if (RHSValue && LHSValue)
11341       return AnalyzeImpConvsInComparison(S, E);
11342 
11343     // We only care about expressions where just one side is literal
11344     if ((bool)RHSValue ^ (bool)LHSValue) {
11345       // Is the constant on the RHS or LHS?
11346       const bool RhsConstant = (bool)RHSValue;
11347       Expr *Const = RhsConstant ? RHS : LHS;
11348       Expr *Other = RhsConstant ? LHS : RHS;
11349       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11350 
11351       // Check whether an integer constant comparison results in a value
11352       // of 'true' or 'false'.
11353       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11354         return AnalyzeImpConvsInComparison(S, E);
11355     }
11356   }
11357 
11358   if (!T->hasUnsignedIntegerRepresentation()) {
11359     // We don't do anything special if this isn't an unsigned integral
11360     // comparison:  we're only interested in integral comparisons, and
11361     // signed comparisons only happen in cases we don't care to warn about.
11362     return AnalyzeImpConvsInComparison(S, E);
11363   }
11364 
11365   LHS = LHS->IgnoreParenImpCasts();
11366   RHS = RHS->IgnoreParenImpCasts();
11367 
11368   if (!S.getLangOpts().CPlusPlus) {
11369     // Avoid warning about comparison of integers with different signs when
11370     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11371     // the type of `E`.
11372     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11373       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11374     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11375       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11376   }
11377 
11378   // Check to see if one of the (unmodified) operands is of different
11379   // signedness.
11380   Expr *signedOperand, *unsignedOperand;
11381   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11382     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11383            "unsigned comparison between two signed integer expressions?");
11384     signedOperand = LHS;
11385     unsignedOperand = RHS;
11386   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11387     signedOperand = RHS;
11388     unsignedOperand = LHS;
11389   } else {
11390     return AnalyzeImpConvsInComparison(S, E);
11391   }
11392 
11393   // Otherwise, calculate the effective range of the signed operand.
11394   IntRange signedRange = GetExprRange(
11395       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11396 
11397   // Go ahead and analyze implicit conversions in the operands.  Note
11398   // that we skip the implicit conversions on both sides.
11399   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11400   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11401 
11402   // If the signed range is non-negative, -Wsign-compare won't fire.
11403   if (signedRange.NonNegative)
11404     return;
11405 
11406   // For (in)equality comparisons, if the unsigned operand is a
11407   // constant which cannot collide with a overflowed signed operand,
11408   // then reinterpreting the signed operand as unsigned will not
11409   // change the result of the comparison.
11410   if (E->isEqualityOp()) {
11411     unsigned comparisonWidth = S.Context.getIntWidth(T);
11412     IntRange unsignedRange =
11413         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11414                      /*Approximate*/ true);
11415 
11416     // We should never be unable to prove that the unsigned operand is
11417     // non-negative.
11418     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11419 
11420     if (unsignedRange.Width < comparisonWidth)
11421       return;
11422   }
11423 
11424   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11425                         S.PDiag(diag::warn_mixed_sign_comparison)
11426                             << LHS->getType() << RHS->getType()
11427                             << LHS->getSourceRange() << RHS->getSourceRange());
11428 }
11429 
11430 /// Analyzes an attempt to assign the given value to a bitfield.
11431 ///
11432 /// Returns true if there was something fishy about the attempt.
11433 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11434                                       SourceLocation InitLoc) {
11435   assert(Bitfield->isBitField());
11436   if (Bitfield->isInvalidDecl())
11437     return false;
11438 
11439   // White-list bool bitfields.
11440   QualType BitfieldType = Bitfield->getType();
11441   if (BitfieldType->isBooleanType())
11442      return false;
11443 
11444   if (BitfieldType->isEnumeralType()) {
11445     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11446     // If the underlying enum type was not explicitly specified as an unsigned
11447     // type and the enum contain only positive values, MSVC++ will cause an
11448     // inconsistency by storing this as a signed type.
11449     if (S.getLangOpts().CPlusPlus11 &&
11450         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11451         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11452         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11453       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11454           << BitfieldEnumDecl;
11455     }
11456   }
11457 
11458   if (Bitfield->getType()->isBooleanType())
11459     return false;
11460 
11461   // Ignore value- or type-dependent expressions.
11462   if (Bitfield->getBitWidth()->isValueDependent() ||
11463       Bitfield->getBitWidth()->isTypeDependent() ||
11464       Init->isValueDependent() ||
11465       Init->isTypeDependent())
11466     return false;
11467 
11468   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11469   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11470 
11471   Expr::EvalResult Result;
11472   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11473                                    Expr::SE_AllowSideEffects)) {
11474     // The RHS is not constant.  If the RHS has an enum type, make sure the
11475     // bitfield is wide enough to hold all the values of the enum without
11476     // truncation.
11477     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11478       EnumDecl *ED = EnumTy->getDecl();
11479       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11480 
11481       // Enum types are implicitly signed on Windows, so check if there are any
11482       // negative enumerators to see if the enum was intended to be signed or
11483       // not.
11484       bool SignedEnum = ED->getNumNegativeBits() > 0;
11485 
11486       // Check for surprising sign changes when assigning enum values to a
11487       // bitfield of different signedness.  If the bitfield is signed and we
11488       // have exactly the right number of bits to store this unsigned enum,
11489       // suggest changing the enum to an unsigned type. This typically happens
11490       // on Windows where unfixed enums always use an underlying type of 'int'.
11491       unsigned DiagID = 0;
11492       if (SignedEnum && !SignedBitfield) {
11493         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11494       } else if (SignedBitfield && !SignedEnum &&
11495                  ED->getNumPositiveBits() == FieldWidth) {
11496         DiagID = diag::warn_signed_bitfield_enum_conversion;
11497       }
11498 
11499       if (DiagID) {
11500         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11501         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11502         SourceRange TypeRange =
11503             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11504         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11505             << SignedEnum << TypeRange;
11506       }
11507 
11508       // Compute the required bitwidth. If the enum has negative values, we need
11509       // one more bit than the normal number of positive bits to represent the
11510       // sign bit.
11511       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11512                                                   ED->getNumNegativeBits())
11513                                        : ED->getNumPositiveBits();
11514 
11515       // Check the bitwidth.
11516       if (BitsNeeded > FieldWidth) {
11517         Expr *WidthExpr = Bitfield->getBitWidth();
11518         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11519             << Bitfield << ED;
11520         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11521             << BitsNeeded << ED << WidthExpr->getSourceRange();
11522       }
11523     }
11524 
11525     return false;
11526   }
11527 
11528   llvm::APSInt Value = Result.Val.getInt();
11529 
11530   unsigned OriginalWidth = Value.getBitWidth();
11531 
11532   if (!Value.isSigned() || Value.isNegative())
11533     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11534       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11535         OriginalWidth = Value.getMinSignedBits();
11536 
11537   if (OriginalWidth <= FieldWidth)
11538     return false;
11539 
11540   // Compute the value which the bitfield will contain.
11541   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11542   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11543 
11544   // Check whether the stored value is equal to the original value.
11545   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11546   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11547     return false;
11548 
11549   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11550   // therefore don't strictly fit into a signed bitfield of width 1.
11551   if (FieldWidth == 1 && Value == 1)
11552     return false;
11553 
11554   std::string PrettyValue = Value.toString(10);
11555   std::string PrettyTrunc = TruncatedValue.toString(10);
11556 
11557   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11558     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11559     << Init->getSourceRange();
11560 
11561   return true;
11562 }
11563 
11564 /// Analyze the given simple or compound assignment for warning-worthy
11565 /// operations.
11566 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11567   // Just recurse on the LHS.
11568   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11569 
11570   // We want to recurse on the RHS as normal unless we're assigning to
11571   // a bitfield.
11572   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11573     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11574                                   E->getOperatorLoc())) {
11575       // Recurse, ignoring any implicit conversions on the RHS.
11576       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11577                                         E->getOperatorLoc());
11578     }
11579   }
11580 
11581   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11582 
11583   // Diagnose implicitly sequentially-consistent atomic assignment.
11584   if (E->getLHS()->getType()->isAtomicType())
11585     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11586 }
11587 
11588 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11589 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11590                             SourceLocation CContext, unsigned diag,
11591                             bool pruneControlFlow = false) {
11592   if (pruneControlFlow) {
11593     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11594                           S.PDiag(diag)
11595                               << SourceType << T << E->getSourceRange()
11596                               << SourceRange(CContext));
11597     return;
11598   }
11599   S.Diag(E->getExprLoc(), diag)
11600     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11601 }
11602 
11603 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11604 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11605                             SourceLocation CContext,
11606                             unsigned diag, bool pruneControlFlow = false) {
11607   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11608 }
11609 
11610 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11611   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11612       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11613 }
11614 
11615 static void adornObjCBoolConversionDiagWithTernaryFixit(
11616     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11617   Expr *Ignored = SourceExpr->IgnoreImplicit();
11618   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11619     Ignored = OVE->getSourceExpr();
11620   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11621                      isa<BinaryOperator>(Ignored) ||
11622                      isa<CXXOperatorCallExpr>(Ignored);
11623   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11624   if (NeedsParens)
11625     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11626             << FixItHint::CreateInsertion(EndLoc, ")");
11627   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11628 }
11629 
11630 /// Diagnose an implicit cast from a floating point value to an integer value.
11631 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11632                                     SourceLocation CContext) {
11633   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11634   const bool PruneWarnings = S.inTemplateInstantiation();
11635 
11636   Expr *InnerE = E->IgnoreParenImpCasts();
11637   // We also want to warn on, e.g., "int i = -1.234"
11638   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11639     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11640       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11641 
11642   const bool IsLiteral =
11643       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11644 
11645   llvm::APFloat Value(0.0);
11646   bool IsConstant =
11647     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11648   if (!IsConstant) {
11649     if (isObjCSignedCharBool(S, T)) {
11650       return adornObjCBoolConversionDiagWithTernaryFixit(
11651           S, E,
11652           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11653               << E->getType());
11654     }
11655 
11656     return DiagnoseImpCast(S, E, T, CContext,
11657                            diag::warn_impcast_float_integer, PruneWarnings);
11658   }
11659 
11660   bool isExact = false;
11661 
11662   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11663                             T->hasUnsignedIntegerRepresentation());
11664   llvm::APFloat::opStatus Result = Value.convertToInteger(
11665       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11666 
11667   // FIXME: Force the precision of the source value down so we don't print
11668   // digits which are usually useless (we don't really care here if we
11669   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11670   // would automatically print the shortest representation, but it's a bit
11671   // tricky to implement.
11672   SmallString<16> PrettySourceValue;
11673   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11674   precision = (precision * 59 + 195) / 196;
11675   Value.toString(PrettySourceValue, precision);
11676 
11677   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11678     return adornObjCBoolConversionDiagWithTernaryFixit(
11679         S, E,
11680         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11681             << PrettySourceValue);
11682   }
11683 
11684   if (Result == llvm::APFloat::opOK && isExact) {
11685     if (IsLiteral) return;
11686     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11687                            PruneWarnings);
11688   }
11689 
11690   // Conversion of a floating-point value to a non-bool integer where the
11691   // integral part cannot be represented by the integer type is undefined.
11692   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11693     return DiagnoseImpCast(
11694         S, E, T, CContext,
11695         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11696                   : diag::warn_impcast_float_to_integer_out_of_range,
11697         PruneWarnings);
11698 
11699   unsigned DiagID = 0;
11700   if (IsLiteral) {
11701     // Warn on floating point literal to integer.
11702     DiagID = diag::warn_impcast_literal_float_to_integer;
11703   } else if (IntegerValue == 0) {
11704     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11705       return DiagnoseImpCast(S, E, T, CContext,
11706                              diag::warn_impcast_float_integer, PruneWarnings);
11707     }
11708     // Warn on non-zero to zero conversion.
11709     DiagID = diag::warn_impcast_float_to_integer_zero;
11710   } else {
11711     if (IntegerValue.isUnsigned()) {
11712       if (!IntegerValue.isMaxValue()) {
11713         return DiagnoseImpCast(S, E, T, CContext,
11714                                diag::warn_impcast_float_integer, PruneWarnings);
11715       }
11716     } else {  // IntegerValue.isSigned()
11717       if (!IntegerValue.isMaxSignedValue() &&
11718           !IntegerValue.isMinSignedValue()) {
11719         return DiagnoseImpCast(S, E, T, CContext,
11720                                diag::warn_impcast_float_integer, PruneWarnings);
11721       }
11722     }
11723     // Warn on evaluatable floating point expression to integer conversion.
11724     DiagID = diag::warn_impcast_float_to_integer;
11725   }
11726 
11727   SmallString<16> PrettyTargetValue;
11728   if (IsBool)
11729     PrettyTargetValue = Value.isZero() ? "false" : "true";
11730   else
11731     IntegerValue.toString(PrettyTargetValue);
11732 
11733   if (PruneWarnings) {
11734     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11735                           S.PDiag(DiagID)
11736                               << E->getType() << T.getUnqualifiedType()
11737                               << PrettySourceValue << PrettyTargetValue
11738                               << E->getSourceRange() << SourceRange(CContext));
11739   } else {
11740     S.Diag(E->getExprLoc(), DiagID)
11741         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11742         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11743   }
11744 }
11745 
11746 /// Analyze the given compound assignment for the possible losing of
11747 /// floating-point precision.
11748 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11749   assert(isa<CompoundAssignOperator>(E) &&
11750          "Must be compound assignment operation");
11751   // Recurse on the LHS and RHS in here
11752   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11753   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11754 
11755   if (E->getLHS()->getType()->isAtomicType())
11756     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11757 
11758   // Now check the outermost expression
11759   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11760   const auto *RBT = cast<CompoundAssignOperator>(E)
11761                         ->getComputationResultType()
11762                         ->getAs<BuiltinType>();
11763 
11764   // The below checks assume source is floating point.
11765   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11766 
11767   // If source is floating point but target is an integer.
11768   if (ResultBT->isInteger())
11769     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11770                            E->getExprLoc(), diag::warn_impcast_float_integer);
11771 
11772   if (!ResultBT->isFloatingPoint())
11773     return;
11774 
11775   // If both source and target are floating points, warn about losing precision.
11776   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11777       QualType(ResultBT, 0), QualType(RBT, 0));
11778   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11779     // warn about dropping FP rank.
11780     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11781                     diag::warn_impcast_float_result_precision);
11782 }
11783 
11784 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11785                                       IntRange Range) {
11786   if (!Range.Width) return "0";
11787 
11788   llvm::APSInt ValueInRange = Value;
11789   ValueInRange.setIsSigned(!Range.NonNegative);
11790   ValueInRange = ValueInRange.trunc(Range.Width);
11791   return ValueInRange.toString(10);
11792 }
11793 
11794 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11795   if (!isa<ImplicitCastExpr>(Ex))
11796     return false;
11797 
11798   Expr *InnerE = Ex->IgnoreParenImpCasts();
11799   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11800   const Type *Source =
11801     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11802   if (Target->isDependentType())
11803     return false;
11804 
11805   const BuiltinType *FloatCandidateBT =
11806     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11807   const Type *BoolCandidateType = ToBool ? Target : Source;
11808 
11809   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11810           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11811 }
11812 
11813 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11814                                              SourceLocation CC) {
11815   unsigned NumArgs = TheCall->getNumArgs();
11816   for (unsigned i = 0; i < NumArgs; ++i) {
11817     Expr *CurrA = TheCall->getArg(i);
11818     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11819       continue;
11820 
11821     bool IsSwapped = ((i > 0) &&
11822         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11823     IsSwapped |= ((i < (NumArgs - 1)) &&
11824         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11825     if (IsSwapped) {
11826       // Warn on this floating-point to bool conversion.
11827       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11828                       CurrA->getType(), CC,
11829                       diag::warn_impcast_floating_point_to_bool);
11830     }
11831   }
11832 }
11833 
11834 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11835                                    SourceLocation CC) {
11836   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11837                         E->getExprLoc()))
11838     return;
11839 
11840   // Don't warn on functions which have return type nullptr_t.
11841   if (isa<CallExpr>(E))
11842     return;
11843 
11844   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11845   const Expr::NullPointerConstantKind NullKind =
11846       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11847   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11848     return;
11849 
11850   // Return if target type is a safe conversion.
11851   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11852       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11853     return;
11854 
11855   SourceLocation Loc = E->getSourceRange().getBegin();
11856 
11857   // Venture through the macro stacks to get to the source of macro arguments.
11858   // The new location is a better location than the complete location that was
11859   // passed in.
11860   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11861   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11862 
11863   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11864   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11865     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11866         Loc, S.SourceMgr, S.getLangOpts());
11867     if (MacroName == "NULL")
11868       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11869   }
11870 
11871   // Only warn if the null and context location are in the same macro expansion.
11872   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11873     return;
11874 
11875   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11876       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11877       << FixItHint::CreateReplacement(Loc,
11878                                       S.getFixItZeroLiteralForType(T, Loc));
11879 }
11880 
11881 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11882                                   ObjCArrayLiteral *ArrayLiteral);
11883 
11884 static void
11885 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11886                            ObjCDictionaryLiteral *DictionaryLiteral);
11887 
11888 /// Check a single element within a collection literal against the
11889 /// target element type.
11890 static void checkObjCCollectionLiteralElement(Sema &S,
11891                                               QualType TargetElementType,
11892                                               Expr *Element,
11893                                               unsigned ElementKind) {
11894   // Skip a bitcast to 'id' or qualified 'id'.
11895   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11896     if (ICE->getCastKind() == CK_BitCast &&
11897         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11898       Element = ICE->getSubExpr();
11899   }
11900 
11901   QualType ElementType = Element->getType();
11902   ExprResult ElementResult(Element);
11903   if (ElementType->getAs<ObjCObjectPointerType>() &&
11904       S.CheckSingleAssignmentConstraints(TargetElementType,
11905                                          ElementResult,
11906                                          false, false)
11907         != Sema::Compatible) {
11908     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11909         << ElementType << ElementKind << TargetElementType
11910         << Element->getSourceRange();
11911   }
11912 
11913   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11914     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11915   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11916     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11917 }
11918 
11919 /// Check an Objective-C array literal being converted to the given
11920 /// target type.
11921 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11922                                   ObjCArrayLiteral *ArrayLiteral) {
11923   if (!S.NSArrayDecl)
11924     return;
11925 
11926   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11927   if (!TargetObjCPtr)
11928     return;
11929 
11930   if (TargetObjCPtr->isUnspecialized() ||
11931       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11932         != S.NSArrayDecl->getCanonicalDecl())
11933     return;
11934 
11935   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11936   if (TypeArgs.size() != 1)
11937     return;
11938 
11939   QualType TargetElementType = TypeArgs[0];
11940   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11941     checkObjCCollectionLiteralElement(S, TargetElementType,
11942                                       ArrayLiteral->getElement(I),
11943                                       0);
11944   }
11945 }
11946 
11947 /// Check an Objective-C dictionary literal being converted to the given
11948 /// target type.
11949 static void
11950 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11951                            ObjCDictionaryLiteral *DictionaryLiteral) {
11952   if (!S.NSDictionaryDecl)
11953     return;
11954 
11955   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11956   if (!TargetObjCPtr)
11957     return;
11958 
11959   if (TargetObjCPtr->isUnspecialized() ||
11960       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11961         != S.NSDictionaryDecl->getCanonicalDecl())
11962     return;
11963 
11964   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11965   if (TypeArgs.size() != 2)
11966     return;
11967 
11968   QualType TargetKeyType = TypeArgs[0];
11969   QualType TargetObjectType = TypeArgs[1];
11970   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11971     auto Element = DictionaryLiteral->getKeyValueElement(I);
11972     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11973     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11974   }
11975 }
11976 
11977 // Helper function to filter out cases for constant width constant conversion.
11978 // Don't warn on char array initialization or for non-decimal values.
11979 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11980                                           SourceLocation CC) {
11981   // If initializing from a constant, and the constant starts with '0',
11982   // then it is a binary, octal, or hexadecimal.  Allow these constants
11983   // to fill all the bits, even if there is a sign change.
11984   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11985     const char FirstLiteralCharacter =
11986         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11987     if (FirstLiteralCharacter == '0')
11988       return false;
11989   }
11990 
11991   // If the CC location points to a '{', and the type is char, then assume
11992   // assume it is an array initialization.
11993   if (CC.isValid() && T->isCharType()) {
11994     const char FirstContextCharacter =
11995         S.getSourceManager().getCharacterData(CC)[0];
11996     if (FirstContextCharacter == '{')
11997       return false;
11998   }
11999 
12000   return true;
12001 }
12002 
12003 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12004   const auto *IL = dyn_cast<IntegerLiteral>(E);
12005   if (!IL) {
12006     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12007       if (UO->getOpcode() == UO_Minus)
12008         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12009     }
12010   }
12011 
12012   return IL;
12013 }
12014 
12015 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12016   E = E->IgnoreParenImpCasts();
12017   SourceLocation ExprLoc = E->getExprLoc();
12018 
12019   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12020     BinaryOperator::Opcode Opc = BO->getOpcode();
12021     Expr::EvalResult Result;
12022     // Do not diagnose unsigned shifts.
12023     if (Opc == BO_Shl) {
12024       const auto *LHS = getIntegerLiteral(BO->getLHS());
12025       const auto *RHS = getIntegerLiteral(BO->getRHS());
12026       if (LHS && LHS->getValue() == 0)
12027         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12028       else if (!E->isValueDependent() && LHS && RHS &&
12029                RHS->getValue().isNonNegative() &&
12030                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12031         S.Diag(ExprLoc, diag::warn_left_shift_always)
12032             << (Result.Val.getInt() != 0);
12033       else if (E->getType()->isSignedIntegerType())
12034         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12035     }
12036   }
12037 
12038   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12039     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12040     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12041     if (!LHS || !RHS)
12042       return;
12043     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12044         (RHS->getValue() == 0 || RHS->getValue() == 1))
12045       // Do not diagnose common idioms.
12046       return;
12047     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12048       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12049   }
12050 }
12051 
12052 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12053                                     SourceLocation CC,
12054                                     bool *ICContext = nullptr,
12055                                     bool IsListInit = false) {
12056   if (E->isTypeDependent() || E->isValueDependent()) return;
12057 
12058   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12059   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12060   if (Source == Target) return;
12061   if (Target->isDependentType()) return;
12062 
12063   // If the conversion context location is invalid don't complain. We also
12064   // don't want to emit a warning if the issue occurs from the expansion of
12065   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12066   // delay this check as long as possible. Once we detect we are in that
12067   // scenario, we just return.
12068   if (CC.isInvalid())
12069     return;
12070 
12071   if (Source->isAtomicType())
12072     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12073 
12074   // Diagnose implicit casts to bool.
12075   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12076     if (isa<StringLiteral>(E))
12077       // Warn on string literal to bool.  Checks for string literals in logical
12078       // and expressions, for instance, assert(0 && "error here"), are
12079       // prevented by a check in AnalyzeImplicitConversions().
12080       return DiagnoseImpCast(S, E, T, CC,
12081                              diag::warn_impcast_string_literal_to_bool);
12082     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12083         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12084       // This covers the literal expressions that evaluate to Objective-C
12085       // objects.
12086       return DiagnoseImpCast(S, E, T, CC,
12087                              diag::warn_impcast_objective_c_literal_to_bool);
12088     }
12089     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12090       // Warn on pointer to bool conversion that is always true.
12091       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12092                                      SourceRange(CC));
12093     }
12094   }
12095 
12096   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12097   // is a typedef for signed char (macOS), then that constant value has to be 1
12098   // or 0.
12099   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12100     Expr::EvalResult Result;
12101     if (E->EvaluateAsInt(Result, S.getASTContext(),
12102                          Expr::SE_AllowSideEffects)) {
12103       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12104         adornObjCBoolConversionDiagWithTernaryFixit(
12105             S, E,
12106             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12107                 << Result.Val.getInt().toString(10));
12108       }
12109       return;
12110     }
12111   }
12112 
12113   // Check implicit casts from Objective-C collection literals to specialized
12114   // collection types, e.g., NSArray<NSString *> *.
12115   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12116     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12117   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12118     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12119 
12120   // Strip vector types.
12121   if (const auto *SourceVT = dyn_cast<VectorType>(Source)) {
12122     if (Target->isVLSTBuiltinType()) {
12123       auto SourceVectorKind = SourceVT->getVectorKind();
12124       if (SourceVectorKind == VectorType::SveFixedLengthDataVector ||
12125           SourceVectorKind == VectorType::SveFixedLengthPredicateVector ||
12126           (SourceVectorKind == VectorType::GenericVector &&
12127            S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits))
12128         return;
12129     }
12130 
12131     if (!isa<VectorType>(Target)) {
12132       if (S.SourceMgr.isInSystemMacro(CC))
12133         return;
12134       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12135     }
12136 
12137     // If the vector cast is cast between two vectors of the same size, it is
12138     // a bitcast, not a conversion.
12139     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12140       return;
12141 
12142     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12143     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12144   }
12145   if (auto VecTy = dyn_cast<VectorType>(Target))
12146     Target = VecTy->getElementType().getTypePtr();
12147 
12148   // Strip complex types.
12149   if (isa<ComplexType>(Source)) {
12150     if (!isa<ComplexType>(Target)) {
12151       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12152         return;
12153 
12154       return DiagnoseImpCast(S, E, T, CC,
12155                              S.getLangOpts().CPlusPlus
12156                                  ? diag::err_impcast_complex_scalar
12157                                  : diag::warn_impcast_complex_scalar);
12158     }
12159 
12160     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12161     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12162   }
12163 
12164   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12165   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12166 
12167   // If the source is floating point...
12168   if (SourceBT && SourceBT->isFloatingPoint()) {
12169     // ...and the target is floating point...
12170     if (TargetBT && TargetBT->isFloatingPoint()) {
12171       // ...then warn if we're dropping FP rank.
12172 
12173       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12174           QualType(SourceBT, 0), QualType(TargetBT, 0));
12175       if (Order > 0) {
12176         // Don't warn about float constants that are precisely
12177         // representable in the target type.
12178         Expr::EvalResult result;
12179         if (E->EvaluateAsRValue(result, S.Context)) {
12180           // Value might be a float, a float vector, or a float complex.
12181           if (IsSameFloatAfterCast(result.Val,
12182                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12183                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12184             return;
12185         }
12186 
12187         if (S.SourceMgr.isInSystemMacro(CC))
12188           return;
12189 
12190         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12191       }
12192       // ... or possibly if we're increasing rank, too
12193       else if (Order < 0) {
12194         if (S.SourceMgr.isInSystemMacro(CC))
12195           return;
12196 
12197         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12198       }
12199       return;
12200     }
12201 
12202     // If the target is integral, always warn.
12203     if (TargetBT && TargetBT->isInteger()) {
12204       if (S.SourceMgr.isInSystemMacro(CC))
12205         return;
12206 
12207       DiagnoseFloatingImpCast(S, E, T, CC);
12208     }
12209 
12210     // Detect the case where a call result is converted from floating-point to
12211     // to bool, and the final argument to the call is converted from bool, to
12212     // discover this typo:
12213     //
12214     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12215     //
12216     // FIXME: This is an incredibly special case; is there some more general
12217     // way to detect this class of misplaced-parentheses bug?
12218     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12219       // Check last argument of function call to see if it is an
12220       // implicit cast from a type matching the type the result
12221       // is being cast to.
12222       CallExpr *CEx = cast<CallExpr>(E);
12223       if (unsigned NumArgs = CEx->getNumArgs()) {
12224         Expr *LastA = CEx->getArg(NumArgs - 1);
12225         Expr *InnerE = LastA->IgnoreParenImpCasts();
12226         if (isa<ImplicitCastExpr>(LastA) &&
12227             InnerE->getType()->isBooleanType()) {
12228           // Warn on this floating-point to bool conversion
12229           DiagnoseImpCast(S, E, T, CC,
12230                           diag::warn_impcast_floating_point_to_bool);
12231         }
12232       }
12233     }
12234     return;
12235   }
12236 
12237   // Valid casts involving fixed point types should be accounted for here.
12238   if (Source->isFixedPointType()) {
12239     if (Target->isUnsaturatedFixedPointType()) {
12240       Expr::EvalResult Result;
12241       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12242                                   S.isConstantEvaluated())) {
12243         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12244         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12245         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12246         if (Value > MaxVal || Value < MinVal) {
12247           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12248                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12249                                     << Value.toString() << T
12250                                     << E->getSourceRange()
12251                                     << clang::SourceRange(CC));
12252           return;
12253         }
12254       }
12255     } else if (Target->isIntegerType()) {
12256       Expr::EvalResult Result;
12257       if (!S.isConstantEvaluated() &&
12258           E->EvaluateAsFixedPoint(Result, S.Context,
12259                                   Expr::SE_AllowSideEffects)) {
12260         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12261 
12262         bool Overflowed;
12263         llvm::APSInt IntResult = FXResult.convertToInt(
12264             S.Context.getIntWidth(T),
12265             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12266 
12267         if (Overflowed) {
12268           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12269                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12270                                     << FXResult.toString() << T
12271                                     << E->getSourceRange()
12272                                     << clang::SourceRange(CC));
12273           return;
12274         }
12275       }
12276     }
12277   } else if (Target->isUnsaturatedFixedPointType()) {
12278     if (Source->isIntegerType()) {
12279       Expr::EvalResult Result;
12280       if (!S.isConstantEvaluated() &&
12281           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12282         llvm::APSInt Value = Result.Val.getInt();
12283 
12284         bool Overflowed;
12285         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12286             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12287 
12288         if (Overflowed) {
12289           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12290                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12291                                     << Value.toString(/*Radix=*/10) << T
12292                                     << E->getSourceRange()
12293                                     << clang::SourceRange(CC));
12294           return;
12295         }
12296       }
12297     }
12298   }
12299 
12300   // If we are casting an integer type to a floating point type without
12301   // initialization-list syntax, we might lose accuracy if the floating
12302   // point type has a narrower significand than the integer type.
12303   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12304       TargetBT->isFloatingType() && !IsListInit) {
12305     // Determine the number of precision bits in the source integer type.
12306     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12307                                         /*Approximate*/ true);
12308     unsigned int SourcePrecision = SourceRange.Width;
12309 
12310     // Determine the number of precision bits in the
12311     // target floating point type.
12312     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12313         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12314 
12315     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12316         SourcePrecision > TargetPrecision) {
12317 
12318       if (Optional<llvm::APSInt> SourceInt =
12319               E->getIntegerConstantExpr(S.Context)) {
12320         // If the source integer is a constant, convert it to the target
12321         // floating point type. Issue a warning if the value changes
12322         // during the whole conversion.
12323         llvm::APFloat TargetFloatValue(
12324             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12325         llvm::APFloat::opStatus ConversionStatus =
12326             TargetFloatValue.convertFromAPInt(
12327                 *SourceInt, SourceBT->isSignedInteger(),
12328                 llvm::APFloat::rmNearestTiesToEven);
12329 
12330         if (ConversionStatus != llvm::APFloat::opOK) {
12331           std::string PrettySourceValue = SourceInt->toString(10);
12332           SmallString<32> PrettyTargetValue;
12333           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12334 
12335           S.DiagRuntimeBehavior(
12336               E->getExprLoc(), E,
12337               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12338                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12339                   << E->getSourceRange() << clang::SourceRange(CC));
12340         }
12341       } else {
12342         // Otherwise, the implicit conversion may lose precision.
12343         DiagnoseImpCast(S, E, T, CC,
12344                         diag::warn_impcast_integer_float_precision);
12345       }
12346     }
12347   }
12348 
12349   DiagnoseNullConversion(S, E, T, CC);
12350 
12351   S.DiscardMisalignedMemberAddress(Target, E);
12352 
12353   if (Target->isBooleanType())
12354     DiagnoseIntInBoolContext(S, E);
12355 
12356   if (!Source->isIntegerType() || !Target->isIntegerType())
12357     return;
12358 
12359   // TODO: remove this early return once the false positives for constant->bool
12360   // in templates, macros, etc, are reduced or removed.
12361   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12362     return;
12363 
12364   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12365       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12366     return adornObjCBoolConversionDiagWithTernaryFixit(
12367         S, E,
12368         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12369             << E->getType());
12370   }
12371 
12372   IntRange SourceTypeRange =
12373       IntRange::forTargetOfCanonicalType(S.Context, Source);
12374   IntRange LikelySourceRange =
12375       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12376   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12377 
12378   if (LikelySourceRange.Width > TargetRange.Width) {
12379     // If the source is a constant, use a default-on diagnostic.
12380     // TODO: this should happen for bitfield stores, too.
12381     Expr::EvalResult Result;
12382     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12383                          S.isConstantEvaluated())) {
12384       llvm::APSInt Value(32);
12385       Value = Result.Val.getInt();
12386 
12387       if (S.SourceMgr.isInSystemMacro(CC))
12388         return;
12389 
12390       std::string PrettySourceValue = Value.toString(10);
12391       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12392 
12393       S.DiagRuntimeBehavior(
12394           E->getExprLoc(), E,
12395           S.PDiag(diag::warn_impcast_integer_precision_constant)
12396               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12397               << E->getSourceRange() << SourceRange(CC));
12398       return;
12399     }
12400 
12401     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12402     if (S.SourceMgr.isInSystemMacro(CC))
12403       return;
12404 
12405     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12406       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12407                              /* pruneControlFlow */ true);
12408     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12409   }
12410 
12411   if (TargetRange.Width > SourceTypeRange.Width) {
12412     if (auto *UO = dyn_cast<UnaryOperator>(E))
12413       if (UO->getOpcode() == UO_Minus)
12414         if (Source->isUnsignedIntegerType()) {
12415           if (Target->isUnsignedIntegerType())
12416             return DiagnoseImpCast(S, E, T, CC,
12417                                    diag::warn_impcast_high_order_zero_bits);
12418           if (Target->isSignedIntegerType())
12419             return DiagnoseImpCast(S, E, T, CC,
12420                                    diag::warn_impcast_nonnegative_result);
12421         }
12422   }
12423 
12424   if (TargetRange.Width == LikelySourceRange.Width &&
12425       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12426       Source->isSignedIntegerType()) {
12427     // Warn when doing a signed to signed conversion, warn if the positive
12428     // source value is exactly the width of the target type, which will
12429     // cause a negative value to be stored.
12430 
12431     Expr::EvalResult Result;
12432     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12433         !S.SourceMgr.isInSystemMacro(CC)) {
12434       llvm::APSInt Value = Result.Val.getInt();
12435       if (isSameWidthConstantConversion(S, E, T, CC)) {
12436         std::string PrettySourceValue = Value.toString(10);
12437         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12438 
12439         S.DiagRuntimeBehavior(
12440             E->getExprLoc(), E,
12441             S.PDiag(diag::warn_impcast_integer_precision_constant)
12442                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12443                 << E->getSourceRange() << SourceRange(CC));
12444         return;
12445       }
12446     }
12447 
12448     // Fall through for non-constants to give a sign conversion warning.
12449   }
12450 
12451   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12452       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12453        LikelySourceRange.Width == TargetRange.Width)) {
12454     if (S.SourceMgr.isInSystemMacro(CC))
12455       return;
12456 
12457     unsigned DiagID = diag::warn_impcast_integer_sign;
12458 
12459     // Traditionally, gcc has warned about this under -Wsign-compare.
12460     // We also want to warn about it in -Wconversion.
12461     // So if -Wconversion is off, use a completely identical diagnostic
12462     // in the sign-compare group.
12463     // The conditional-checking code will
12464     if (ICContext) {
12465       DiagID = diag::warn_impcast_integer_sign_conditional;
12466       *ICContext = true;
12467     }
12468 
12469     return DiagnoseImpCast(S, E, T, CC, DiagID);
12470   }
12471 
12472   // Diagnose conversions between different enumeration types.
12473   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12474   // type, to give us better diagnostics.
12475   QualType SourceType = E->getType();
12476   if (!S.getLangOpts().CPlusPlus) {
12477     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12478       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12479         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12480         SourceType = S.Context.getTypeDeclType(Enum);
12481         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12482       }
12483   }
12484 
12485   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12486     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12487       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12488           TargetEnum->getDecl()->hasNameForLinkage() &&
12489           SourceEnum != TargetEnum) {
12490         if (S.SourceMgr.isInSystemMacro(CC))
12491           return;
12492 
12493         return DiagnoseImpCast(S, E, SourceType, T, CC,
12494                                diag::warn_impcast_different_enum_types);
12495       }
12496 }
12497 
12498 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12499                                      SourceLocation CC, QualType T);
12500 
12501 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12502                                     SourceLocation CC, bool &ICContext) {
12503   E = E->IgnoreParenImpCasts();
12504 
12505   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12506     return CheckConditionalOperator(S, CO, CC, T);
12507 
12508   AnalyzeImplicitConversions(S, E, CC);
12509   if (E->getType() != T)
12510     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12511 }
12512 
12513 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12514                                      SourceLocation CC, QualType T) {
12515   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12516 
12517   Expr *TrueExpr = E->getTrueExpr();
12518   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12519     TrueExpr = BCO->getCommon();
12520 
12521   bool Suspicious = false;
12522   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12523   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12524 
12525   if (T->isBooleanType())
12526     DiagnoseIntInBoolContext(S, E);
12527 
12528   // If -Wconversion would have warned about either of the candidates
12529   // for a signedness conversion to the context type...
12530   if (!Suspicious) return;
12531 
12532   // ...but it's currently ignored...
12533   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12534     return;
12535 
12536   // ...then check whether it would have warned about either of the
12537   // candidates for a signedness conversion to the condition type.
12538   if (E->getType() == T) return;
12539 
12540   Suspicious = false;
12541   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12542                           E->getType(), CC, &Suspicious);
12543   if (!Suspicious)
12544     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12545                             E->getType(), CC, &Suspicious);
12546 }
12547 
12548 /// Check conversion of given expression to boolean.
12549 /// Input argument E is a logical expression.
12550 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12551   if (S.getLangOpts().Bool)
12552     return;
12553   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12554     return;
12555   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12556 }
12557 
12558 namespace {
12559 struct AnalyzeImplicitConversionsWorkItem {
12560   Expr *E;
12561   SourceLocation CC;
12562   bool IsListInit;
12563 };
12564 }
12565 
12566 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12567 /// that should be visited are added to WorkList.
12568 static void AnalyzeImplicitConversions(
12569     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12570     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12571   Expr *OrigE = Item.E;
12572   SourceLocation CC = Item.CC;
12573 
12574   QualType T = OrigE->getType();
12575   Expr *E = OrigE->IgnoreParenImpCasts();
12576 
12577   // Propagate whether we are in a C++ list initialization expression.
12578   // If so, we do not issue warnings for implicit int-float conversion
12579   // precision loss, because C++11 narrowing already handles it.
12580   bool IsListInit = Item.IsListInit ||
12581                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12582 
12583   if (E->isTypeDependent() || E->isValueDependent())
12584     return;
12585 
12586   Expr *SourceExpr = E;
12587   // Examine, but don't traverse into the source expression of an
12588   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12589   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12590   // evaluate it in the context of checking the specific conversion to T though.
12591   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12592     if (auto *Src = OVE->getSourceExpr())
12593       SourceExpr = Src;
12594 
12595   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12596     if (UO->getOpcode() == UO_Not &&
12597         UO->getSubExpr()->isKnownToHaveBooleanValue())
12598       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12599           << OrigE->getSourceRange() << T->isBooleanType()
12600           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12601 
12602   // For conditional operators, we analyze the arguments as if they
12603   // were being fed directly into the output.
12604   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12605     CheckConditionalOperator(S, CO, CC, T);
12606     return;
12607   }
12608 
12609   // Check implicit argument conversions for function calls.
12610   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12611     CheckImplicitArgumentConversions(S, Call, CC);
12612 
12613   // Go ahead and check any implicit conversions we might have skipped.
12614   // The non-canonical typecheck is just an optimization;
12615   // CheckImplicitConversion will filter out dead implicit conversions.
12616   if (SourceExpr->getType() != T)
12617     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12618 
12619   // Now continue drilling into this expression.
12620 
12621   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12622     // The bound subexpressions in a PseudoObjectExpr are not reachable
12623     // as transitive children.
12624     // FIXME: Use a more uniform representation for this.
12625     for (auto *SE : POE->semantics())
12626       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12627         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12628   }
12629 
12630   // Skip past explicit casts.
12631   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12632     E = CE->getSubExpr()->IgnoreParenImpCasts();
12633     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12634       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12635     WorkList.push_back({E, CC, IsListInit});
12636     return;
12637   }
12638 
12639   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12640     // Do a somewhat different check with comparison operators.
12641     if (BO->isComparisonOp())
12642       return AnalyzeComparison(S, BO);
12643 
12644     // And with simple assignments.
12645     if (BO->getOpcode() == BO_Assign)
12646       return AnalyzeAssignment(S, BO);
12647     // And with compound assignments.
12648     if (BO->isAssignmentOp())
12649       return AnalyzeCompoundAssignment(S, BO);
12650   }
12651 
12652   // These break the otherwise-useful invariant below.  Fortunately,
12653   // we don't really need to recurse into them, because any internal
12654   // expressions should have been analyzed already when they were
12655   // built into statements.
12656   if (isa<StmtExpr>(E)) return;
12657 
12658   // Don't descend into unevaluated contexts.
12659   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12660 
12661   // Now just recurse over the expression's children.
12662   CC = E->getExprLoc();
12663   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12664   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12665   for (Stmt *SubStmt : E->children()) {
12666     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12667     if (!ChildExpr)
12668       continue;
12669 
12670     if (IsLogicalAndOperator &&
12671         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12672       // Ignore checking string literals that are in logical and operators.
12673       // This is a common pattern for asserts.
12674       continue;
12675     WorkList.push_back({ChildExpr, CC, IsListInit});
12676   }
12677 
12678   if (BO && BO->isLogicalOp()) {
12679     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12680     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12681       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12682 
12683     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12684     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12685       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12686   }
12687 
12688   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12689     if (U->getOpcode() == UO_LNot) {
12690       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12691     } else if (U->getOpcode() != UO_AddrOf) {
12692       if (U->getSubExpr()->getType()->isAtomicType())
12693         S.Diag(U->getSubExpr()->getBeginLoc(),
12694                diag::warn_atomic_implicit_seq_cst);
12695     }
12696   }
12697 }
12698 
12699 /// AnalyzeImplicitConversions - Find and report any interesting
12700 /// implicit conversions in the given expression.  There are a couple
12701 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12702 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12703                                        bool IsListInit/*= false*/) {
12704   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12705   WorkList.push_back({OrigE, CC, IsListInit});
12706   while (!WorkList.empty())
12707     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12708 }
12709 
12710 /// Diagnose integer type and any valid implicit conversion to it.
12711 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12712   // Taking into account implicit conversions,
12713   // allow any integer.
12714   if (!E->getType()->isIntegerType()) {
12715     S.Diag(E->getBeginLoc(),
12716            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12717     return true;
12718   }
12719   // Potentially emit standard warnings for implicit conversions if enabled
12720   // using -Wconversion.
12721   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12722   return false;
12723 }
12724 
12725 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12726 // Returns true when emitting a warning about taking the address of a reference.
12727 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12728                               const PartialDiagnostic &PD) {
12729   E = E->IgnoreParenImpCasts();
12730 
12731   const FunctionDecl *FD = nullptr;
12732 
12733   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12734     if (!DRE->getDecl()->getType()->isReferenceType())
12735       return false;
12736   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12737     if (!M->getMemberDecl()->getType()->isReferenceType())
12738       return false;
12739   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12740     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12741       return false;
12742     FD = Call->getDirectCallee();
12743   } else {
12744     return false;
12745   }
12746 
12747   SemaRef.Diag(E->getExprLoc(), PD);
12748 
12749   // If possible, point to location of function.
12750   if (FD) {
12751     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12752   }
12753 
12754   return true;
12755 }
12756 
12757 // Returns true if the SourceLocation is expanded from any macro body.
12758 // Returns false if the SourceLocation is invalid, is from not in a macro
12759 // expansion, or is from expanded from a top-level macro argument.
12760 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12761   if (Loc.isInvalid())
12762     return false;
12763 
12764   while (Loc.isMacroID()) {
12765     if (SM.isMacroBodyExpansion(Loc))
12766       return true;
12767     Loc = SM.getImmediateMacroCallerLoc(Loc);
12768   }
12769 
12770   return false;
12771 }
12772 
12773 /// Diagnose pointers that are always non-null.
12774 /// \param E the expression containing the pointer
12775 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12776 /// compared to a null pointer
12777 /// \param IsEqual True when the comparison is equal to a null pointer
12778 /// \param Range Extra SourceRange to highlight in the diagnostic
12779 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12780                                         Expr::NullPointerConstantKind NullKind,
12781                                         bool IsEqual, SourceRange Range) {
12782   if (!E)
12783     return;
12784 
12785   // Don't warn inside macros.
12786   if (E->getExprLoc().isMacroID()) {
12787     const SourceManager &SM = getSourceManager();
12788     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12789         IsInAnyMacroBody(SM, Range.getBegin()))
12790       return;
12791   }
12792   E = E->IgnoreImpCasts();
12793 
12794   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12795 
12796   if (isa<CXXThisExpr>(E)) {
12797     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12798                                 : diag::warn_this_bool_conversion;
12799     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12800     return;
12801   }
12802 
12803   bool IsAddressOf = false;
12804 
12805   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12806     if (UO->getOpcode() != UO_AddrOf)
12807       return;
12808     IsAddressOf = true;
12809     E = UO->getSubExpr();
12810   }
12811 
12812   if (IsAddressOf) {
12813     unsigned DiagID = IsCompare
12814                           ? diag::warn_address_of_reference_null_compare
12815                           : diag::warn_address_of_reference_bool_conversion;
12816     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12817                                          << IsEqual;
12818     if (CheckForReference(*this, E, PD)) {
12819       return;
12820     }
12821   }
12822 
12823   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12824     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12825     std::string Str;
12826     llvm::raw_string_ostream S(Str);
12827     E->printPretty(S, nullptr, getPrintingPolicy());
12828     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12829                                 : diag::warn_cast_nonnull_to_bool;
12830     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12831       << E->getSourceRange() << Range << IsEqual;
12832     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12833   };
12834 
12835   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12836   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12837     if (auto *Callee = Call->getDirectCallee()) {
12838       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12839         ComplainAboutNonnullParamOrCall(A);
12840         return;
12841       }
12842     }
12843   }
12844 
12845   // Expect to find a single Decl.  Skip anything more complicated.
12846   ValueDecl *D = nullptr;
12847   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12848     D = R->getDecl();
12849   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12850     D = M->getMemberDecl();
12851   }
12852 
12853   // Weak Decls can be null.
12854   if (!D || D->isWeak())
12855     return;
12856 
12857   // Check for parameter decl with nonnull attribute
12858   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12859     if (getCurFunction() &&
12860         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12861       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12862         ComplainAboutNonnullParamOrCall(A);
12863         return;
12864       }
12865 
12866       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12867         // Skip function template not specialized yet.
12868         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12869           return;
12870         auto ParamIter = llvm::find(FD->parameters(), PV);
12871         assert(ParamIter != FD->param_end());
12872         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12873 
12874         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12875           if (!NonNull->args_size()) {
12876               ComplainAboutNonnullParamOrCall(NonNull);
12877               return;
12878           }
12879 
12880           for (const ParamIdx &ArgNo : NonNull->args()) {
12881             if (ArgNo.getASTIndex() == ParamNo) {
12882               ComplainAboutNonnullParamOrCall(NonNull);
12883               return;
12884             }
12885           }
12886         }
12887       }
12888     }
12889   }
12890 
12891   QualType T = D->getType();
12892   const bool IsArray = T->isArrayType();
12893   const bool IsFunction = T->isFunctionType();
12894 
12895   // Address of function is used to silence the function warning.
12896   if (IsAddressOf && IsFunction) {
12897     return;
12898   }
12899 
12900   // Found nothing.
12901   if (!IsAddressOf && !IsFunction && !IsArray)
12902     return;
12903 
12904   // Pretty print the expression for the diagnostic.
12905   std::string Str;
12906   llvm::raw_string_ostream S(Str);
12907   E->printPretty(S, nullptr, getPrintingPolicy());
12908 
12909   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12910                               : diag::warn_impcast_pointer_to_bool;
12911   enum {
12912     AddressOf,
12913     FunctionPointer,
12914     ArrayPointer
12915   } DiagType;
12916   if (IsAddressOf)
12917     DiagType = AddressOf;
12918   else if (IsFunction)
12919     DiagType = FunctionPointer;
12920   else if (IsArray)
12921     DiagType = ArrayPointer;
12922   else
12923     llvm_unreachable("Could not determine diagnostic.");
12924   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12925                                 << Range << IsEqual;
12926 
12927   if (!IsFunction)
12928     return;
12929 
12930   // Suggest '&' to silence the function warning.
12931   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12932       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12933 
12934   // Check to see if '()' fixit should be emitted.
12935   QualType ReturnType;
12936   UnresolvedSet<4> NonTemplateOverloads;
12937   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12938   if (ReturnType.isNull())
12939     return;
12940 
12941   if (IsCompare) {
12942     // There are two cases here.  If there is null constant, the only suggest
12943     // for a pointer return type.  If the null is 0, then suggest if the return
12944     // type is a pointer or an integer type.
12945     if (!ReturnType->isPointerType()) {
12946       if (NullKind == Expr::NPCK_ZeroExpression ||
12947           NullKind == Expr::NPCK_ZeroLiteral) {
12948         if (!ReturnType->isIntegerType())
12949           return;
12950       } else {
12951         return;
12952       }
12953     }
12954   } else { // !IsCompare
12955     // For function to bool, only suggest if the function pointer has bool
12956     // return type.
12957     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12958       return;
12959   }
12960   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12961       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12962 }
12963 
12964 /// Diagnoses "dangerous" implicit conversions within the given
12965 /// expression (which is a full expression).  Implements -Wconversion
12966 /// and -Wsign-compare.
12967 ///
12968 /// \param CC the "context" location of the implicit conversion, i.e.
12969 ///   the most location of the syntactic entity requiring the implicit
12970 ///   conversion
12971 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12972   // Don't diagnose in unevaluated contexts.
12973   if (isUnevaluatedContext())
12974     return;
12975 
12976   // Don't diagnose for value- or type-dependent expressions.
12977   if (E->isTypeDependent() || E->isValueDependent())
12978     return;
12979 
12980   // Check for array bounds violations in cases where the check isn't triggered
12981   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12982   // ArraySubscriptExpr is on the RHS of a variable initialization.
12983   CheckArrayAccess(E);
12984 
12985   // This is not the right CC for (e.g.) a variable initialization.
12986   AnalyzeImplicitConversions(*this, E, CC);
12987 }
12988 
12989 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12990 /// Input argument E is a logical expression.
12991 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12992   ::CheckBoolLikeConversion(*this, E, CC);
12993 }
12994 
12995 /// Diagnose when expression is an integer constant expression and its evaluation
12996 /// results in integer overflow
12997 void Sema::CheckForIntOverflow (Expr *E) {
12998   // Use a work list to deal with nested struct initializers.
12999   SmallVector<Expr *, 2> Exprs(1, E);
13000 
13001   do {
13002     Expr *OriginalE = Exprs.pop_back_val();
13003     Expr *E = OriginalE->IgnoreParenCasts();
13004 
13005     if (isa<BinaryOperator>(E)) {
13006       E->EvaluateForOverflow(Context);
13007       continue;
13008     }
13009 
13010     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13011       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13012     else if (isa<ObjCBoxedExpr>(OriginalE))
13013       E->EvaluateForOverflow(Context);
13014     else if (auto Call = dyn_cast<CallExpr>(E))
13015       Exprs.append(Call->arg_begin(), Call->arg_end());
13016     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13017       Exprs.append(Message->arg_begin(), Message->arg_end());
13018   } while (!Exprs.empty());
13019 }
13020 
13021 namespace {
13022 
13023 /// Visitor for expressions which looks for unsequenced operations on the
13024 /// same object.
13025 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13026   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13027 
13028   /// A tree of sequenced regions within an expression. Two regions are
13029   /// unsequenced if one is an ancestor or a descendent of the other. When we
13030   /// finish processing an expression with sequencing, such as a comma
13031   /// expression, we fold its tree nodes into its parent, since they are
13032   /// unsequenced with respect to nodes we will visit later.
13033   class SequenceTree {
13034     struct Value {
13035       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13036       unsigned Parent : 31;
13037       unsigned Merged : 1;
13038     };
13039     SmallVector<Value, 8> Values;
13040 
13041   public:
13042     /// A region within an expression which may be sequenced with respect
13043     /// to some other region.
13044     class Seq {
13045       friend class SequenceTree;
13046 
13047       unsigned Index;
13048 
13049       explicit Seq(unsigned N) : Index(N) {}
13050 
13051     public:
13052       Seq() : Index(0) {}
13053     };
13054 
13055     SequenceTree() { Values.push_back(Value(0)); }
13056     Seq root() const { return Seq(0); }
13057 
13058     /// Create a new sequence of operations, which is an unsequenced
13059     /// subset of \p Parent. This sequence of operations is sequenced with
13060     /// respect to other children of \p Parent.
13061     Seq allocate(Seq Parent) {
13062       Values.push_back(Value(Parent.Index));
13063       return Seq(Values.size() - 1);
13064     }
13065 
13066     /// Merge a sequence of operations into its parent.
13067     void merge(Seq S) {
13068       Values[S.Index].Merged = true;
13069     }
13070 
13071     /// Determine whether two operations are unsequenced. This operation
13072     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13073     /// should have been merged into its parent as appropriate.
13074     bool isUnsequenced(Seq Cur, Seq Old) {
13075       unsigned C = representative(Cur.Index);
13076       unsigned Target = representative(Old.Index);
13077       while (C >= Target) {
13078         if (C == Target)
13079           return true;
13080         C = Values[C].Parent;
13081       }
13082       return false;
13083     }
13084 
13085   private:
13086     /// Pick a representative for a sequence.
13087     unsigned representative(unsigned K) {
13088       if (Values[K].Merged)
13089         // Perform path compression as we go.
13090         return Values[K].Parent = representative(Values[K].Parent);
13091       return K;
13092     }
13093   };
13094 
13095   /// An object for which we can track unsequenced uses.
13096   using Object = const NamedDecl *;
13097 
13098   /// Different flavors of object usage which we track. We only track the
13099   /// least-sequenced usage of each kind.
13100   enum UsageKind {
13101     /// A read of an object. Multiple unsequenced reads are OK.
13102     UK_Use,
13103 
13104     /// A modification of an object which is sequenced before the value
13105     /// computation of the expression, such as ++n in C++.
13106     UK_ModAsValue,
13107 
13108     /// A modification of an object which is not sequenced before the value
13109     /// computation of the expression, such as n++.
13110     UK_ModAsSideEffect,
13111 
13112     UK_Count = UK_ModAsSideEffect + 1
13113   };
13114 
13115   /// Bundle together a sequencing region and the expression corresponding
13116   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13117   struct Usage {
13118     const Expr *UsageExpr;
13119     SequenceTree::Seq Seq;
13120 
13121     Usage() : UsageExpr(nullptr), Seq() {}
13122   };
13123 
13124   struct UsageInfo {
13125     Usage Uses[UK_Count];
13126 
13127     /// Have we issued a diagnostic for this object already?
13128     bool Diagnosed;
13129 
13130     UsageInfo() : Uses(), Diagnosed(false) {}
13131   };
13132   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13133 
13134   Sema &SemaRef;
13135 
13136   /// Sequenced regions within the expression.
13137   SequenceTree Tree;
13138 
13139   /// Declaration modifications and references which we have seen.
13140   UsageInfoMap UsageMap;
13141 
13142   /// The region we are currently within.
13143   SequenceTree::Seq Region;
13144 
13145   /// Filled in with declarations which were modified as a side-effect
13146   /// (that is, post-increment operations).
13147   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13148 
13149   /// Expressions to check later. We defer checking these to reduce
13150   /// stack usage.
13151   SmallVectorImpl<const Expr *> &WorkList;
13152 
13153   /// RAII object wrapping the visitation of a sequenced subexpression of an
13154   /// expression. At the end of this process, the side-effects of the evaluation
13155   /// become sequenced with respect to the value computation of the result, so
13156   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13157   /// UK_ModAsValue.
13158   struct SequencedSubexpression {
13159     SequencedSubexpression(SequenceChecker &Self)
13160       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13161       Self.ModAsSideEffect = &ModAsSideEffect;
13162     }
13163 
13164     ~SequencedSubexpression() {
13165       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13166         // Add a new usage with usage kind UK_ModAsValue, and then restore
13167         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13168         // the previous one was empty).
13169         UsageInfo &UI = Self.UsageMap[M.first];
13170         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13171         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13172         SideEffectUsage = M.second;
13173       }
13174       Self.ModAsSideEffect = OldModAsSideEffect;
13175     }
13176 
13177     SequenceChecker &Self;
13178     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13179     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13180   };
13181 
13182   /// RAII object wrapping the visitation of a subexpression which we might
13183   /// choose to evaluate as a constant. If any subexpression is evaluated and
13184   /// found to be non-constant, this allows us to suppress the evaluation of
13185   /// the outer expression.
13186   class EvaluationTracker {
13187   public:
13188     EvaluationTracker(SequenceChecker &Self)
13189         : Self(Self), Prev(Self.EvalTracker) {
13190       Self.EvalTracker = this;
13191     }
13192 
13193     ~EvaluationTracker() {
13194       Self.EvalTracker = Prev;
13195       if (Prev)
13196         Prev->EvalOK &= EvalOK;
13197     }
13198 
13199     bool evaluate(const Expr *E, bool &Result) {
13200       if (!EvalOK || E->isValueDependent())
13201         return false;
13202       EvalOK = E->EvaluateAsBooleanCondition(
13203           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13204       return EvalOK;
13205     }
13206 
13207   private:
13208     SequenceChecker &Self;
13209     EvaluationTracker *Prev;
13210     bool EvalOK = true;
13211   } *EvalTracker = nullptr;
13212 
13213   /// Find the object which is produced by the specified expression,
13214   /// if any.
13215   Object getObject(const Expr *E, bool Mod) const {
13216     E = E->IgnoreParenCasts();
13217     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13218       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13219         return getObject(UO->getSubExpr(), Mod);
13220     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13221       if (BO->getOpcode() == BO_Comma)
13222         return getObject(BO->getRHS(), Mod);
13223       if (Mod && BO->isAssignmentOp())
13224         return getObject(BO->getLHS(), Mod);
13225     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13226       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13227       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13228         return ME->getMemberDecl();
13229     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13230       // FIXME: If this is a reference, map through to its value.
13231       return DRE->getDecl();
13232     return nullptr;
13233   }
13234 
13235   /// Note that an object \p O was modified or used by an expression
13236   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13237   /// the object \p O as obtained via the \p UsageMap.
13238   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13239     // Get the old usage for the given object and usage kind.
13240     Usage &U = UI.Uses[UK];
13241     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13242       // If we have a modification as side effect and are in a sequenced
13243       // subexpression, save the old Usage so that we can restore it later
13244       // in SequencedSubexpression::~SequencedSubexpression.
13245       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13246         ModAsSideEffect->push_back(std::make_pair(O, U));
13247       // Then record the new usage with the current sequencing region.
13248       U.UsageExpr = UsageExpr;
13249       U.Seq = Region;
13250     }
13251   }
13252 
13253   /// Check whether a modification or use of an object \p O in an expression
13254   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13255   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13256   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13257   /// usage and false we are checking for a mod-use unsequenced usage.
13258   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13259                   UsageKind OtherKind, bool IsModMod) {
13260     if (UI.Diagnosed)
13261       return;
13262 
13263     const Usage &U = UI.Uses[OtherKind];
13264     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13265       return;
13266 
13267     const Expr *Mod = U.UsageExpr;
13268     const Expr *ModOrUse = UsageExpr;
13269     if (OtherKind == UK_Use)
13270       std::swap(Mod, ModOrUse);
13271 
13272     SemaRef.DiagRuntimeBehavior(
13273         Mod->getExprLoc(), {Mod, ModOrUse},
13274         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13275                                : diag::warn_unsequenced_mod_use)
13276             << O << SourceRange(ModOrUse->getExprLoc()));
13277     UI.Diagnosed = true;
13278   }
13279 
13280   // A note on note{Pre, Post}{Use, Mod}:
13281   //
13282   // (It helps to follow the algorithm with an expression such as
13283   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13284   //  operations before C++17 and both are well-defined in C++17).
13285   //
13286   // When visiting a node which uses/modify an object we first call notePreUse
13287   // or notePreMod before visiting its sub-expression(s). At this point the
13288   // children of the current node have not yet been visited and so the eventual
13289   // uses/modifications resulting from the children of the current node have not
13290   // been recorded yet.
13291   //
13292   // We then visit the children of the current node. After that notePostUse or
13293   // notePostMod is called. These will 1) detect an unsequenced modification
13294   // as side effect (as in "k++ + k") and 2) add a new usage with the
13295   // appropriate usage kind.
13296   //
13297   // We also have to be careful that some operation sequences modification as
13298   // side effect as well (for example: || or ,). To account for this we wrap
13299   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13300   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13301   // which record usages which are modifications as side effect, and then
13302   // downgrade them (or more accurately restore the previous usage which was a
13303   // modification as side effect) when exiting the scope of the sequenced
13304   // subexpression.
13305 
13306   void notePreUse(Object O, const Expr *UseExpr) {
13307     UsageInfo &UI = UsageMap[O];
13308     // Uses conflict with other modifications.
13309     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13310   }
13311 
13312   void notePostUse(Object O, const Expr *UseExpr) {
13313     UsageInfo &UI = UsageMap[O];
13314     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13315                /*IsModMod=*/false);
13316     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13317   }
13318 
13319   void notePreMod(Object O, const Expr *ModExpr) {
13320     UsageInfo &UI = UsageMap[O];
13321     // Modifications conflict with other modifications and with uses.
13322     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13323     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13324   }
13325 
13326   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13327     UsageInfo &UI = UsageMap[O];
13328     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13329                /*IsModMod=*/true);
13330     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13331   }
13332 
13333 public:
13334   SequenceChecker(Sema &S, const Expr *E,
13335                   SmallVectorImpl<const Expr *> &WorkList)
13336       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13337     Visit(E);
13338     // Silence a -Wunused-private-field since WorkList is now unused.
13339     // TODO: Evaluate if it can be used, and if not remove it.
13340     (void)this->WorkList;
13341   }
13342 
13343   void VisitStmt(const Stmt *S) {
13344     // Skip all statements which aren't expressions for now.
13345   }
13346 
13347   void VisitExpr(const Expr *E) {
13348     // By default, just recurse to evaluated subexpressions.
13349     Base::VisitStmt(E);
13350   }
13351 
13352   void VisitCastExpr(const CastExpr *E) {
13353     Object O = Object();
13354     if (E->getCastKind() == CK_LValueToRValue)
13355       O = getObject(E->getSubExpr(), false);
13356 
13357     if (O)
13358       notePreUse(O, E);
13359     VisitExpr(E);
13360     if (O)
13361       notePostUse(O, E);
13362   }
13363 
13364   void VisitSequencedExpressions(const Expr *SequencedBefore,
13365                                  const Expr *SequencedAfter) {
13366     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13367     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13368     SequenceTree::Seq OldRegion = Region;
13369 
13370     {
13371       SequencedSubexpression SeqBefore(*this);
13372       Region = BeforeRegion;
13373       Visit(SequencedBefore);
13374     }
13375 
13376     Region = AfterRegion;
13377     Visit(SequencedAfter);
13378 
13379     Region = OldRegion;
13380 
13381     Tree.merge(BeforeRegion);
13382     Tree.merge(AfterRegion);
13383   }
13384 
13385   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13386     // C++17 [expr.sub]p1:
13387     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13388     //   expression E1 is sequenced before the expression E2.
13389     if (SemaRef.getLangOpts().CPlusPlus17)
13390       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13391     else {
13392       Visit(ASE->getLHS());
13393       Visit(ASE->getRHS());
13394     }
13395   }
13396 
13397   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13398   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13399   void VisitBinPtrMem(const BinaryOperator *BO) {
13400     // C++17 [expr.mptr.oper]p4:
13401     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13402     //  the expression E1 is sequenced before the expression E2.
13403     if (SemaRef.getLangOpts().CPlusPlus17)
13404       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13405     else {
13406       Visit(BO->getLHS());
13407       Visit(BO->getRHS());
13408     }
13409   }
13410 
13411   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13412   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13413   void VisitBinShlShr(const BinaryOperator *BO) {
13414     // C++17 [expr.shift]p4:
13415     //  The expression E1 is sequenced before the expression E2.
13416     if (SemaRef.getLangOpts().CPlusPlus17)
13417       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13418     else {
13419       Visit(BO->getLHS());
13420       Visit(BO->getRHS());
13421     }
13422   }
13423 
13424   void VisitBinComma(const BinaryOperator *BO) {
13425     // C++11 [expr.comma]p1:
13426     //   Every value computation and side effect associated with the left
13427     //   expression is sequenced before every value computation and side
13428     //   effect associated with the right expression.
13429     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13430   }
13431 
13432   void VisitBinAssign(const BinaryOperator *BO) {
13433     SequenceTree::Seq RHSRegion;
13434     SequenceTree::Seq LHSRegion;
13435     if (SemaRef.getLangOpts().CPlusPlus17) {
13436       RHSRegion = Tree.allocate(Region);
13437       LHSRegion = Tree.allocate(Region);
13438     } else {
13439       RHSRegion = Region;
13440       LHSRegion = Region;
13441     }
13442     SequenceTree::Seq OldRegion = Region;
13443 
13444     // C++11 [expr.ass]p1:
13445     //  [...] the assignment is sequenced after the value computation
13446     //  of the right and left operands, [...]
13447     //
13448     // so check it before inspecting the operands and update the
13449     // map afterwards.
13450     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13451     if (O)
13452       notePreMod(O, BO);
13453 
13454     if (SemaRef.getLangOpts().CPlusPlus17) {
13455       // C++17 [expr.ass]p1:
13456       //  [...] The right operand is sequenced before the left operand. [...]
13457       {
13458         SequencedSubexpression SeqBefore(*this);
13459         Region = RHSRegion;
13460         Visit(BO->getRHS());
13461       }
13462 
13463       Region = LHSRegion;
13464       Visit(BO->getLHS());
13465 
13466       if (O && isa<CompoundAssignOperator>(BO))
13467         notePostUse(O, BO);
13468 
13469     } else {
13470       // C++11 does not specify any sequencing between the LHS and RHS.
13471       Region = LHSRegion;
13472       Visit(BO->getLHS());
13473 
13474       if (O && isa<CompoundAssignOperator>(BO))
13475         notePostUse(O, BO);
13476 
13477       Region = RHSRegion;
13478       Visit(BO->getRHS());
13479     }
13480 
13481     // C++11 [expr.ass]p1:
13482     //  the assignment is sequenced [...] before the value computation of the
13483     //  assignment expression.
13484     // C11 6.5.16/3 has no such rule.
13485     Region = OldRegion;
13486     if (O)
13487       notePostMod(O, BO,
13488                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13489                                                   : UK_ModAsSideEffect);
13490     if (SemaRef.getLangOpts().CPlusPlus17) {
13491       Tree.merge(RHSRegion);
13492       Tree.merge(LHSRegion);
13493     }
13494   }
13495 
13496   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13497     VisitBinAssign(CAO);
13498   }
13499 
13500   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13501   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13502   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13503     Object O = getObject(UO->getSubExpr(), true);
13504     if (!O)
13505       return VisitExpr(UO);
13506 
13507     notePreMod(O, UO);
13508     Visit(UO->getSubExpr());
13509     // C++11 [expr.pre.incr]p1:
13510     //   the expression ++x is equivalent to x+=1
13511     notePostMod(O, UO,
13512                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13513                                                 : UK_ModAsSideEffect);
13514   }
13515 
13516   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13517   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13518   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13519     Object O = getObject(UO->getSubExpr(), true);
13520     if (!O)
13521       return VisitExpr(UO);
13522 
13523     notePreMod(O, UO);
13524     Visit(UO->getSubExpr());
13525     notePostMod(O, UO, UK_ModAsSideEffect);
13526   }
13527 
13528   void VisitBinLOr(const BinaryOperator *BO) {
13529     // C++11 [expr.log.or]p2:
13530     //  If the second expression is evaluated, every value computation and
13531     //  side effect associated with the first expression is sequenced before
13532     //  every value computation and side effect associated with the
13533     //  second expression.
13534     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13535     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13536     SequenceTree::Seq OldRegion = Region;
13537 
13538     EvaluationTracker Eval(*this);
13539     {
13540       SequencedSubexpression Sequenced(*this);
13541       Region = LHSRegion;
13542       Visit(BO->getLHS());
13543     }
13544 
13545     // C++11 [expr.log.or]p1:
13546     //  [...] the second operand is not evaluated if the first operand
13547     //  evaluates to true.
13548     bool EvalResult = false;
13549     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13550     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13551     if (ShouldVisitRHS) {
13552       Region = RHSRegion;
13553       Visit(BO->getRHS());
13554     }
13555 
13556     Region = OldRegion;
13557     Tree.merge(LHSRegion);
13558     Tree.merge(RHSRegion);
13559   }
13560 
13561   void VisitBinLAnd(const BinaryOperator *BO) {
13562     // C++11 [expr.log.and]p2:
13563     //  If the second expression is evaluated, every value computation and
13564     //  side effect associated with the first expression is sequenced before
13565     //  every value computation and side effect associated with the
13566     //  second expression.
13567     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13568     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13569     SequenceTree::Seq OldRegion = Region;
13570 
13571     EvaluationTracker Eval(*this);
13572     {
13573       SequencedSubexpression Sequenced(*this);
13574       Region = LHSRegion;
13575       Visit(BO->getLHS());
13576     }
13577 
13578     // C++11 [expr.log.and]p1:
13579     //  [...] the second operand is not evaluated if the first operand is false.
13580     bool EvalResult = false;
13581     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13582     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13583     if (ShouldVisitRHS) {
13584       Region = RHSRegion;
13585       Visit(BO->getRHS());
13586     }
13587 
13588     Region = OldRegion;
13589     Tree.merge(LHSRegion);
13590     Tree.merge(RHSRegion);
13591   }
13592 
13593   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13594     // C++11 [expr.cond]p1:
13595     //  [...] Every value computation and side effect associated with the first
13596     //  expression is sequenced before every value computation and side effect
13597     //  associated with the second or third expression.
13598     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13599 
13600     // No sequencing is specified between the true and false expression.
13601     // However since exactly one of both is going to be evaluated we can
13602     // consider them to be sequenced. This is needed to avoid warning on
13603     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13604     // both the true and false expressions because we can't evaluate x.
13605     // This will still allow us to detect an expression like (pre C++17)
13606     // "(x ? y += 1 : y += 2) = y".
13607     //
13608     // We don't wrap the visitation of the true and false expression with
13609     // SequencedSubexpression because we don't want to downgrade modifications
13610     // as side effect in the true and false expressions after the visition
13611     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13612     // not warn between the two "y++", but we should warn between the "y++"
13613     // and the "y".
13614     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13615     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13616     SequenceTree::Seq OldRegion = Region;
13617 
13618     EvaluationTracker Eval(*this);
13619     {
13620       SequencedSubexpression Sequenced(*this);
13621       Region = ConditionRegion;
13622       Visit(CO->getCond());
13623     }
13624 
13625     // C++11 [expr.cond]p1:
13626     // [...] The first expression is contextually converted to bool (Clause 4).
13627     // It is evaluated and if it is true, the result of the conditional
13628     // expression is the value of the second expression, otherwise that of the
13629     // third expression. Only one of the second and third expressions is
13630     // evaluated. [...]
13631     bool EvalResult = false;
13632     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13633     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13634     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13635     if (ShouldVisitTrueExpr) {
13636       Region = TrueRegion;
13637       Visit(CO->getTrueExpr());
13638     }
13639     if (ShouldVisitFalseExpr) {
13640       Region = FalseRegion;
13641       Visit(CO->getFalseExpr());
13642     }
13643 
13644     Region = OldRegion;
13645     Tree.merge(ConditionRegion);
13646     Tree.merge(TrueRegion);
13647     Tree.merge(FalseRegion);
13648   }
13649 
13650   void VisitCallExpr(const CallExpr *CE) {
13651     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13652 
13653     if (CE->isUnevaluatedBuiltinCall(Context))
13654       return;
13655 
13656     // C++11 [intro.execution]p15:
13657     //   When calling a function [...], every value computation and side effect
13658     //   associated with any argument expression, or with the postfix expression
13659     //   designating the called function, is sequenced before execution of every
13660     //   expression or statement in the body of the function [and thus before
13661     //   the value computation of its result].
13662     SequencedSubexpression Sequenced(*this);
13663     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13664       // C++17 [expr.call]p5
13665       //   The postfix-expression is sequenced before each expression in the
13666       //   expression-list and any default argument. [...]
13667       SequenceTree::Seq CalleeRegion;
13668       SequenceTree::Seq OtherRegion;
13669       if (SemaRef.getLangOpts().CPlusPlus17) {
13670         CalleeRegion = Tree.allocate(Region);
13671         OtherRegion = Tree.allocate(Region);
13672       } else {
13673         CalleeRegion = Region;
13674         OtherRegion = Region;
13675       }
13676       SequenceTree::Seq OldRegion = Region;
13677 
13678       // Visit the callee expression first.
13679       Region = CalleeRegion;
13680       if (SemaRef.getLangOpts().CPlusPlus17) {
13681         SequencedSubexpression Sequenced(*this);
13682         Visit(CE->getCallee());
13683       } else {
13684         Visit(CE->getCallee());
13685       }
13686 
13687       // Then visit the argument expressions.
13688       Region = OtherRegion;
13689       for (const Expr *Argument : CE->arguments())
13690         Visit(Argument);
13691 
13692       Region = OldRegion;
13693       if (SemaRef.getLangOpts().CPlusPlus17) {
13694         Tree.merge(CalleeRegion);
13695         Tree.merge(OtherRegion);
13696       }
13697     });
13698   }
13699 
13700   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13701     // C++17 [over.match.oper]p2:
13702     //   [...] the operator notation is first transformed to the equivalent
13703     //   function-call notation as summarized in Table 12 (where @ denotes one
13704     //   of the operators covered in the specified subclause). However, the
13705     //   operands are sequenced in the order prescribed for the built-in
13706     //   operator (Clause 8).
13707     //
13708     // From the above only overloaded binary operators and overloaded call
13709     // operators have sequencing rules in C++17 that we need to handle
13710     // separately.
13711     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13712         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13713       return VisitCallExpr(CXXOCE);
13714 
13715     enum {
13716       NoSequencing,
13717       LHSBeforeRHS,
13718       RHSBeforeLHS,
13719       LHSBeforeRest
13720     } SequencingKind;
13721     switch (CXXOCE->getOperator()) {
13722     case OO_Equal:
13723     case OO_PlusEqual:
13724     case OO_MinusEqual:
13725     case OO_StarEqual:
13726     case OO_SlashEqual:
13727     case OO_PercentEqual:
13728     case OO_CaretEqual:
13729     case OO_AmpEqual:
13730     case OO_PipeEqual:
13731     case OO_LessLessEqual:
13732     case OO_GreaterGreaterEqual:
13733       SequencingKind = RHSBeforeLHS;
13734       break;
13735 
13736     case OO_LessLess:
13737     case OO_GreaterGreater:
13738     case OO_AmpAmp:
13739     case OO_PipePipe:
13740     case OO_Comma:
13741     case OO_ArrowStar:
13742     case OO_Subscript:
13743       SequencingKind = LHSBeforeRHS;
13744       break;
13745 
13746     case OO_Call:
13747       SequencingKind = LHSBeforeRest;
13748       break;
13749 
13750     default:
13751       SequencingKind = NoSequencing;
13752       break;
13753     }
13754 
13755     if (SequencingKind == NoSequencing)
13756       return VisitCallExpr(CXXOCE);
13757 
13758     // This is a call, so all subexpressions are sequenced before the result.
13759     SequencedSubexpression Sequenced(*this);
13760 
13761     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13762       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13763              "Should only get there with C++17 and above!");
13764       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13765              "Should only get there with an overloaded binary operator"
13766              " or an overloaded call operator!");
13767 
13768       if (SequencingKind == LHSBeforeRest) {
13769         assert(CXXOCE->getOperator() == OO_Call &&
13770                "We should only have an overloaded call operator here!");
13771 
13772         // This is very similar to VisitCallExpr, except that we only have the
13773         // C++17 case. The postfix-expression is the first argument of the
13774         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13775         // are in the following arguments.
13776         //
13777         // Note that we intentionally do not visit the callee expression since
13778         // it is just a decayed reference to a function.
13779         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13780         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13781         SequenceTree::Seq OldRegion = Region;
13782 
13783         assert(CXXOCE->getNumArgs() >= 1 &&
13784                "An overloaded call operator must have at least one argument"
13785                " for the postfix-expression!");
13786         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13787         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13788                                           CXXOCE->getNumArgs() - 1);
13789 
13790         // Visit the postfix-expression first.
13791         {
13792           Region = PostfixExprRegion;
13793           SequencedSubexpression Sequenced(*this);
13794           Visit(PostfixExpr);
13795         }
13796 
13797         // Then visit the argument expressions.
13798         Region = ArgsRegion;
13799         for (const Expr *Arg : Args)
13800           Visit(Arg);
13801 
13802         Region = OldRegion;
13803         Tree.merge(PostfixExprRegion);
13804         Tree.merge(ArgsRegion);
13805       } else {
13806         assert(CXXOCE->getNumArgs() == 2 &&
13807                "Should only have two arguments here!");
13808         assert((SequencingKind == LHSBeforeRHS ||
13809                 SequencingKind == RHSBeforeLHS) &&
13810                "Unexpected sequencing kind!");
13811 
13812         // We do not visit the callee expression since it is just a decayed
13813         // reference to a function.
13814         const Expr *E1 = CXXOCE->getArg(0);
13815         const Expr *E2 = CXXOCE->getArg(1);
13816         if (SequencingKind == RHSBeforeLHS)
13817           std::swap(E1, E2);
13818 
13819         return VisitSequencedExpressions(E1, E2);
13820       }
13821     });
13822   }
13823 
13824   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13825     // This is a call, so all subexpressions are sequenced before the result.
13826     SequencedSubexpression Sequenced(*this);
13827 
13828     if (!CCE->isListInitialization())
13829       return VisitExpr(CCE);
13830 
13831     // In C++11, list initializations are sequenced.
13832     SmallVector<SequenceTree::Seq, 32> Elts;
13833     SequenceTree::Seq Parent = Region;
13834     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13835                                               E = CCE->arg_end();
13836          I != E; ++I) {
13837       Region = Tree.allocate(Parent);
13838       Elts.push_back(Region);
13839       Visit(*I);
13840     }
13841 
13842     // Forget that the initializers are sequenced.
13843     Region = Parent;
13844     for (unsigned I = 0; I < Elts.size(); ++I)
13845       Tree.merge(Elts[I]);
13846   }
13847 
13848   void VisitInitListExpr(const InitListExpr *ILE) {
13849     if (!SemaRef.getLangOpts().CPlusPlus11)
13850       return VisitExpr(ILE);
13851 
13852     // In C++11, list initializations are sequenced.
13853     SmallVector<SequenceTree::Seq, 32> Elts;
13854     SequenceTree::Seq Parent = Region;
13855     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13856       const Expr *E = ILE->getInit(I);
13857       if (!E)
13858         continue;
13859       Region = Tree.allocate(Parent);
13860       Elts.push_back(Region);
13861       Visit(E);
13862     }
13863 
13864     // Forget that the initializers are sequenced.
13865     Region = Parent;
13866     for (unsigned I = 0; I < Elts.size(); ++I)
13867       Tree.merge(Elts[I]);
13868   }
13869 };
13870 
13871 } // namespace
13872 
13873 void Sema::CheckUnsequencedOperations(const Expr *E) {
13874   SmallVector<const Expr *, 8> WorkList;
13875   WorkList.push_back(E);
13876   while (!WorkList.empty()) {
13877     const Expr *Item = WorkList.pop_back_val();
13878     SequenceChecker(*this, Item, WorkList);
13879   }
13880 }
13881 
13882 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13883                               bool IsConstexpr) {
13884   llvm::SaveAndRestore<bool> ConstantContext(
13885       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13886   CheckImplicitConversions(E, CheckLoc);
13887   if (!E->isInstantiationDependent())
13888     CheckUnsequencedOperations(E);
13889   if (!IsConstexpr && !E->isValueDependent())
13890     CheckForIntOverflow(E);
13891   DiagnoseMisalignedMembers();
13892 }
13893 
13894 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13895                                        FieldDecl *BitField,
13896                                        Expr *Init) {
13897   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13898 }
13899 
13900 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13901                                          SourceLocation Loc) {
13902   if (!PType->isVariablyModifiedType())
13903     return;
13904   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13905     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13906     return;
13907   }
13908   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13909     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13910     return;
13911   }
13912   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13913     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13914     return;
13915   }
13916 
13917   const ArrayType *AT = S.Context.getAsArrayType(PType);
13918   if (!AT)
13919     return;
13920 
13921   if (AT->getSizeModifier() != ArrayType::Star) {
13922     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13923     return;
13924   }
13925 
13926   S.Diag(Loc, diag::err_array_star_in_function_definition);
13927 }
13928 
13929 /// CheckParmsForFunctionDef - Check that the parameters of the given
13930 /// function are appropriate for the definition of a function. This
13931 /// takes care of any checks that cannot be performed on the
13932 /// declaration itself, e.g., that the types of each of the function
13933 /// parameters are complete.
13934 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13935                                     bool CheckParameterNames) {
13936   bool HasInvalidParm = false;
13937   for (ParmVarDecl *Param : Parameters) {
13938     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13939     // function declarator that is part of a function definition of
13940     // that function shall not have incomplete type.
13941     //
13942     // This is also C++ [dcl.fct]p6.
13943     if (!Param->isInvalidDecl() &&
13944         RequireCompleteType(Param->getLocation(), Param->getType(),
13945                             diag::err_typecheck_decl_incomplete_type)) {
13946       Param->setInvalidDecl();
13947       HasInvalidParm = true;
13948     }
13949 
13950     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13951     // declaration of each parameter shall include an identifier.
13952     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13953         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13954       // Diagnose this as an extension in C17 and earlier.
13955       if (!getLangOpts().C2x)
13956         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13957     }
13958 
13959     // C99 6.7.5.3p12:
13960     //   If the function declarator is not part of a definition of that
13961     //   function, parameters may have incomplete type and may use the [*]
13962     //   notation in their sequences of declarator specifiers to specify
13963     //   variable length array types.
13964     QualType PType = Param->getOriginalType();
13965     // FIXME: This diagnostic should point the '[*]' if source-location
13966     // information is added for it.
13967     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13968 
13969     // If the parameter is a c++ class type and it has to be destructed in the
13970     // callee function, declare the destructor so that it can be called by the
13971     // callee function. Do not perform any direct access check on the dtor here.
13972     if (!Param->isInvalidDecl()) {
13973       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13974         if (!ClassDecl->isInvalidDecl() &&
13975             !ClassDecl->hasIrrelevantDestructor() &&
13976             !ClassDecl->isDependentContext() &&
13977             ClassDecl->isParamDestroyedInCallee()) {
13978           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13979           MarkFunctionReferenced(Param->getLocation(), Destructor);
13980           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13981         }
13982       }
13983     }
13984 
13985     // Parameters with the pass_object_size attribute only need to be marked
13986     // constant at function definitions. Because we lack information about
13987     // whether we're on a declaration or definition when we're instantiating the
13988     // attribute, we need to check for constness here.
13989     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13990       if (!Param->getType().isConstQualified())
13991         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13992             << Attr->getSpelling() << 1;
13993 
13994     // Check for parameter names shadowing fields from the class.
13995     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13996       // The owning context for the parameter should be the function, but we
13997       // want to see if this function's declaration context is a record.
13998       DeclContext *DC = Param->getDeclContext();
13999       if (DC && DC->isFunctionOrMethod()) {
14000         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14001           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14002                                      RD, /*DeclIsField*/ false);
14003       }
14004     }
14005   }
14006 
14007   return HasInvalidParm;
14008 }
14009 
14010 Optional<std::pair<CharUnits, CharUnits>>
14011 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14012 
14013 /// Compute the alignment and offset of the base class object given the
14014 /// derived-to-base cast expression and the alignment and offset of the derived
14015 /// class object.
14016 static std::pair<CharUnits, CharUnits>
14017 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14018                                    CharUnits BaseAlignment, CharUnits Offset,
14019                                    ASTContext &Ctx) {
14020   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14021        ++PathI) {
14022     const CXXBaseSpecifier *Base = *PathI;
14023     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14024     if (Base->isVirtual()) {
14025       // The complete object may have a lower alignment than the non-virtual
14026       // alignment of the base, in which case the base may be misaligned. Choose
14027       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14028       // conservative lower bound of the complete object alignment.
14029       CharUnits NonVirtualAlignment =
14030           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14031       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14032       Offset = CharUnits::Zero();
14033     } else {
14034       const ASTRecordLayout &RL =
14035           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14036       Offset += RL.getBaseClassOffset(BaseDecl);
14037     }
14038     DerivedType = Base->getType();
14039   }
14040 
14041   return std::make_pair(BaseAlignment, Offset);
14042 }
14043 
14044 /// Compute the alignment and offset of a binary additive operator.
14045 static Optional<std::pair<CharUnits, CharUnits>>
14046 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14047                                      bool IsSub, ASTContext &Ctx) {
14048   QualType PointeeType = PtrE->getType()->getPointeeType();
14049 
14050   if (!PointeeType->isConstantSizeType())
14051     return llvm::None;
14052 
14053   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14054 
14055   if (!P)
14056     return llvm::None;
14057 
14058   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14059   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14060     CharUnits Offset = EltSize * IdxRes->getExtValue();
14061     if (IsSub)
14062       Offset = -Offset;
14063     return std::make_pair(P->first, P->second + Offset);
14064   }
14065 
14066   // If the integer expression isn't a constant expression, compute the lower
14067   // bound of the alignment using the alignment and offset of the pointer
14068   // expression and the element size.
14069   return std::make_pair(
14070       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14071       CharUnits::Zero());
14072 }
14073 
14074 /// This helper function takes an lvalue expression and returns the alignment of
14075 /// a VarDecl and a constant offset from the VarDecl.
14076 Optional<std::pair<CharUnits, CharUnits>>
14077 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14078   E = E->IgnoreParens();
14079   switch (E->getStmtClass()) {
14080   default:
14081     break;
14082   case Stmt::CStyleCastExprClass:
14083   case Stmt::CXXStaticCastExprClass:
14084   case Stmt::ImplicitCastExprClass: {
14085     auto *CE = cast<CastExpr>(E);
14086     const Expr *From = CE->getSubExpr();
14087     switch (CE->getCastKind()) {
14088     default:
14089       break;
14090     case CK_NoOp:
14091       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14092     case CK_UncheckedDerivedToBase:
14093     case CK_DerivedToBase: {
14094       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14095       if (!P)
14096         break;
14097       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14098                                                 P->second, Ctx);
14099     }
14100     }
14101     break;
14102   }
14103   case Stmt::ArraySubscriptExprClass: {
14104     auto *ASE = cast<ArraySubscriptExpr>(E);
14105     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14106                                                 false, Ctx);
14107   }
14108   case Stmt::DeclRefExprClass: {
14109     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14110       // FIXME: If VD is captured by copy or is an escaping __block variable,
14111       // use the alignment of VD's type.
14112       if (!VD->getType()->isReferenceType())
14113         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14114       if (VD->hasInit())
14115         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14116     }
14117     break;
14118   }
14119   case Stmt::MemberExprClass: {
14120     auto *ME = cast<MemberExpr>(E);
14121     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14122     if (!FD || FD->getType()->isReferenceType())
14123       break;
14124     Optional<std::pair<CharUnits, CharUnits>> P;
14125     if (ME->isArrow())
14126       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14127     else
14128       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14129     if (!P)
14130       break;
14131     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14132     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14133     return std::make_pair(P->first,
14134                           P->second + CharUnits::fromQuantity(Offset));
14135   }
14136   case Stmt::UnaryOperatorClass: {
14137     auto *UO = cast<UnaryOperator>(E);
14138     switch (UO->getOpcode()) {
14139     default:
14140       break;
14141     case UO_Deref:
14142       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14143     }
14144     break;
14145   }
14146   case Stmt::BinaryOperatorClass: {
14147     auto *BO = cast<BinaryOperator>(E);
14148     auto Opcode = BO->getOpcode();
14149     switch (Opcode) {
14150     default:
14151       break;
14152     case BO_Comma:
14153       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14154     }
14155     break;
14156   }
14157   }
14158   return llvm::None;
14159 }
14160 
14161 /// This helper function takes a pointer expression and returns the alignment of
14162 /// a VarDecl and a constant offset from the VarDecl.
14163 Optional<std::pair<CharUnits, CharUnits>>
14164 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14165   E = E->IgnoreParens();
14166   switch (E->getStmtClass()) {
14167   default:
14168     break;
14169   case Stmt::CStyleCastExprClass:
14170   case Stmt::CXXStaticCastExprClass:
14171   case Stmt::ImplicitCastExprClass: {
14172     auto *CE = cast<CastExpr>(E);
14173     const Expr *From = CE->getSubExpr();
14174     switch (CE->getCastKind()) {
14175     default:
14176       break;
14177     case CK_NoOp:
14178       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14179     case CK_ArrayToPointerDecay:
14180       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14181     case CK_UncheckedDerivedToBase:
14182     case CK_DerivedToBase: {
14183       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14184       if (!P)
14185         break;
14186       return getDerivedToBaseAlignmentAndOffset(
14187           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14188     }
14189     }
14190     break;
14191   }
14192   case Stmt::CXXThisExprClass: {
14193     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14194     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14195     return std::make_pair(Alignment, CharUnits::Zero());
14196   }
14197   case Stmt::UnaryOperatorClass: {
14198     auto *UO = cast<UnaryOperator>(E);
14199     if (UO->getOpcode() == UO_AddrOf)
14200       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14201     break;
14202   }
14203   case Stmt::BinaryOperatorClass: {
14204     auto *BO = cast<BinaryOperator>(E);
14205     auto Opcode = BO->getOpcode();
14206     switch (Opcode) {
14207     default:
14208       break;
14209     case BO_Add:
14210     case BO_Sub: {
14211       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14212       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14213         std::swap(LHS, RHS);
14214       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14215                                                   Ctx);
14216     }
14217     case BO_Comma:
14218       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14219     }
14220     break;
14221   }
14222   }
14223   return llvm::None;
14224 }
14225 
14226 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14227   // See if we can compute the alignment of a VarDecl and an offset from it.
14228   Optional<std::pair<CharUnits, CharUnits>> P =
14229       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14230 
14231   if (P)
14232     return P->first.alignmentAtOffset(P->second);
14233 
14234   // If that failed, return the type's alignment.
14235   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14236 }
14237 
14238 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14239 /// pointer cast increases the alignment requirements.
14240 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14241   // This is actually a lot of work to potentially be doing on every
14242   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14243   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14244     return;
14245 
14246   // Ignore dependent types.
14247   if (T->isDependentType() || Op->getType()->isDependentType())
14248     return;
14249 
14250   // Require that the destination be a pointer type.
14251   const PointerType *DestPtr = T->getAs<PointerType>();
14252   if (!DestPtr) return;
14253 
14254   // If the destination has alignment 1, we're done.
14255   QualType DestPointee = DestPtr->getPointeeType();
14256   if (DestPointee->isIncompleteType()) return;
14257   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14258   if (DestAlign.isOne()) return;
14259 
14260   // Require that the source be a pointer type.
14261   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14262   if (!SrcPtr) return;
14263   QualType SrcPointee = SrcPtr->getPointeeType();
14264 
14265   // Explicitly allow casts from cv void*.  We already implicitly
14266   // allowed casts to cv void*, since they have alignment 1.
14267   // Also allow casts involving incomplete types, which implicitly
14268   // includes 'void'.
14269   if (SrcPointee->isIncompleteType()) return;
14270 
14271   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14272 
14273   if (SrcAlign >= DestAlign) return;
14274 
14275   Diag(TRange.getBegin(), diag::warn_cast_align)
14276     << Op->getType() << T
14277     << static_cast<unsigned>(SrcAlign.getQuantity())
14278     << static_cast<unsigned>(DestAlign.getQuantity())
14279     << TRange << Op->getSourceRange();
14280 }
14281 
14282 /// Check whether this array fits the idiom of a size-one tail padded
14283 /// array member of a struct.
14284 ///
14285 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14286 /// commonly used to emulate flexible arrays in C89 code.
14287 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14288                                     const NamedDecl *ND) {
14289   if (Size != 1 || !ND) return false;
14290 
14291   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14292   if (!FD) return false;
14293 
14294   // Don't consider sizes resulting from macro expansions or template argument
14295   // substitution to form C89 tail-padded arrays.
14296 
14297   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14298   while (TInfo) {
14299     TypeLoc TL = TInfo->getTypeLoc();
14300     // Look through typedefs.
14301     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14302       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14303       TInfo = TDL->getTypeSourceInfo();
14304       continue;
14305     }
14306     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14307       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14308       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14309         return false;
14310     }
14311     break;
14312   }
14313 
14314   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14315   if (!RD) return false;
14316   if (RD->isUnion()) return false;
14317   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14318     if (!CRD->isStandardLayout()) return false;
14319   }
14320 
14321   // See if this is the last field decl in the record.
14322   const Decl *D = FD;
14323   while ((D = D->getNextDeclInContext()))
14324     if (isa<FieldDecl>(D))
14325       return false;
14326   return true;
14327 }
14328 
14329 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14330                             const ArraySubscriptExpr *ASE,
14331                             bool AllowOnePastEnd, bool IndexNegated) {
14332   // Already diagnosed by the constant evaluator.
14333   if (isConstantEvaluated())
14334     return;
14335 
14336   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14337   if (IndexExpr->isValueDependent())
14338     return;
14339 
14340   const Type *EffectiveType =
14341       BaseExpr->getType()->getPointeeOrArrayElementType();
14342   BaseExpr = BaseExpr->IgnoreParenCasts();
14343   const ConstantArrayType *ArrayTy =
14344       Context.getAsConstantArrayType(BaseExpr->getType());
14345 
14346   if (!ArrayTy)
14347     return;
14348 
14349   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
14350   if (EffectiveType->isDependentType() || BaseType->isDependentType())
14351     return;
14352 
14353   Expr::EvalResult Result;
14354   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14355     return;
14356 
14357   llvm::APSInt index = Result.Val.getInt();
14358   if (IndexNegated)
14359     index = -index;
14360 
14361   const NamedDecl *ND = nullptr;
14362   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14363     ND = DRE->getDecl();
14364   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14365     ND = ME->getMemberDecl();
14366 
14367   if (index.isUnsigned() || !index.isNegative()) {
14368     // It is possible that the type of the base expression after
14369     // IgnoreParenCasts is incomplete, even though the type of the base
14370     // expression before IgnoreParenCasts is complete (see PR39746 for an
14371     // example). In this case we have no information about whether the array
14372     // access exceeds the array bounds. However we can still diagnose an array
14373     // access which precedes the array bounds.
14374     if (BaseType->isIncompleteType())
14375       return;
14376 
14377     llvm::APInt size = ArrayTy->getSize();
14378     if (!size.isStrictlyPositive())
14379       return;
14380 
14381     if (BaseType != EffectiveType) {
14382       // Make sure we're comparing apples to apples when comparing index to size
14383       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14384       uint64_t array_typesize = Context.getTypeSize(BaseType);
14385       // Handle ptrarith_typesize being zero, such as when casting to void*
14386       if (!ptrarith_typesize) ptrarith_typesize = 1;
14387       if (ptrarith_typesize != array_typesize) {
14388         // There's a cast to a different size type involved
14389         uint64_t ratio = array_typesize / ptrarith_typesize;
14390         // TODO: Be smarter about handling cases where array_typesize is not a
14391         // multiple of ptrarith_typesize
14392         if (ptrarith_typesize * ratio == array_typesize)
14393           size *= llvm::APInt(size.getBitWidth(), ratio);
14394       }
14395     }
14396 
14397     if (size.getBitWidth() > index.getBitWidth())
14398       index = index.zext(size.getBitWidth());
14399     else if (size.getBitWidth() < index.getBitWidth())
14400       size = size.zext(index.getBitWidth());
14401 
14402     // For array subscripting the index must be less than size, but for pointer
14403     // arithmetic also allow the index (offset) to be equal to size since
14404     // computing the next address after the end of the array is legal and
14405     // commonly done e.g. in C++ iterators and range-based for loops.
14406     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14407       return;
14408 
14409     // Also don't warn for arrays of size 1 which are members of some
14410     // structure. These are often used to approximate flexible arrays in C89
14411     // code.
14412     if (IsTailPaddedMemberArray(*this, size, ND))
14413       return;
14414 
14415     // Suppress the warning if the subscript expression (as identified by the
14416     // ']' location) and the index expression are both from macro expansions
14417     // within a system header.
14418     if (ASE) {
14419       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14420           ASE->getRBracketLoc());
14421       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14422         SourceLocation IndexLoc =
14423             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14424         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14425           return;
14426       }
14427     }
14428 
14429     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
14430     if (ASE)
14431       DiagID = diag::warn_array_index_exceeds_bounds;
14432 
14433     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14434                         PDiag(DiagID) << index.toString(10, true)
14435                                       << size.toString(10, true)
14436                                       << (unsigned)size.getLimitedValue(~0U)
14437                                       << IndexExpr->getSourceRange());
14438   } else {
14439     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14440     if (!ASE) {
14441       DiagID = diag::warn_ptr_arith_precedes_bounds;
14442       if (index.isNegative()) index = -index;
14443     }
14444 
14445     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14446                         PDiag(DiagID) << index.toString(10, true)
14447                                       << IndexExpr->getSourceRange());
14448   }
14449 
14450   if (!ND) {
14451     // Try harder to find a NamedDecl to point at in the note.
14452     while (const ArraySubscriptExpr *ASE =
14453            dyn_cast<ArraySubscriptExpr>(BaseExpr))
14454       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14455     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14456       ND = DRE->getDecl();
14457     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14458       ND = ME->getMemberDecl();
14459   }
14460 
14461   if (ND)
14462     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14463                         PDiag(diag::note_array_declared_here) << ND);
14464 }
14465 
14466 void Sema::CheckArrayAccess(const Expr *expr) {
14467   int AllowOnePastEnd = 0;
14468   while (expr) {
14469     expr = expr->IgnoreParenImpCasts();
14470     switch (expr->getStmtClass()) {
14471       case Stmt::ArraySubscriptExprClass: {
14472         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14473         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14474                          AllowOnePastEnd > 0);
14475         expr = ASE->getBase();
14476         break;
14477       }
14478       case Stmt::MemberExprClass: {
14479         expr = cast<MemberExpr>(expr)->getBase();
14480         break;
14481       }
14482       case Stmt::OMPArraySectionExprClass: {
14483         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14484         if (ASE->getLowerBound())
14485           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14486                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14487         return;
14488       }
14489       case Stmt::UnaryOperatorClass: {
14490         // Only unwrap the * and & unary operators
14491         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14492         expr = UO->getSubExpr();
14493         switch (UO->getOpcode()) {
14494           case UO_AddrOf:
14495             AllowOnePastEnd++;
14496             break;
14497           case UO_Deref:
14498             AllowOnePastEnd--;
14499             break;
14500           default:
14501             return;
14502         }
14503         break;
14504       }
14505       case Stmt::ConditionalOperatorClass: {
14506         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14507         if (const Expr *lhs = cond->getLHS())
14508           CheckArrayAccess(lhs);
14509         if (const Expr *rhs = cond->getRHS())
14510           CheckArrayAccess(rhs);
14511         return;
14512       }
14513       case Stmt::CXXOperatorCallExprClass: {
14514         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14515         for (const auto *Arg : OCE->arguments())
14516           CheckArrayAccess(Arg);
14517         return;
14518       }
14519       default:
14520         return;
14521     }
14522   }
14523 }
14524 
14525 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14526 
14527 namespace {
14528 
14529 struct RetainCycleOwner {
14530   VarDecl *Variable = nullptr;
14531   SourceRange Range;
14532   SourceLocation Loc;
14533   bool Indirect = false;
14534 
14535   RetainCycleOwner() = default;
14536 
14537   void setLocsFrom(Expr *e) {
14538     Loc = e->getExprLoc();
14539     Range = e->getSourceRange();
14540   }
14541 };
14542 
14543 } // namespace
14544 
14545 /// Consider whether capturing the given variable can possibly lead to
14546 /// a retain cycle.
14547 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14548   // In ARC, it's captured strongly iff the variable has __strong
14549   // lifetime.  In MRR, it's captured strongly if the variable is
14550   // __block and has an appropriate type.
14551   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14552     return false;
14553 
14554   owner.Variable = var;
14555   if (ref)
14556     owner.setLocsFrom(ref);
14557   return true;
14558 }
14559 
14560 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14561   while (true) {
14562     e = e->IgnoreParens();
14563     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14564       switch (cast->getCastKind()) {
14565       case CK_BitCast:
14566       case CK_LValueBitCast:
14567       case CK_LValueToRValue:
14568       case CK_ARCReclaimReturnedObject:
14569         e = cast->getSubExpr();
14570         continue;
14571 
14572       default:
14573         return false;
14574       }
14575     }
14576 
14577     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14578       ObjCIvarDecl *ivar = ref->getDecl();
14579       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14580         return false;
14581 
14582       // Try to find a retain cycle in the base.
14583       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14584         return false;
14585 
14586       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14587       owner.Indirect = true;
14588       return true;
14589     }
14590 
14591     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14592       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14593       if (!var) return false;
14594       return considerVariable(var, ref, owner);
14595     }
14596 
14597     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14598       if (member->isArrow()) return false;
14599 
14600       // Don't count this as an indirect ownership.
14601       e = member->getBase();
14602       continue;
14603     }
14604 
14605     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14606       // Only pay attention to pseudo-objects on property references.
14607       ObjCPropertyRefExpr *pre
14608         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14609                                               ->IgnoreParens());
14610       if (!pre) return false;
14611       if (pre->isImplicitProperty()) return false;
14612       ObjCPropertyDecl *property = pre->getExplicitProperty();
14613       if (!property->isRetaining() &&
14614           !(property->getPropertyIvarDecl() &&
14615             property->getPropertyIvarDecl()->getType()
14616               .getObjCLifetime() == Qualifiers::OCL_Strong))
14617           return false;
14618 
14619       owner.Indirect = true;
14620       if (pre->isSuperReceiver()) {
14621         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14622         if (!owner.Variable)
14623           return false;
14624         owner.Loc = pre->getLocation();
14625         owner.Range = pre->getSourceRange();
14626         return true;
14627       }
14628       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14629                               ->getSourceExpr());
14630       continue;
14631     }
14632 
14633     // Array ivars?
14634 
14635     return false;
14636   }
14637 }
14638 
14639 namespace {
14640 
14641   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14642     ASTContext &Context;
14643     VarDecl *Variable;
14644     Expr *Capturer = nullptr;
14645     bool VarWillBeReased = false;
14646 
14647     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14648         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14649           Context(Context), Variable(variable) {}
14650 
14651     void VisitDeclRefExpr(DeclRefExpr *ref) {
14652       if (ref->getDecl() == Variable && !Capturer)
14653         Capturer = ref;
14654     }
14655 
14656     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14657       if (Capturer) return;
14658       Visit(ref->getBase());
14659       if (Capturer && ref->isFreeIvar())
14660         Capturer = ref;
14661     }
14662 
14663     void VisitBlockExpr(BlockExpr *block) {
14664       // Look inside nested blocks
14665       if (block->getBlockDecl()->capturesVariable(Variable))
14666         Visit(block->getBlockDecl()->getBody());
14667     }
14668 
14669     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14670       if (Capturer) return;
14671       if (OVE->getSourceExpr())
14672         Visit(OVE->getSourceExpr());
14673     }
14674 
14675     void VisitBinaryOperator(BinaryOperator *BinOp) {
14676       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14677         return;
14678       Expr *LHS = BinOp->getLHS();
14679       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14680         if (DRE->getDecl() != Variable)
14681           return;
14682         if (Expr *RHS = BinOp->getRHS()) {
14683           RHS = RHS->IgnoreParenCasts();
14684           Optional<llvm::APSInt> Value;
14685           VarWillBeReased =
14686               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14687                *Value == 0);
14688         }
14689       }
14690     }
14691   };
14692 
14693 } // namespace
14694 
14695 /// Check whether the given argument is a block which captures a
14696 /// variable.
14697 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14698   assert(owner.Variable && owner.Loc.isValid());
14699 
14700   e = e->IgnoreParenCasts();
14701 
14702   // Look through [^{...} copy] and Block_copy(^{...}).
14703   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14704     Selector Cmd = ME->getSelector();
14705     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14706       e = ME->getInstanceReceiver();
14707       if (!e)
14708         return nullptr;
14709       e = e->IgnoreParenCasts();
14710     }
14711   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14712     if (CE->getNumArgs() == 1) {
14713       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14714       if (Fn) {
14715         const IdentifierInfo *FnI = Fn->getIdentifier();
14716         if (FnI && FnI->isStr("_Block_copy")) {
14717           e = CE->getArg(0)->IgnoreParenCasts();
14718         }
14719       }
14720     }
14721   }
14722 
14723   BlockExpr *block = dyn_cast<BlockExpr>(e);
14724   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14725     return nullptr;
14726 
14727   FindCaptureVisitor visitor(S.Context, owner.Variable);
14728   visitor.Visit(block->getBlockDecl()->getBody());
14729   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14730 }
14731 
14732 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14733                                 RetainCycleOwner &owner) {
14734   assert(capturer);
14735   assert(owner.Variable && owner.Loc.isValid());
14736 
14737   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14738     << owner.Variable << capturer->getSourceRange();
14739   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14740     << owner.Indirect << owner.Range;
14741 }
14742 
14743 /// Check for a keyword selector that starts with the word 'add' or
14744 /// 'set'.
14745 static bool isSetterLikeSelector(Selector sel) {
14746   if (sel.isUnarySelector()) return false;
14747 
14748   StringRef str = sel.getNameForSlot(0);
14749   while (!str.empty() && str.front() == '_') str = str.substr(1);
14750   if (str.startswith("set"))
14751     str = str.substr(3);
14752   else if (str.startswith("add")) {
14753     // Specially allow 'addOperationWithBlock:'.
14754     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14755       return false;
14756     str = str.substr(3);
14757   }
14758   else
14759     return false;
14760 
14761   if (str.empty()) return true;
14762   return !isLowercase(str.front());
14763 }
14764 
14765 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14766                                                     ObjCMessageExpr *Message) {
14767   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14768                                                 Message->getReceiverInterface(),
14769                                                 NSAPI::ClassId_NSMutableArray);
14770   if (!IsMutableArray) {
14771     return None;
14772   }
14773 
14774   Selector Sel = Message->getSelector();
14775 
14776   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14777     S.NSAPIObj->getNSArrayMethodKind(Sel);
14778   if (!MKOpt) {
14779     return None;
14780   }
14781 
14782   NSAPI::NSArrayMethodKind MK = *MKOpt;
14783 
14784   switch (MK) {
14785     case NSAPI::NSMutableArr_addObject:
14786     case NSAPI::NSMutableArr_insertObjectAtIndex:
14787     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14788       return 0;
14789     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14790       return 1;
14791 
14792     default:
14793       return None;
14794   }
14795 
14796   return None;
14797 }
14798 
14799 static
14800 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14801                                                   ObjCMessageExpr *Message) {
14802   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14803                                             Message->getReceiverInterface(),
14804                                             NSAPI::ClassId_NSMutableDictionary);
14805   if (!IsMutableDictionary) {
14806     return None;
14807   }
14808 
14809   Selector Sel = Message->getSelector();
14810 
14811   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14812     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14813   if (!MKOpt) {
14814     return None;
14815   }
14816 
14817   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14818 
14819   switch (MK) {
14820     case NSAPI::NSMutableDict_setObjectForKey:
14821     case NSAPI::NSMutableDict_setValueForKey:
14822     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14823       return 0;
14824 
14825     default:
14826       return None;
14827   }
14828 
14829   return None;
14830 }
14831 
14832 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14833   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14834                                                 Message->getReceiverInterface(),
14835                                                 NSAPI::ClassId_NSMutableSet);
14836 
14837   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14838                                             Message->getReceiverInterface(),
14839                                             NSAPI::ClassId_NSMutableOrderedSet);
14840   if (!IsMutableSet && !IsMutableOrderedSet) {
14841     return None;
14842   }
14843 
14844   Selector Sel = Message->getSelector();
14845 
14846   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14847   if (!MKOpt) {
14848     return None;
14849   }
14850 
14851   NSAPI::NSSetMethodKind MK = *MKOpt;
14852 
14853   switch (MK) {
14854     case NSAPI::NSMutableSet_addObject:
14855     case NSAPI::NSOrderedSet_setObjectAtIndex:
14856     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14857     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14858       return 0;
14859     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14860       return 1;
14861   }
14862 
14863   return None;
14864 }
14865 
14866 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14867   if (!Message->isInstanceMessage()) {
14868     return;
14869   }
14870 
14871   Optional<int> ArgOpt;
14872 
14873   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14874       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14875       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14876     return;
14877   }
14878 
14879   int ArgIndex = *ArgOpt;
14880 
14881   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14882   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14883     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14884   }
14885 
14886   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14887     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14888       if (ArgRE->isObjCSelfExpr()) {
14889         Diag(Message->getSourceRange().getBegin(),
14890              diag::warn_objc_circular_container)
14891           << ArgRE->getDecl() << StringRef("'super'");
14892       }
14893     }
14894   } else {
14895     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14896 
14897     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14898       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14899     }
14900 
14901     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14902       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14903         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14904           ValueDecl *Decl = ReceiverRE->getDecl();
14905           Diag(Message->getSourceRange().getBegin(),
14906                diag::warn_objc_circular_container)
14907             << Decl << Decl;
14908           if (!ArgRE->isObjCSelfExpr()) {
14909             Diag(Decl->getLocation(),
14910                  diag::note_objc_circular_container_declared_here)
14911               << Decl;
14912           }
14913         }
14914       }
14915     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14916       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14917         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14918           ObjCIvarDecl *Decl = IvarRE->getDecl();
14919           Diag(Message->getSourceRange().getBegin(),
14920                diag::warn_objc_circular_container)
14921             << Decl << Decl;
14922           Diag(Decl->getLocation(),
14923                diag::note_objc_circular_container_declared_here)
14924             << Decl;
14925         }
14926       }
14927     }
14928   }
14929 }
14930 
14931 /// Check a message send to see if it's likely to cause a retain cycle.
14932 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14933   // Only check instance methods whose selector looks like a setter.
14934   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14935     return;
14936 
14937   // Try to find a variable that the receiver is strongly owned by.
14938   RetainCycleOwner owner;
14939   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14940     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14941       return;
14942   } else {
14943     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14944     owner.Variable = getCurMethodDecl()->getSelfDecl();
14945     owner.Loc = msg->getSuperLoc();
14946     owner.Range = msg->getSuperLoc();
14947   }
14948 
14949   // Check whether the receiver is captured by any of the arguments.
14950   const ObjCMethodDecl *MD = msg->getMethodDecl();
14951   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14952     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14953       // noescape blocks should not be retained by the method.
14954       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14955         continue;
14956       return diagnoseRetainCycle(*this, capturer, owner);
14957     }
14958   }
14959 }
14960 
14961 /// Check a property assign to see if it's likely to cause a retain cycle.
14962 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14963   RetainCycleOwner owner;
14964   if (!findRetainCycleOwner(*this, receiver, owner))
14965     return;
14966 
14967   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14968     diagnoseRetainCycle(*this, capturer, owner);
14969 }
14970 
14971 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14972   RetainCycleOwner Owner;
14973   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14974     return;
14975 
14976   // Because we don't have an expression for the variable, we have to set the
14977   // location explicitly here.
14978   Owner.Loc = Var->getLocation();
14979   Owner.Range = Var->getSourceRange();
14980 
14981   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14982     diagnoseRetainCycle(*this, Capturer, Owner);
14983 }
14984 
14985 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14986                                      Expr *RHS, bool isProperty) {
14987   // Check if RHS is an Objective-C object literal, which also can get
14988   // immediately zapped in a weak reference.  Note that we explicitly
14989   // allow ObjCStringLiterals, since those are designed to never really die.
14990   RHS = RHS->IgnoreParenImpCasts();
14991 
14992   // This enum needs to match with the 'select' in
14993   // warn_objc_arc_literal_assign (off-by-1).
14994   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14995   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14996     return false;
14997 
14998   S.Diag(Loc, diag::warn_arc_literal_assign)
14999     << (unsigned) Kind
15000     << (isProperty ? 0 : 1)
15001     << RHS->getSourceRange();
15002 
15003   return true;
15004 }
15005 
15006 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15007                                     Qualifiers::ObjCLifetime LT,
15008                                     Expr *RHS, bool isProperty) {
15009   // Strip off any implicit cast added to get to the one ARC-specific.
15010   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15011     if (cast->getCastKind() == CK_ARCConsumeObject) {
15012       S.Diag(Loc, diag::warn_arc_retained_assign)
15013         << (LT == Qualifiers::OCL_ExplicitNone)
15014         << (isProperty ? 0 : 1)
15015         << RHS->getSourceRange();
15016       return true;
15017     }
15018     RHS = cast->getSubExpr();
15019   }
15020 
15021   if (LT == Qualifiers::OCL_Weak &&
15022       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15023     return true;
15024 
15025   return false;
15026 }
15027 
15028 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15029                               QualType LHS, Expr *RHS) {
15030   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15031 
15032   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15033     return false;
15034 
15035   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15036     return true;
15037 
15038   return false;
15039 }
15040 
15041 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15042                               Expr *LHS, Expr *RHS) {
15043   QualType LHSType;
15044   // PropertyRef on LHS type need be directly obtained from
15045   // its declaration as it has a PseudoType.
15046   ObjCPropertyRefExpr *PRE
15047     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15048   if (PRE && !PRE->isImplicitProperty()) {
15049     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15050     if (PD)
15051       LHSType = PD->getType();
15052   }
15053 
15054   if (LHSType.isNull())
15055     LHSType = LHS->getType();
15056 
15057   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15058 
15059   if (LT == Qualifiers::OCL_Weak) {
15060     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15061       getCurFunction()->markSafeWeakUse(LHS);
15062   }
15063 
15064   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15065     return;
15066 
15067   // FIXME. Check for other life times.
15068   if (LT != Qualifiers::OCL_None)
15069     return;
15070 
15071   if (PRE) {
15072     if (PRE->isImplicitProperty())
15073       return;
15074     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15075     if (!PD)
15076       return;
15077 
15078     unsigned Attributes = PD->getPropertyAttributes();
15079     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15080       // when 'assign' attribute was not explicitly specified
15081       // by user, ignore it and rely on property type itself
15082       // for lifetime info.
15083       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15084       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15085           LHSType->isObjCRetainableType())
15086         return;
15087 
15088       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15089         if (cast->getCastKind() == CK_ARCConsumeObject) {
15090           Diag(Loc, diag::warn_arc_retained_property_assign)
15091           << RHS->getSourceRange();
15092           return;
15093         }
15094         RHS = cast->getSubExpr();
15095       }
15096     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15097       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15098         return;
15099     }
15100   }
15101 }
15102 
15103 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15104 
15105 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15106                                         SourceLocation StmtLoc,
15107                                         const NullStmt *Body) {
15108   // Do not warn if the body is a macro that expands to nothing, e.g:
15109   //
15110   // #define CALL(x)
15111   // if (condition)
15112   //   CALL(0);
15113   if (Body->hasLeadingEmptyMacro())
15114     return false;
15115 
15116   // Get line numbers of statement and body.
15117   bool StmtLineInvalid;
15118   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15119                                                       &StmtLineInvalid);
15120   if (StmtLineInvalid)
15121     return false;
15122 
15123   bool BodyLineInvalid;
15124   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15125                                                       &BodyLineInvalid);
15126   if (BodyLineInvalid)
15127     return false;
15128 
15129   // Warn if null statement and body are on the same line.
15130   if (StmtLine != BodyLine)
15131     return false;
15132 
15133   return true;
15134 }
15135 
15136 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15137                                  const Stmt *Body,
15138                                  unsigned DiagID) {
15139   // Since this is a syntactic check, don't emit diagnostic for template
15140   // instantiations, this just adds noise.
15141   if (CurrentInstantiationScope)
15142     return;
15143 
15144   // The body should be a null statement.
15145   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15146   if (!NBody)
15147     return;
15148 
15149   // Do the usual checks.
15150   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15151     return;
15152 
15153   Diag(NBody->getSemiLoc(), DiagID);
15154   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15155 }
15156 
15157 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15158                                  const Stmt *PossibleBody) {
15159   assert(!CurrentInstantiationScope); // Ensured by caller
15160 
15161   SourceLocation StmtLoc;
15162   const Stmt *Body;
15163   unsigned DiagID;
15164   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15165     StmtLoc = FS->getRParenLoc();
15166     Body = FS->getBody();
15167     DiagID = diag::warn_empty_for_body;
15168   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15169     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15170     Body = WS->getBody();
15171     DiagID = diag::warn_empty_while_body;
15172   } else
15173     return; // Neither `for' nor `while'.
15174 
15175   // The body should be a null statement.
15176   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15177   if (!NBody)
15178     return;
15179 
15180   // Skip expensive checks if diagnostic is disabled.
15181   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15182     return;
15183 
15184   // Do the usual checks.
15185   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15186     return;
15187 
15188   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15189   // noise level low, emit diagnostics only if for/while is followed by a
15190   // CompoundStmt, e.g.:
15191   //    for (int i = 0; i < n; i++);
15192   //    {
15193   //      a(i);
15194   //    }
15195   // or if for/while is followed by a statement with more indentation
15196   // than for/while itself:
15197   //    for (int i = 0; i < n; i++);
15198   //      a(i);
15199   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15200   if (!ProbableTypo) {
15201     bool BodyColInvalid;
15202     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15203         PossibleBody->getBeginLoc(), &BodyColInvalid);
15204     if (BodyColInvalid)
15205       return;
15206 
15207     bool StmtColInvalid;
15208     unsigned StmtCol =
15209         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15210     if (StmtColInvalid)
15211       return;
15212 
15213     if (BodyCol > StmtCol)
15214       ProbableTypo = true;
15215   }
15216 
15217   if (ProbableTypo) {
15218     Diag(NBody->getSemiLoc(), DiagID);
15219     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15220   }
15221 }
15222 
15223 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15224 
15225 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15226 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15227                              SourceLocation OpLoc) {
15228   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15229     return;
15230 
15231   if (inTemplateInstantiation())
15232     return;
15233 
15234   // Strip parens and casts away.
15235   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15236   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15237 
15238   // Check for a call expression
15239   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15240   if (!CE || CE->getNumArgs() != 1)
15241     return;
15242 
15243   // Check for a call to std::move
15244   if (!CE->isCallToStdMove())
15245     return;
15246 
15247   // Get argument from std::move
15248   RHSExpr = CE->getArg(0);
15249 
15250   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15251   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15252 
15253   // Two DeclRefExpr's, check that the decls are the same.
15254   if (LHSDeclRef && RHSDeclRef) {
15255     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15256       return;
15257     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15258         RHSDeclRef->getDecl()->getCanonicalDecl())
15259       return;
15260 
15261     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15262                                         << LHSExpr->getSourceRange()
15263                                         << RHSExpr->getSourceRange();
15264     return;
15265   }
15266 
15267   // Member variables require a different approach to check for self moves.
15268   // MemberExpr's are the same if every nested MemberExpr refers to the same
15269   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15270   // the base Expr's are CXXThisExpr's.
15271   const Expr *LHSBase = LHSExpr;
15272   const Expr *RHSBase = RHSExpr;
15273   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15274   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15275   if (!LHSME || !RHSME)
15276     return;
15277 
15278   while (LHSME && RHSME) {
15279     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15280         RHSME->getMemberDecl()->getCanonicalDecl())
15281       return;
15282 
15283     LHSBase = LHSME->getBase();
15284     RHSBase = RHSME->getBase();
15285     LHSME = dyn_cast<MemberExpr>(LHSBase);
15286     RHSME = dyn_cast<MemberExpr>(RHSBase);
15287   }
15288 
15289   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15290   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15291   if (LHSDeclRef && RHSDeclRef) {
15292     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15293       return;
15294     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15295         RHSDeclRef->getDecl()->getCanonicalDecl())
15296       return;
15297 
15298     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15299                                         << LHSExpr->getSourceRange()
15300                                         << RHSExpr->getSourceRange();
15301     return;
15302   }
15303 
15304   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15305     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15306                                         << LHSExpr->getSourceRange()
15307                                         << RHSExpr->getSourceRange();
15308 }
15309 
15310 //===--- Layout compatibility ----------------------------------------------//
15311 
15312 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15313 
15314 /// Check if two enumeration types are layout-compatible.
15315 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15316   // C++11 [dcl.enum] p8:
15317   // Two enumeration types are layout-compatible if they have the same
15318   // underlying type.
15319   return ED1->isComplete() && ED2->isComplete() &&
15320          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15321 }
15322 
15323 /// Check if two fields are layout-compatible.
15324 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15325                                FieldDecl *Field2) {
15326   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15327     return false;
15328 
15329   if (Field1->isBitField() != Field2->isBitField())
15330     return false;
15331 
15332   if (Field1->isBitField()) {
15333     // Make sure that the bit-fields are the same length.
15334     unsigned Bits1 = Field1->getBitWidthValue(C);
15335     unsigned Bits2 = Field2->getBitWidthValue(C);
15336 
15337     if (Bits1 != Bits2)
15338       return false;
15339   }
15340 
15341   return true;
15342 }
15343 
15344 /// Check if two standard-layout structs are layout-compatible.
15345 /// (C++11 [class.mem] p17)
15346 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15347                                      RecordDecl *RD2) {
15348   // If both records are C++ classes, check that base classes match.
15349   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15350     // If one of records is a CXXRecordDecl we are in C++ mode,
15351     // thus the other one is a CXXRecordDecl, too.
15352     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15353     // Check number of base classes.
15354     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15355       return false;
15356 
15357     // Check the base classes.
15358     for (CXXRecordDecl::base_class_const_iterator
15359                Base1 = D1CXX->bases_begin(),
15360            BaseEnd1 = D1CXX->bases_end(),
15361               Base2 = D2CXX->bases_begin();
15362          Base1 != BaseEnd1;
15363          ++Base1, ++Base2) {
15364       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15365         return false;
15366     }
15367   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15368     // If only RD2 is a C++ class, it should have zero base classes.
15369     if (D2CXX->getNumBases() > 0)
15370       return false;
15371   }
15372 
15373   // Check the fields.
15374   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15375                              Field2End = RD2->field_end(),
15376                              Field1 = RD1->field_begin(),
15377                              Field1End = RD1->field_end();
15378   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15379     if (!isLayoutCompatible(C, *Field1, *Field2))
15380       return false;
15381   }
15382   if (Field1 != Field1End || Field2 != Field2End)
15383     return false;
15384 
15385   return true;
15386 }
15387 
15388 /// Check if two standard-layout unions are layout-compatible.
15389 /// (C++11 [class.mem] p18)
15390 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15391                                     RecordDecl *RD2) {
15392   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15393   for (auto *Field2 : RD2->fields())
15394     UnmatchedFields.insert(Field2);
15395 
15396   for (auto *Field1 : RD1->fields()) {
15397     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15398         I = UnmatchedFields.begin(),
15399         E = UnmatchedFields.end();
15400 
15401     for ( ; I != E; ++I) {
15402       if (isLayoutCompatible(C, Field1, *I)) {
15403         bool Result = UnmatchedFields.erase(*I);
15404         (void) Result;
15405         assert(Result);
15406         break;
15407       }
15408     }
15409     if (I == E)
15410       return false;
15411   }
15412 
15413   return UnmatchedFields.empty();
15414 }
15415 
15416 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15417                                RecordDecl *RD2) {
15418   if (RD1->isUnion() != RD2->isUnion())
15419     return false;
15420 
15421   if (RD1->isUnion())
15422     return isLayoutCompatibleUnion(C, RD1, RD2);
15423   else
15424     return isLayoutCompatibleStruct(C, RD1, RD2);
15425 }
15426 
15427 /// Check if two types are layout-compatible in C++11 sense.
15428 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15429   if (T1.isNull() || T2.isNull())
15430     return false;
15431 
15432   // C++11 [basic.types] p11:
15433   // If two types T1 and T2 are the same type, then T1 and T2 are
15434   // layout-compatible types.
15435   if (C.hasSameType(T1, T2))
15436     return true;
15437 
15438   T1 = T1.getCanonicalType().getUnqualifiedType();
15439   T2 = T2.getCanonicalType().getUnqualifiedType();
15440 
15441   const Type::TypeClass TC1 = T1->getTypeClass();
15442   const Type::TypeClass TC2 = T2->getTypeClass();
15443 
15444   if (TC1 != TC2)
15445     return false;
15446 
15447   if (TC1 == Type::Enum) {
15448     return isLayoutCompatible(C,
15449                               cast<EnumType>(T1)->getDecl(),
15450                               cast<EnumType>(T2)->getDecl());
15451   } else if (TC1 == Type::Record) {
15452     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15453       return false;
15454 
15455     return isLayoutCompatible(C,
15456                               cast<RecordType>(T1)->getDecl(),
15457                               cast<RecordType>(T2)->getDecl());
15458   }
15459 
15460   return false;
15461 }
15462 
15463 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15464 
15465 /// Given a type tag expression find the type tag itself.
15466 ///
15467 /// \param TypeExpr Type tag expression, as it appears in user's code.
15468 ///
15469 /// \param VD Declaration of an identifier that appears in a type tag.
15470 ///
15471 /// \param MagicValue Type tag magic value.
15472 ///
15473 /// \param isConstantEvaluated wether the evalaution should be performed in
15474 
15475 /// constant context.
15476 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15477                             const ValueDecl **VD, uint64_t *MagicValue,
15478                             bool isConstantEvaluated) {
15479   while(true) {
15480     if (!TypeExpr)
15481       return false;
15482 
15483     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15484 
15485     switch (TypeExpr->getStmtClass()) {
15486     case Stmt::UnaryOperatorClass: {
15487       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15488       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15489         TypeExpr = UO->getSubExpr();
15490         continue;
15491       }
15492       return false;
15493     }
15494 
15495     case Stmt::DeclRefExprClass: {
15496       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15497       *VD = DRE->getDecl();
15498       return true;
15499     }
15500 
15501     case Stmt::IntegerLiteralClass: {
15502       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15503       llvm::APInt MagicValueAPInt = IL->getValue();
15504       if (MagicValueAPInt.getActiveBits() <= 64) {
15505         *MagicValue = MagicValueAPInt.getZExtValue();
15506         return true;
15507       } else
15508         return false;
15509     }
15510 
15511     case Stmt::BinaryConditionalOperatorClass:
15512     case Stmt::ConditionalOperatorClass: {
15513       const AbstractConditionalOperator *ACO =
15514           cast<AbstractConditionalOperator>(TypeExpr);
15515       bool Result;
15516       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15517                                                      isConstantEvaluated)) {
15518         if (Result)
15519           TypeExpr = ACO->getTrueExpr();
15520         else
15521           TypeExpr = ACO->getFalseExpr();
15522         continue;
15523       }
15524       return false;
15525     }
15526 
15527     case Stmt::BinaryOperatorClass: {
15528       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15529       if (BO->getOpcode() == BO_Comma) {
15530         TypeExpr = BO->getRHS();
15531         continue;
15532       }
15533       return false;
15534     }
15535 
15536     default:
15537       return false;
15538     }
15539   }
15540 }
15541 
15542 /// Retrieve the C type corresponding to type tag TypeExpr.
15543 ///
15544 /// \param TypeExpr Expression that specifies a type tag.
15545 ///
15546 /// \param MagicValues Registered magic values.
15547 ///
15548 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15549 ///        kind.
15550 ///
15551 /// \param TypeInfo Information about the corresponding C type.
15552 ///
15553 /// \param isConstantEvaluated wether the evalaution should be performed in
15554 /// constant context.
15555 ///
15556 /// \returns true if the corresponding C type was found.
15557 static bool GetMatchingCType(
15558     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15559     const ASTContext &Ctx,
15560     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15561         *MagicValues,
15562     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15563     bool isConstantEvaluated) {
15564   FoundWrongKind = false;
15565 
15566   // Variable declaration that has type_tag_for_datatype attribute.
15567   const ValueDecl *VD = nullptr;
15568 
15569   uint64_t MagicValue;
15570 
15571   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15572     return false;
15573 
15574   if (VD) {
15575     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15576       if (I->getArgumentKind() != ArgumentKind) {
15577         FoundWrongKind = true;
15578         return false;
15579       }
15580       TypeInfo.Type = I->getMatchingCType();
15581       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15582       TypeInfo.MustBeNull = I->getMustBeNull();
15583       return true;
15584     }
15585     return false;
15586   }
15587 
15588   if (!MagicValues)
15589     return false;
15590 
15591   llvm::DenseMap<Sema::TypeTagMagicValue,
15592                  Sema::TypeTagData>::const_iterator I =
15593       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15594   if (I == MagicValues->end())
15595     return false;
15596 
15597   TypeInfo = I->second;
15598   return true;
15599 }
15600 
15601 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15602                                       uint64_t MagicValue, QualType Type,
15603                                       bool LayoutCompatible,
15604                                       bool MustBeNull) {
15605   if (!TypeTagForDatatypeMagicValues)
15606     TypeTagForDatatypeMagicValues.reset(
15607         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15608 
15609   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15610   (*TypeTagForDatatypeMagicValues)[Magic] =
15611       TypeTagData(Type, LayoutCompatible, MustBeNull);
15612 }
15613 
15614 static bool IsSameCharType(QualType T1, QualType T2) {
15615   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15616   if (!BT1)
15617     return false;
15618 
15619   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15620   if (!BT2)
15621     return false;
15622 
15623   BuiltinType::Kind T1Kind = BT1->getKind();
15624   BuiltinType::Kind T2Kind = BT2->getKind();
15625 
15626   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15627          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15628          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15629          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15630 }
15631 
15632 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15633                                     const ArrayRef<const Expr *> ExprArgs,
15634                                     SourceLocation CallSiteLoc) {
15635   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15636   bool IsPointerAttr = Attr->getIsPointer();
15637 
15638   // Retrieve the argument representing the 'type_tag'.
15639   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15640   if (TypeTagIdxAST >= ExprArgs.size()) {
15641     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15642         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15643     return;
15644   }
15645   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15646   bool FoundWrongKind;
15647   TypeTagData TypeInfo;
15648   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15649                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15650                         TypeInfo, isConstantEvaluated())) {
15651     if (FoundWrongKind)
15652       Diag(TypeTagExpr->getExprLoc(),
15653            diag::warn_type_tag_for_datatype_wrong_kind)
15654         << TypeTagExpr->getSourceRange();
15655     return;
15656   }
15657 
15658   // Retrieve the argument representing the 'arg_idx'.
15659   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15660   if (ArgumentIdxAST >= ExprArgs.size()) {
15661     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15662         << 1 << Attr->getArgumentIdx().getSourceIndex();
15663     return;
15664   }
15665   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15666   if (IsPointerAttr) {
15667     // Skip implicit cast of pointer to `void *' (as a function argument).
15668     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15669       if (ICE->getType()->isVoidPointerType() &&
15670           ICE->getCastKind() == CK_BitCast)
15671         ArgumentExpr = ICE->getSubExpr();
15672   }
15673   QualType ArgumentType = ArgumentExpr->getType();
15674 
15675   // Passing a `void*' pointer shouldn't trigger a warning.
15676   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15677     return;
15678 
15679   if (TypeInfo.MustBeNull) {
15680     // Type tag with matching void type requires a null pointer.
15681     if (!ArgumentExpr->isNullPointerConstant(Context,
15682                                              Expr::NPC_ValueDependentIsNotNull)) {
15683       Diag(ArgumentExpr->getExprLoc(),
15684            diag::warn_type_safety_null_pointer_required)
15685           << ArgumentKind->getName()
15686           << ArgumentExpr->getSourceRange()
15687           << TypeTagExpr->getSourceRange();
15688     }
15689     return;
15690   }
15691 
15692   QualType RequiredType = TypeInfo.Type;
15693   if (IsPointerAttr)
15694     RequiredType = Context.getPointerType(RequiredType);
15695 
15696   bool mismatch = false;
15697   if (!TypeInfo.LayoutCompatible) {
15698     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15699 
15700     // C++11 [basic.fundamental] p1:
15701     // Plain char, signed char, and unsigned char are three distinct types.
15702     //
15703     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15704     // char' depending on the current char signedness mode.
15705     if (mismatch)
15706       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15707                                            RequiredType->getPointeeType())) ||
15708           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15709         mismatch = false;
15710   } else
15711     if (IsPointerAttr)
15712       mismatch = !isLayoutCompatible(Context,
15713                                      ArgumentType->getPointeeType(),
15714                                      RequiredType->getPointeeType());
15715     else
15716       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15717 
15718   if (mismatch)
15719     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15720         << ArgumentType << ArgumentKind
15721         << TypeInfo.LayoutCompatible << RequiredType
15722         << ArgumentExpr->getSourceRange()
15723         << TypeTagExpr->getSourceRange();
15724 }
15725 
15726 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15727                                          CharUnits Alignment) {
15728   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15729 }
15730 
15731 void Sema::DiagnoseMisalignedMembers() {
15732   for (MisalignedMember &m : MisalignedMembers) {
15733     const NamedDecl *ND = m.RD;
15734     if (ND->getName().empty()) {
15735       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15736         ND = TD;
15737     }
15738     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15739         << m.MD << ND << m.E->getSourceRange();
15740   }
15741   MisalignedMembers.clear();
15742 }
15743 
15744 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15745   E = E->IgnoreParens();
15746   if (!T->isPointerType() && !T->isIntegerType())
15747     return;
15748   if (isa<UnaryOperator>(E) &&
15749       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15750     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15751     if (isa<MemberExpr>(Op)) {
15752       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15753       if (MA != MisalignedMembers.end() &&
15754           (T->isIntegerType() ||
15755            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15756                                    Context.getTypeAlignInChars(
15757                                        T->getPointeeType()) <= MA->Alignment))))
15758         MisalignedMembers.erase(MA);
15759     }
15760   }
15761 }
15762 
15763 void Sema::RefersToMemberWithReducedAlignment(
15764     Expr *E,
15765     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15766         Action) {
15767   const auto *ME = dyn_cast<MemberExpr>(E);
15768   if (!ME)
15769     return;
15770 
15771   // No need to check expressions with an __unaligned-qualified type.
15772   if (E->getType().getQualifiers().hasUnaligned())
15773     return;
15774 
15775   // For a chain of MemberExpr like "a.b.c.d" this list
15776   // will keep FieldDecl's like [d, c, b].
15777   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15778   const MemberExpr *TopME = nullptr;
15779   bool AnyIsPacked = false;
15780   do {
15781     QualType BaseType = ME->getBase()->getType();
15782     if (BaseType->isDependentType())
15783       return;
15784     if (ME->isArrow())
15785       BaseType = BaseType->getPointeeType();
15786     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15787     if (RD->isInvalidDecl())
15788       return;
15789 
15790     ValueDecl *MD = ME->getMemberDecl();
15791     auto *FD = dyn_cast<FieldDecl>(MD);
15792     // We do not care about non-data members.
15793     if (!FD || FD->isInvalidDecl())
15794       return;
15795 
15796     AnyIsPacked =
15797         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15798     ReverseMemberChain.push_back(FD);
15799 
15800     TopME = ME;
15801     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15802   } while (ME);
15803   assert(TopME && "We did not compute a topmost MemberExpr!");
15804 
15805   // Not the scope of this diagnostic.
15806   if (!AnyIsPacked)
15807     return;
15808 
15809   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15810   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15811   // TODO: The innermost base of the member expression may be too complicated.
15812   // For now, just disregard these cases. This is left for future
15813   // improvement.
15814   if (!DRE && !isa<CXXThisExpr>(TopBase))
15815       return;
15816 
15817   // Alignment expected by the whole expression.
15818   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15819 
15820   // No need to do anything else with this case.
15821   if (ExpectedAlignment.isOne())
15822     return;
15823 
15824   // Synthesize offset of the whole access.
15825   CharUnits Offset;
15826   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15827        I++) {
15828     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15829   }
15830 
15831   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15832   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15833       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15834 
15835   // The base expression of the innermost MemberExpr may give
15836   // stronger guarantees than the class containing the member.
15837   if (DRE && !TopME->isArrow()) {
15838     const ValueDecl *VD = DRE->getDecl();
15839     if (!VD->getType()->isReferenceType())
15840       CompleteObjectAlignment =
15841           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15842   }
15843 
15844   // Check if the synthesized offset fulfills the alignment.
15845   if (Offset % ExpectedAlignment != 0 ||
15846       // It may fulfill the offset it but the effective alignment may still be
15847       // lower than the expected expression alignment.
15848       CompleteObjectAlignment < ExpectedAlignment) {
15849     // If this happens, we want to determine a sensible culprit of this.
15850     // Intuitively, watching the chain of member expressions from right to
15851     // left, we start with the required alignment (as required by the field
15852     // type) but some packed attribute in that chain has reduced the alignment.
15853     // It may happen that another packed structure increases it again. But if
15854     // we are here such increase has not been enough. So pointing the first
15855     // FieldDecl that either is packed or else its RecordDecl is,
15856     // seems reasonable.
15857     FieldDecl *FD = nullptr;
15858     CharUnits Alignment;
15859     for (FieldDecl *FDI : ReverseMemberChain) {
15860       if (FDI->hasAttr<PackedAttr>() ||
15861           FDI->getParent()->hasAttr<PackedAttr>()) {
15862         FD = FDI;
15863         Alignment = std::min(
15864             Context.getTypeAlignInChars(FD->getType()),
15865             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15866         break;
15867       }
15868     }
15869     assert(FD && "We did not find a packed FieldDecl!");
15870     Action(E, FD->getParent(), FD, Alignment);
15871   }
15872 }
15873 
15874 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15875   using namespace std::placeholders;
15876 
15877   RefersToMemberWithReducedAlignment(
15878       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15879                      _2, _3, _4));
15880 }
15881 
15882 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15883                                             ExprResult CallResult) {
15884   if (checkArgCount(*this, TheCall, 1))
15885     return ExprError();
15886 
15887   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15888   if (MatrixArg.isInvalid())
15889     return MatrixArg;
15890   Expr *Matrix = MatrixArg.get();
15891 
15892   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15893   if (!MType) {
15894     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15895     return ExprError();
15896   }
15897 
15898   // Create returned matrix type by swapping rows and columns of the argument
15899   // matrix type.
15900   QualType ResultType = Context.getConstantMatrixType(
15901       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15902 
15903   // Change the return type to the type of the returned matrix.
15904   TheCall->setType(ResultType);
15905 
15906   // Update call argument to use the possibly converted matrix argument.
15907   TheCall->setArg(0, Matrix);
15908   return CallResult;
15909 }
15910 
15911 // Get and verify the matrix dimensions.
15912 static llvm::Optional<unsigned>
15913 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15914   SourceLocation ErrorPos;
15915   Optional<llvm::APSInt> Value =
15916       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
15917   if (!Value) {
15918     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15919         << Name;
15920     return {};
15921   }
15922   uint64_t Dim = Value->getZExtValue();
15923   if (!ConstantMatrixType::isDimensionValid(Dim)) {
15924     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15925         << Name << ConstantMatrixType::getMaxElementsPerDimension();
15926     return {};
15927   }
15928   return Dim;
15929 }
15930 
15931 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15932                                                   ExprResult CallResult) {
15933   if (!getLangOpts().MatrixTypes) {
15934     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15935     return ExprError();
15936   }
15937 
15938   if (checkArgCount(*this, TheCall, 4))
15939     return ExprError();
15940 
15941   unsigned PtrArgIdx = 0;
15942   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15943   Expr *RowsExpr = TheCall->getArg(1);
15944   Expr *ColumnsExpr = TheCall->getArg(2);
15945   Expr *StrideExpr = TheCall->getArg(3);
15946 
15947   bool ArgError = false;
15948 
15949   // Check pointer argument.
15950   {
15951     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15952     if (PtrConv.isInvalid())
15953       return PtrConv;
15954     PtrExpr = PtrConv.get();
15955     TheCall->setArg(0, PtrExpr);
15956     if (PtrExpr->isTypeDependent()) {
15957       TheCall->setType(Context.DependentTy);
15958       return TheCall;
15959     }
15960   }
15961 
15962   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15963   QualType ElementTy;
15964   if (!PtrTy) {
15965     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15966         << PtrArgIdx + 1;
15967     ArgError = true;
15968   } else {
15969     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15970 
15971     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15972       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15973           << PtrArgIdx + 1;
15974       ArgError = true;
15975     }
15976   }
15977 
15978   // Apply default Lvalue conversions and convert the expression to size_t.
15979   auto ApplyArgumentConversions = [this](Expr *E) {
15980     ExprResult Conv = DefaultLvalueConversion(E);
15981     if (Conv.isInvalid())
15982       return Conv;
15983 
15984     return tryConvertExprToType(Conv.get(), Context.getSizeType());
15985   };
15986 
15987   // Apply conversion to row and column expressions.
15988   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15989   if (!RowsConv.isInvalid()) {
15990     RowsExpr = RowsConv.get();
15991     TheCall->setArg(1, RowsExpr);
15992   } else
15993     RowsExpr = nullptr;
15994 
15995   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
15996   if (!ColumnsConv.isInvalid()) {
15997     ColumnsExpr = ColumnsConv.get();
15998     TheCall->setArg(2, ColumnsExpr);
15999   } else
16000     ColumnsExpr = nullptr;
16001 
16002   // If any any part of the result matrix type is still pending, just use
16003   // Context.DependentTy, until all parts are resolved.
16004   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16005       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16006     TheCall->setType(Context.DependentTy);
16007     return CallResult;
16008   }
16009 
16010   // Check row and column dimenions.
16011   llvm::Optional<unsigned> MaybeRows;
16012   if (RowsExpr)
16013     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16014 
16015   llvm::Optional<unsigned> MaybeColumns;
16016   if (ColumnsExpr)
16017     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16018 
16019   // Check stride argument.
16020   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16021   if (StrideConv.isInvalid())
16022     return ExprError();
16023   StrideExpr = StrideConv.get();
16024   TheCall->setArg(3, StrideExpr);
16025 
16026   if (MaybeRows) {
16027     if (Optional<llvm::APSInt> Value =
16028             StrideExpr->getIntegerConstantExpr(Context)) {
16029       uint64_t Stride = Value->getZExtValue();
16030       if (Stride < *MaybeRows) {
16031         Diag(StrideExpr->getBeginLoc(),
16032              diag::err_builtin_matrix_stride_too_small);
16033         ArgError = true;
16034       }
16035     }
16036   }
16037 
16038   if (ArgError || !MaybeRows || !MaybeColumns)
16039     return ExprError();
16040 
16041   TheCall->setType(
16042       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16043   return CallResult;
16044 }
16045 
16046 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16047                                                    ExprResult CallResult) {
16048   if (checkArgCount(*this, TheCall, 3))
16049     return ExprError();
16050 
16051   unsigned PtrArgIdx = 1;
16052   Expr *MatrixExpr = TheCall->getArg(0);
16053   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16054   Expr *StrideExpr = TheCall->getArg(2);
16055 
16056   bool ArgError = false;
16057 
16058   {
16059     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16060     if (MatrixConv.isInvalid())
16061       return MatrixConv;
16062     MatrixExpr = MatrixConv.get();
16063     TheCall->setArg(0, MatrixExpr);
16064   }
16065   if (MatrixExpr->isTypeDependent()) {
16066     TheCall->setType(Context.DependentTy);
16067     return TheCall;
16068   }
16069 
16070   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16071   if (!MatrixTy) {
16072     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16073     ArgError = true;
16074   }
16075 
16076   {
16077     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16078     if (PtrConv.isInvalid())
16079       return PtrConv;
16080     PtrExpr = PtrConv.get();
16081     TheCall->setArg(1, PtrExpr);
16082     if (PtrExpr->isTypeDependent()) {
16083       TheCall->setType(Context.DependentTy);
16084       return TheCall;
16085     }
16086   }
16087 
16088   // Check pointer argument.
16089   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16090   if (!PtrTy) {
16091     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16092         << PtrArgIdx + 1;
16093     ArgError = true;
16094   } else {
16095     QualType ElementTy = PtrTy->getPointeeType();
16096     if (ElementTy.isConstQualified()) {
16097       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16098       ArgError = true;
16099     }
16100     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16101     if (MatrixTy &&
16102         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16103       Diag(PtrExpr->getBeginLoc(),
16104            diag::err_builtin_matrix_pointer_arg_mismatch)
16105           << ElementTy << MatrixTy->getElementType();
16106       ArgError = true;
16107     }
16108   }
16109 
16110   // Apply default Lvalue conversions and convert the stride expression to
16111   // size_t.
16112   {
16113     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16114     if (StrideConv.isInvalid())
16115       return StrideConv;
16116 
16117     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16118     if (StrideConv.isInvalid())
16119       return StrideConv;
16120     StrideExpr = StrideConv.get();
16121     TheCall->setArg(2, StrideExpr);
16122   }
16123 
16124   // Check stride argument.
16125   if (MatrixTy) {
16126     if (Optional<llvm::APSInt> Value =
16127             StrideExpr->getIntegerConstantExpr(Context)) {
16128       uint64_t Stride = Value->getZExtValue();
16129       if (Stride < MatrixTy->getNumRows()) {
16130         Diag(StrideExpr->getBeginLoc(),
16131              diag::err_builtin_matrix_stride_too_small);
16132         ArgError = true;
16133       }
16134     }
16135   }
16136 
16137   if (ArgError)
16138     return ExprError();
16139 
16140   return CallResult;
16141 }
16142 
16143 /// \brief Enforce the bounds of a TCB
16144 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16145 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16146 /// and enforce_tcb_leaf attributes.
16147 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16148                                const FunctionDecl *Callee) {
16149   const FunctionDecl *Caller = getCurFunctionDecl();
16150 
16151   // Calls to builtins are not enforced.
16152   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16153       Callee->getBuiltinID() != 0)
16154     return;
16155 
16156   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16157   // all TCBs the callee is a part of.
16158   llvm::StringSet<> CalleeTCBs;
16159   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16160            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16161   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16162            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16163 
16164   // Go through the TCBs the caller is a part of and emit warnings if Caller
16165   // is in a TCB that the Callee is not.
16166   for_each(
16167       Caller->specific_attrs<EnforceTCBAttr>(),
16168       [&](const auto *A) {
16169         StringRef CallerTCB = A->getTCBName();
16170         if (CalleeTCBs.count(CallerTCB) == 0) {
16171           this->Diag(TheCall->getExprLoc(),
16172                      diag::warn_tcb_enforcement_violation) << Callee
16173                                                            << CallerTCB;
16174         }
16175       });
16176 }
16177