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 <cctype>
95 #include <cstddef>
96 #include <cstdint>
97 #include <functional>
98 #include <limits>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 
103 using namespace clang;
104 using namespace sema;
105 
106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107                                                     unsigned ByteNo) const {
108   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109                                Context.getTargetInfo());
110 }
111 
112 /// Checks that a call expression's argument count is at least the desired
113 /// number. This is useful when doing custom type-checking on a variadic
114 /// function. Returns true on error.
115 static bool checkArgCountAtLeast(Sema &S, CallExpr *Call,
116                                  unsigned MinArgCount) {
117   unsigned ArgCount = Call->getNumArgs();
118   if (ArgCount >= MinArgCount)
119     return false;
120 
121   return S.Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
122          << 0 /*function call*/ << MinArgCount << ArgCount
123          << Call->getSourceRange();
124 }
125 
126 /// Checks that a call expression's argument count is the desired number.
127 /// This is useful when doing custom type-checking.  Returns true on error.
128 static bool checkArgCount(Sema &S, CallExpr *Call, unsigned DesiredArgCount) {
129   unsigned ArgCount = Call->getNumArgs();
130   if (ArgCount == DesiredArgCount)
131     return false;
132 
133   if (checkArgCountAtLeast(S, Call, DesiredArgCount))
134     return true;
135   assert(ArgCount > DesiredArgCount && "should have diagnosed this");
136 
137   // Highlight all the excess arguments.
138   SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
139                     Call->getArg(ArgCount - 1)->getEndLoc());
140 
141   return S.Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
142          << 0 /*function call*/ << DesiredArgCount << ArgCount
143          << Call->getArg(1)->getSourceRange();
144 }
145 
146 /// Check that the first argument to __builtin_annotation is an integer
147 /// and the second argument is a non-wide string literal.
148 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
149   if (checkArgCount(S, TheCall, 2))
150     return true;
151 
152   // First argument should be an integer.
153   Expr *ValArg = TheCall->getArg(0);
154   QualType Ty = ValArg->getType();
155   if (!Ty->isIntegerType()) {
156     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
157         << ValArg->getSourceRange();
158     return true;
159   }
160 
161   // Second argument should be a constant string.
162   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
163   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
164   if (!Literal || !Literal->isAscii()) {
165     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
166         << StrArg->getSourceRange();
167     return true;
168   }
169 
170   TheCall->setType(Ty);
171   return false;
172 }
173 
174 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
175   // We need at least one argument.
176   if (TheCall->getNumArgs() < 1) {
177     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
178         << 0 << 1 << TheCall->getNumArgs()
179         << TheCall->getCallee()->getSourceRange();
180     return true;
181   }
182 
183   // All arguments should be wide string literals.
184   for (Expr *Arg : TheCall->arguments()) {
185     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
186     if (!Literal || !Literal->isWide()) {
187       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
188           << Arg->getSourceRange();
189       return true;
190     }
191   }
192 
193   return false;
194 }
195 
196 /// Check that the argument to __builtin_addressof is a glvalue, and set the
197 /// result type to the corresponding pointer type.
198 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
199   if (checkArgCount(S, TheCall, 1))
200     return true;
201 
202   ExprResult Arg(TheCall->getArg(0));
203   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
204   if (ResultType.isNull())
205     return true;
206 
207   TheCall->setArg(0, Arg.get());
208   TheCall->setType(ResultType);
209   return false;
210 }
211 
212 /// Check that the argument to __builtin_function_start is a function.
213 static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
214   if (checkArgCount(S, TheCall, 1))
215     return true;
216 
217   ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
218   if (Arg.isInvalid())
219     return true;
220 
221   TheCall->setArg(0, Arg.get());
222   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
223       Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext()));
224 
225   if (!FD) {
226     S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
227         << TheCall->getSourceRange();
228     return true;
229   }
230 
231   return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
232                                               TheCall->getBeginLoc());
233 }
234 
235 /// Check the number of arguments and set the result type to
236 /// the argument type.
237 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
238   if (checkArgCount(S, TheCall, 1))
239     return true;
240 
241   TheCall->setType(TheCall->getArg(0)->getType());
242   return false;
243 }
244 
245 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
246 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
247 /// type (but not a function pointer) and that the alignment is a power-of-two.
248 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
249   if (checkArgCount(S, TheCall, 2))
250     return true;
251 
252   clang::Expr *Source = TheCall->getArg(0);
253   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
254 
255   auto IsValidIntegerType = [](QualType Ty) {
256     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
257   };
258   QualType SrcTy = Source->getType();
259   // We should also be able to use it with arrays (but not functions!).
260   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
261     SrcTy = S.Context.getDecayedType(SrcTy);
262   }
263   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
264       SrcTy->isFunctionPointerType()) {
265     // FIXME: this is not quite the right error message since we don't allow
266     // floating point types, or member pointers.
267     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
268         << SrcTy;
269     return true;
270   }
271 
272   clang::Expr *AlignOp = TheCall->getArg(1);
273   if (!IsValidIntegerType(AlignOp->getType())) {
274     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
275         << AlignOp->getType();
276     return true;
277   }
278   Expr::EvalResult AlignResult;
279   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
280   // We can't check validity of alignment if it is value dependent.
281   if (!AlignOp->isValueDependent() &&
282       AlignOp->EvaluateAsInt(AlignResult, S.Context,
283                              Expr::SE_AllowSideEffects)) {
284     llvm::APSInt AlignValue = AlignResult.Val.getInt();
285     llvm::APSInt MaxValue(
286         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
287     if (AlignValue < 1) {
288       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
289       return true;
290     }
291     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
292       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
293           << toString(MaxValue, 10);
294       return true;
295     }
296     if (!AlignValue.isPowerOf2()) {
297       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
298       return true;
299     }
300     if (AlignValue == 1) {
301       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
302           << IsBooleanAlignBuiltin;
303     }
304   }
305 
306   ExprResult SrcArg = S.PerformCopyInitialization(
307       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
308       SourceLocation(), Source);
309   if (SrcArg.isInvalid())
310     return true;
311   TheCall->setArg(0, SrcArg.get());
312   ExprResult AlignArg =
313       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
314                                       S.Context, AlignOp->getType(), false),
315                                   SourceLocation(), AlignOp);
316   if (AlignArg.isInvalid())
317     return true;
318   TheCall->setArg(1, AlignArg.get());
319   // For align_up/align_down, the return type is the same as the (potentially
320   // decayed) argument type including qualifiers. For is_aligned(), the result
321   // is always bool.
322   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
323   return false;
324 }
325 
326 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
327                                 unsigned BuiltinID) {
328   if (checkArgCount(S, TheCall, 3))
329     return true;
330 
331   // First two arguments should be integers.
332   for (unsigned I = 0; I < 2; ++I) {
333     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
334     if (Arg.isInvalid()) return true;
335     TheCall->setArg(I, Arg.get());
336 
337     QualType Ty = Arg.get()->getType();
338     if (!Ty->isIntegerType()) {
339       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
340           << Ty << Arg.get()->getSourceRange();
341       return true;
342     }
343   }
344 
345   // Third argument should be a pointer to a non-const integer.
346   // IRGen correctly handles volatile, restrict, and address spaces, and
347   // the other qualifiers aren't possible.
348   {
349     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
350     if (Arg.isInvalid()) return true;
351     TheCall->setArg(2, Arg.get());
352 
353     QualType Ty = Arg.get()->getType();
354     const auto *PtrTy = Ty->getAs<PointerType>();
355     if (!PtrTy ||
356         !PtrTy->getPointeeType()->isIntegerType() ||
357         PtrTy->getPointeeType().isConstQualified()) {
358       S.Diag(Arg.get()->getBeginLoc(),
359              diag::err_overflow_builtin_must_be_ptr_int)
360         << Ty << Arg.get()->getSourceRange();
361       return true;
362     }
363   }
364 
365   // Disallow signed bit-precise integer args larger than 128 bits to mul
366   // function until we improve backend support.
367   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
368     for (unsigned I = 0; I < 3; ++I) {
369       const auto Arg = TheCall->getArg(I);
370       // Third argument will be a pointer.
371       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
372       if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
373           S.getASTContext().getIntWidth(Ty) > 128)
374         return S.Diag(Arg->getBeginLoc(),
375                       diag::err_overflow_builtin_bit_int_max_size)
376                << 128;
377     }
378   }
379 
380   return false;
381 }
382 
383 namespace {
384 struct BuiltinDumpStructGenerator {
385   Sema &S;
386   CallExpr *TheCall;
387   SourceLocation Loc = TheCall->getBeginLoc();
388   SmallVector<Expr *, 32> Actions;
389   DiagnosticErrorTrap ErrorTracker;
390   PrintingPolicy Policy;
391 
392   BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
393       : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
394         Policy(S.Context.getPrintingPolicy()) {
395     Policy.AnonymousTagLocations = false;
396   }
397 
398   Expr *makeOpaqueValueExpr(Expr *Inner) {
399     auto *OVE = new (S.Context)
400         OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
401                         Inner->getObjectKind(), Inner);
402     Actions.push_back(OVE);
403     return OVE;
404   }
405 
406   Expr *getStringLiteral(llvm::StringRef Str) {
407     Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Str);
408     // Wrap the literal in parentheses to attach a source location.
409     return new (S.Context) ParenExpr(Loc, Loc, Lit);
410   }
411 
412   bool callPrintFunction(llvm::StringRef Format,
413                          llvm::ArrayRef<Expr *> Exprs = {}) {
414     SmallVector<Expr *, 8> Args;
415     assert(TheCall->getNumArgs() >= 2);
416     Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
417     Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
418     Args.push_back(getStringLiteral(Format));
419     Args.insert(Args.end(), Exprs.begin(), Exprs.end());
420 
421     // Register a note to explain why we're performing the call.
422     Sema::CodeSynthesisContext Ctx;
423     Ctx.Kind = Sema::CodeSynthesisContext::BuildingBuiltinDumpStructCall;
424     Ctx.PointOfInstantiation = Loc;
425     Ctx.CallArgs = Args.data();
426     Ctx.NumCallArgs = Args.size();
427     S.pushCodeSynthesisContext(Ctx);
428 
429     ExprResult RealCall =
430         S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
431                         TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
432 
433     S.popCodeSynthesisContext();
434     if (!RealCall.isInvalid())
435       Actions.push_back(RealCall.get());
436     // Bail out if we've hit any errors, even if we managed to build the
437     // call. We don't want to produce more than one error.
438     return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
439   }
440 
441   Expr *getIndentString(unsigned Depth) {
442     if (!Depth)
443       return nullptr;
444 
445     llvm::SmallString<32> Indent;
446     Indent.resize(Depth * Policy.Indentation, ' ');
447     return getStringLiteral(Indent);
448   }
449 
450   Expr *getTypeString(QualType T) {
451     return getStringLiteral(T.getAsString(Policy));
452   }
453 
454   bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
455     llvm::raw_svector_ostream OS(Str);
456 
457     // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
458     // than trying to print a single character.
459     if (auto *BT = T->getAs<BuiltinType>()) {
460       switch (BT->getKind()) {
461       case BuiltinType::Bool:
462         OS << "%d";
463         return true;
464       case BuiltinType::Char_U:
465       case BuiltinType::UChar:
466         OS << "%hhu";
467         return true;
468       case BuiltinType::Char_S:
469       case BuiltinType::SChar:
470         OS << "%hhd";
471         return true;
472       default:
473         break;
474       }
475     }
476 
477     analyze_printf::PrintfSpecifier Specifier;
478     if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
479       // We were able to guess how to format this.
480       if (Specifier.getConversionSpecifier().getKind() ==
481           analyze_printf::PrintfConversionSpecifier::sArg) {
482         // Wrap double-quotes around a '%s' specifier and limit its maximum
483         // length. Ideally we'd also somehow escape special characters in the
484         // contents but printf doesn't support that.
485         // FIXME: '%s' formatting is not safe in general.
486         OS << '"';
487         Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
488         Specifier.toString(OS);
489         OS << '"';
490         // FIXME: It would be nice to include a '...' if the string doesn't fit
491         // in the length limit.
492       } else {
493         Specifier.toString(OS);
494       }
495       return true;
496     }
497 
498     if (T->isPointerType()) {
499       // Format all pointers with '%p'.
500       OS << "%p";
501       return true;
502     }
503 
504     return false;
505   }
506 
507   bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
508     Expr *IndentLit = getIndentString(Depth);
509     Expr *TypeLit = getTypeString(S.Context.getRecordType(RD));
510     if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
511                   : callPrintFunction("%s", {TypeLit}))
512       return true;
513 
514     return dumpRecordValue(RD, E, IndentLit, Depth);
515   }
516 
517   // Dump a record value. E should be a pointer or lvalue referring to an RD.
518   bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
519                        unsigned Depth) {
520     // FIXME: Decide what to do if RD is a union. At least we should probably
521     // turn off printing `const char*` members with `%s`, because that is very
522     // likely to crash if that's not the active member. Whatever we decide, we
523     // should document it.
524 
525     // Build an OpaqueValueExpr so we can refer to E more than once without
526     // triggering re-evaluation.
527     Expr *RecordArg = makeOpaqueValueExpr(E);
528     bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
529 
530     if (callPrintFunction(" {\n"))
531       return true;
532 
533     // Dump each base class, regardless of whether they're aggregates.
534     if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
535       for (const auto &Base : CXXRD->bases()) {
536         QualType BaseType =
537             RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
538                            : S.Context.getLValueReferenceType(Base.getType());
539         ExprResult BasePtr = S.BuildCStyleCastExpr(
540             Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
541             RecordArg);
542         if (BasePtr.isInvalid() ||
543             dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
544                               Depth + 1))
545           return true;
546       }
547     }
548 
549     Expr *FieldIndentArg = getIndentString(Depth + 1);
550 
551     // Dump each field.
552     for (auto *D : RD->decls()) {
553       auto *IFD = dyn_cast<IndirectFieldDecl>(D);
554       auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
555       if (!FD || FD->isUnnamedBitfield() || FD->isAnonymousStructOrUnion())
556         continue;
557 
558       llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
559       llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
560                                            getTypeString(FD->getType()),
561                                            getStringLiteral(FD->getName())};
562 
563       if (FD->isBitField()) {
564         Format += ": %zu ";
565         QualType SizeT = S.Context.getSizeType();
566         llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
567                              FD->getBitWidthValue(S.Context));
568         Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
569       }
570 
571       Format += "=";
572 
573       ExprResult Field =
574           IFD ? S.BuildAnonymousStructUnionMemberReference(
575                     CXXScopeSpec(), Loc, IFD,
576                     DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
577               : S.BuildFieldReferenceExpr(
578                     RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
579                     DeclAccessPair::make(FD, AS_public),
580                     DeclarationNameInfo(FD->getDeclName(), Loc));
581       if (Field.isInvalid())
582         return true;
583 
584       auto *InnerRD = FD->getType()->getAsRecordDecl();
585       auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
586       if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
587         // Recursively print the values of members of aggregate record type.
588         if (callPrintFunction(Format, Args) ||
589             dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
590           return true;
591       } else {
592         Format += " ";
593         if (appendFormatSpecifier(FD->getType(), Format)) {
594           // We know how to print this field.
595           Args.push_back(Field.get());
596         } else {
597           // We don't know how to print this field. Print out its address
598           // with a format specifier that a smart tool will be able to
599           // recognize and treat specially.
600           Format += "*%p";
601           ExprResult FieldAddr =
602               S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
603           if (FieldAddr.isInvalid())
604             return true;
605           Args.push_back(FieldAddr.get());
606         }
607         Format += "\n";
608         if (callPrintFunction(Format, Args))
609           return true;
610       }
611     }
612 
613     return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
614                         : callPrintFunction("}\n");
615   }
616 
617   Expr *buildWrapper() {
618     auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
619                                              PseudoObjectExpr::NoResult);
620     TheCall->setType(Wrapper->getType());
621     TheCall->setValueKind(Wrapper->getValueKind());
622     return Wrapper;
623   }
624 };
625 } // namespace
626 
627 static ExprResult SemaBuiltinDumpStruct(Sema &S, CallExpr *TheCall) {
628   if (checkArgCountAtLeast(S, TheCall, 2))
629     return ExprError();
630 
631   ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
632   if (PtrArgResult.isInvalid())
633     return ExprError();
634   TheCall->setArg(0, PtrArgResult.get());
635 
636   // First argument should be a pointer to a struct.
637   QualType PtrArgType = PtrArgResult.get()->getType();
638   if (!PtrArgType->isPointerType() ||
639       !PtrArgType->getPointeeType()->isRecordType()) {
640     S.Diag(PtrArgResult.get()->getBeginLoc(),
641            diag::err_expected_struct_pointer_argument)
642         << 1 << TheCall->getDirectCallee() << PtrArgType;
643     return ExprError();
644   }
645   const RecordDecl *RD = PtrArgType->getPointeeType()->getAsRecordDecl();
646 
647   // Second argument is a callable, but we can't fully validate it until we try
648   // calling it.
649   QualType FnArgType = TheCall->getArg(1)->getType();
650   if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
651       !FnArgType->isBlockPointerType() &&
652       !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
653     auto *BT = FnArgType->getAs<BuiltinType>();
654     switch (BT ? BT->getKind() : BuiltinType::Void) {
655     case BuiltinType::Dependent:
656     case BuiltinType::Overload:
657     case BuiltinType::BoundMember:
658     case BuiltinType::PseudoObject:
659     case BuiltinType::UnknownAny:
660     case BuiltinType::BuiltinFn:
661       // This might be a callable.
662       break;
663 
664     default:
665       S.Diag(TheCall->getArg(1)->getBeginLoc(),
666              diag::err_expected_callable_argument)
667           << 2 << TheCall->getDirectCallee() << FnArgType;
668       return ExprError();
669     }
670   }
671 
672   BuiltinDumpStructGenerator Generator(S, TheCall);
673 
674   // Wrap parentheses around the given pointer. This is not necessary for
675   // correct code generation, but it means that when we pretty-print the call
676   // arguments in our diagnostics we will produce '(&s)->n' instead of the
677   // incorrect '&s->n'.
678   Expr *PtrArg = PtrArgResult.get();
679   PtrArg = new (S.Context)
680       ParenExpr(PtrArg->getBeginLoc(),
681                 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
682   if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
683     return ExprError();
684 
685   return Generator.buildWrapper();
686 }
687 
688 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
689   if (checkArgCount(S, BuiltinCall, 2))
690     return true;
691 
692   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
693   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
694   Expr *Call = BuiltinCall->getArg(0);
695   Expr *Chain = BuiltinCall->getArg(1);
696 
697   if (Call->getStmtClass() != Stmt::CallExprClass) {
698     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
699         << Call->getSourceRange();
700     return true;
701   }
702 
703   auto CE = cast<CallExpr>(Call);
704   if (CE->getCallee()->getType()->isBlockPointerType()) {
705     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
706         << Call->getSourceRange();
707     return true;
708   }
709 
710   const Decl *TargetDecl = CE->getCalleeDecl();
711   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
712     if (FD->getBuiltinID()) {
713       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
714           << Call->getSourceRange();
715       return true;
716     }
717 
718   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
719     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
720         << Call->getSourceRange();
721     return true;
722   }
723 
724   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
725   if (ChainResult.isInvalid())
726     return true;
727   if (!ChainResult.get()->getType()->isPointerType()) {
728     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
729         << Chain->getSourceRange();
730     return true;
731   }
732 
733   QualType ReturnTy = CE->getCallReturnType(S.Context);
734   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
735   QualType BuiltinTy = S.Context.getFunctionType(
736       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
737   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
738 
739   Builtin =
740       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
741 
742   BuiltinCall->setType(CE->getType());
743   BuiltinCall->setValueKind(CE->getValueKind());
744   BuiltinCall->setObjectKind(CE->getObjectKind());
745   BuiltinCall->setCallee(Builtin);
746   BuiltinCall->setArg(1, ChainResult.get());
747 
748   return false;
749 }
750 
751 namespace {
752 
753 class ScanfDiagnosticFormatHandler
754     : public analyze_format_string::FormatStringHandler {
755   // Accepts the argument index (relative to the first destination index) of the
756   // argument whose size we want.
757   using ComputeSizeFunction =
758       llvm::function_ref<Optional<llvm::APSInt>(unsigned)>;
759 
760   // Accepts the argument index (relative to the first destination index), the
761   // destination size, and the source size).
762   using DiagnoseFunction =
763       llvm::function_ref<void(unsigned, unsigned, unsigned)>;
764 
765   ComputeSizeFunction ComputeSizeArgument;
766   DiagnoseFunction Diagnose;
767 
768 public:
769   ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
770                                DiagnoseFunction Diagnose)
771       : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
772 
773   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
774                             const char *StartSpecifier,
775                             unsigned specifierLen) override {
776     if (!FS.consumesDataArgument())
777       return true;
778 
779     unsigned NulByte = 0;
780     switch ((FS.getConversionSpecifier().getKind())) {
781     default:
782       return true;
783     case analyze_format_string::ConversionSpecifier::sArg:
784     case analyze_format_string::ConversionSpecifier::ScanListArg:
785       NulByte = 1;
786       break;
787     case analyze_format_string::ConversionSpecifier::cArg:
788       break;
789     }
790 
791     analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
792     if (FW.getHowSpecified() !=
793         analyze_format_string::OptionalAmount::HowSpecified::Constant)
794       return true;
795 
796     unsigned SourceSize = FW.getConstantAmount() + NulByte;
797 
798     Optional<llvm::APSInt> DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
799     if (!DestSizeAPS)
800       return true;
801 
802     unsigned DestSize = DestSizeAPS->getZExtValue();
803 
804     if (DestSize < SourceSize)
805       Diagnose(FS.getArgIndex(), DestSize, SourceSize);
806 
807     return true;
808   }
809 };
810 
811 class EstimateSizeFormatHandler
812     : public analyze_format_string::FormatStringHandler {
813   size_t Size;
814 
815 public:
816   EstimateSizeFormatHandler(StringRef Format)
817       : Size(std::min(Format.find(0), Format.size()) +
818              1 /* null byte always written by sprintf */) {}
819 
820   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
821                              const char *, unsigned SpecifierLen,
822                              const TargetInfo &) override {
823 
824     const size_t FieldWidth = computeFieldWidth(FS);
825     const size_t Precision = computePrecision(FS);
826 
827     // The actual format.
828     switch (FS.getConversionSpecifier().getKind()) {
829     // Just a char.
830     case analyze_format_string::ConversionSpecifier::cArg:
831     case analyze_format_string::ConversionSpecifier::CArg:
832       Size += std::max(FieldWidth, (size_t)1);
833       break;
834     // Just an integer.
835     case analyze_format_string::ConversionSpecifier::dArg:
836     case analyze_format_string::ConversionSpecifier::DArg:
837     case analyze_format_string::ConversionSpecifier::iArg:
838     case analyze_format_string::ConversionSpecifier::oArg:
839     case analyze_format_string::ConversionSpecifier::OArg:
840     case analyze_format_string::ConversionSpecifier::uArg:
841     case analyze_format_string::ConversionSpecifier::UArg:
842     case analyze_format_string::ConversionSpecifier::xArg:
843     case analyze_format_string::ConversionSpecifier::XArg:
844       Size += std::max(FieldWidth, Precision);
845       break;
846 
847     // %g style conversion switches between %f or %e style dynamically.
848     // %f always takes less space, so default to it.
849     case analyze_format_string::ConversionSpecifier::gArg:
850     case analyze_format_string::ConversionSpecifier::GArg:
851 
852     // Floating point number in the form '[+]ddd.ddd'.
853     case analyze_format_string::ConversionSpecifier::fArg:
854     case analyze_format_string::ConversionSpecifier::FArg:
855       Size += std::max(FieldWidth, 1 /* integer part */ +
856                                        (Precision ? 1 + Precision
857                                                   : 0) /* period + decimal */);
858       break;
859 
860     // Floating point number in the form '[-]d.ddde[+-]dd'.
861     case analyze_format_string::ConversionSpecifier::eArg:
862     case analyze_format_string::ConversionSpecifier::EArg:
863       Size +=
864           std::max(FieldWidth,
865                    1 /* integer part */ +
866                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
867                        1 /* e or E letter */ + 2 /* exponent */);
868       break;
869 
870     // Floating point number in the form '[-]0xh.hhhhp±dd'.
871     case analyze_format_string::ConversionSpecifier::aArg:
872     case analyze_format_string::ConversionSpecifier::AArg:
873       Size +=
874           std::max(FieldWidth,
875                    2 /* 0x */ + 1 /* integer part */ +
876                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
877                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
878       break;
879 
880     // Just a string.
881     case analyze_format_string::ConversionSpecifier::sArg:
882     case analyze_format_string::ConversionSpecifier::SArg:
883       Size += FieldWidth;
884       break;
885 
886     // Just a pointer in the form '0xddd'.
887     case analyze_format_string::ConversionSpecifier::pArg:
888       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
889       break;
890 
891     // A plain percent.
892     case analyze_format_string::ConversionSpecifier::PercentArg:
893       Size += 1;
894       break;
895 
896     default:
897       break;
898     }
899 
900     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
901 
902     if (FS.hasAlternativeForm()) {
903       switch (FS.getConversionSpecifier().getKind()) {
904       default:
905         break;
906       // Force a leading '0'.
907       case analyze_format_string::ConversionSpecifier::oArg:
908         Size += 1;
909         break;
910       // Force a leading '0x'.
911       case analyze_format_string::ConversionSpecifier::xArg:
912       case analyze_format_string::ConversionSpecifier::XArg:
913         Size += 2;
914         break;
915       // Force a period '.' before decimal, even if precision is 0.
916       case analyze_format_string::ConversionSpecifier::aArg:
917       case analyze_format_string::ConversionSpecifier::AArg:
918       case analyze_format_string::ConversionSpecifier::eArg:
919       case analyze_format_string::ConversionSpecifier::EArg:
920       case analyze_format_string::ConversionSpecifier::fArg:
921       case analyze_format_string::ConversionSpecifier::FArg:
922       case analyze_format_string::ConversionSpecifier::gArg:
923       case analyze_format_string::ConversionSpecifier::GArg:
924         Size += (Precision ? 0 : 1);
925         break;
926       }
927     }
928     assert(SpecifierLen <= Size && "no underflow");
929     Size -= SpecifierLen;
930     return true;
931   }
932 
933   size_t getSizeLowerBound() const { return Size; }
934 
935 private:
936   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
937     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
938     size_t FieldWidth = 0;
939     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
940       FieldWidth = FW.getConstantAmount();
941     return FieldWidth;
942   }
943 
944   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
945     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
946     size_t Precision = 0;
947 
948     // See man 3 printf for default precision value based on the specifier.
949     switch (FW.getHowSpecified()) {
950     case analyze_format_string::OptionalAmount::NotSpecified:
951       switch (FS.getConversionSpecifier().getKind()) {
952       default:
953         break;
954       case analyze_format_string::ConversionSpecifier::dArg: // %d
955       case analyze_format_string::ConversionSpecifier::DArg: // %D
956       case analyze_format_string::ConversionSpecifier::iArg: // %i
957         Precision = 1;
958         break;
959       case analyze_format_string::ConversionSpecifier::oArg: // %d
960       case analyze_format_string::ConversionSpecifier::OArg: // %D
961       case analyze_format_string::ConversionSpecifier::uArg: // %d
962       case analyze_format_string::ConversionSpecifier::UArg: // %D
963       case analyze_format_string::ConversionSpecifier::xArg: // %d
964       case analyze_format_string::ConversionSpecifier::XArg: // %D
965         Precision = 1;
966         break;
967       case analyze_format_string::ConversionSpecifier::fArg: // %f
968       case analyze_format_string::ConversionSpecifier::FArg: // %F
969       case analyze_format_string::ConversionSpecifier::eArg: // %e
970       case analyze_format_string::ConversionSpecifier::EArg: // %E
971       case analyze_format_string::ConversionSpecifier::gArg: // %g
972       case analyze_format_string::ConversionSpecifier::GArg: // %G
973         Precision = 6;
974         break;
975       case analyze_format_string::ConversionSpecifier::pArg: // %d
976         Precision = 1;
977         break;
978       }
979       break;
980     case analyze_format_string::OptionalAmount::Constant:
981       Precision = FW.getConstantAmount();
982       break;
983     default:
984       break;
985     }
986     return Precision;
987   }
988 };
989 
990 } // namespace
991 
992 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
993                                                CallExpr *TheCall) {
994   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
995       isConstantEvaluated())
996     return;
997 
998   bool UseDABAttr = false;
999   const FunctionDecl *UseDecl = FD;
1000 
1001   const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1002   if (DABAttr) {
1003     UseDecl = DABAttr->getFunction();
1004     assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1005     UseDABAttr = true;
1006   }
1007 
1008   unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1009 
1010   if (!BuiltinID)
1011     return;
1012 
1013   const TargetInfo &TI = getASTContext().getTargetInfo();
1014   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1015 
1016   auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> {
1017     // If we refer to a diagnose_as_builtin attribute, we need to change the
1018     // argument index to refer to the arguments of the called function. Unless
1019     // the index is out of bounds, which presumably means it's a variadic
1020     // function.
1021     if (!UseDABAttr)
1022       return Index;
1023     unsigned DABIndices = DABAttr->argIndices_size();
1024     unsigned NewIndex = Index < DABIndices
1025                             ? DABAttr->argIndices_begin()[Index]
1026                             : Index - DABIndices + FD->getNumParams();
1027     if (NewIndex >= TheCall->getNumArgs())
1028       return llvm::None;
1029     return NewIndex;
1030   };
1031 
1032   auto ComputeExplicitObjectSizeArgument =
1033       [&](unsigned Index) -> Optional<llvm::APSInt> {
1034     Optional<unsigned> IndexOptional = TranslateIndex(Index);
1035     if (!IndexOptional)
1036       return llvm::None;
1037     unsigned NewIndex = IndexOptional.getValue();
1038     Expr::EvalResult Result;
1039     Expr *SizeArg = TheCall->getArg(NewIndex);
1040     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1041       return llvm::None;
1042     llvm::APSInt Integer = Result.Val.getInt();
1043     Integer.setIsUnsigned(true);
1044     return Integer;
1045   };
1046 
1047   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
1048     // If the parameter has a pass_object_size attribute, then we should use its
1049     // (potentially) more strict checking mode. Otherwise, conservatively assume
1050     // type 0.
1051     int BOSType = 0;
1052     // This check can fail for variadic functions.
1053     if (Index < FD->getNumParams()) {
1054       if (const auto *POS =
1055               FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1056         BOSType = POS->getType();
1057     }
1058 
1059     Optional<unsigned> IndexOptional = TranslateIndex(Index);
1060     if (!IndexOptional)
1061       return llvm::None;
1062     unsigned NewIndex = IndexOptional.getValue();
1063 
1064     const Expr *ObjArg = TheCall->getArg(NewIndex);
1065     uint64_t Result;
1066     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1067       return llvm::None;
1068 
1069     // Get the object size in the target's size_t width.
1070     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1071   };
1072 
1073   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
1074     Optional<unsigned> IndexOptional = TranslateIndex(Index);
1075     if (!IndexOptional)
1076       return llvm::None;
1077     unsigned NewIndex = IndexOptional.getValue();
1078 
1079     const Expr *ObjArg = TheCall->getArg(NewIndex);
1080     uint64_t Result;
1081     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1082       return llvm::None;
1083     // Add 1 for null byte.
1084     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1085   };
1086 
1087   Optional<llvm::APSInt> SourceSize;
1088   Optional<llvm::APSInt> DestinationSize;
1089   unsigned DiagID = 0;
1090   bool IsChkVariant = false;
1091 
1092   auto GetFunctionName = [&]() {
1093     StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
1094     // Skim off the details of whichever builtin was called to produce a better
1095     // diagnostic, as it's unlikely that the user wrote the __builtin
1096     // explicitly.
1097     if (IsChkVariant) {
1098       FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1099       FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1100     } else if (FunctionName.startswith("__builtin_")) {
1101       FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
1102     }
1103     return FunctionName;
1104   };
1105 
1106   switch (BuiltinID) {
1107   default:
1108     return;
1109   case Builtin::BI__builtin_strcpy:
1110   case Builtin::BIstrcpy: {
1111     DiagID = diag::warn_fortify_strlen_overflow;
1112     SourceSize = ComputeStrLenArgument(1);
1113     DestinationSize = ComputeSizeArgument(0);
1114     break;
1115   }
1116 
1117   case Builtin::BI__builtin___strcpy_chk: {
1118     DiagID = diag::warn_fortify_strlen_overflow;
1119     SourceSize = ComputeStrLenArgument(1);
1120     DestinationSize = ComputeExplicitObjectSizeArgument(2);
1121     IsChkVariant = true;
1122     break;
1123   }
1124 
1125   case Builtin::BIscanf:
1126   case Builtin::BIfscanf:
1127   case Builtin::BIsscanf: {
1128     unsigned FormatIndex = 1;
1129     unsigned DataIndex = 2;
1130     if (BuiltinID == Builtin::BIscanf) {
1131       FormatIndex = 0;
1132       DataIndex = 1;
1133     }
1134 
1135     const auto *FormatExpr =
1136         TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1137 
1138     const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1139     if (!Format)
1140       return;
1141 
1142     if (!Format->isAscii() && !Format->isUTF8())
1143       return;
1144 
1145     auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1146                         unsigned SourceSize) {
1147       DiagID = diag::warn_fortify_scanf_overflow;
1148       unsigned Index = ArgIndex + DataIndex;
1149       StringRef FunctionName = GetFunctionName();
1150       DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1151                           PDiag(DiagID) << FunctionName << (Index + 1)
1152                                         << DestSize << SourceSize);
1153     };
1154 
1155     StringRef FormatStrRef = Format->getString();
1156     auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1157       return ComputeSizeArgument(Index + DataIndex);
1158     };
1159     ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1160     const char *FormatBytes = FormatStrRef.data();
1161     const ConstantArrayType *T =
1162         Context.getAsConstantArrayType(Format->getType());
1163     assert(T && "String literal not of constant array type!");
1164     size_t TypeSize = T->getSize().getZExtValue();
1165 
1166     // In case there's a null byte somewhere.
1167     size_t StrLen =
1168         std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1169 
1170     analyze_format_string::ParseScanfString(H, FormatBytes,
1171                                             FormatBytes + StrLen, getLangOpts(),
1172                                             Context.getTargetInfo());
1173 
1174     // Unlike the other cases, in this one we have already issued the diagnostic
1175     // here, so no need to continue (because unlike the other cases, here the
1176     // diagnostic refers to the argument number).
1177     return;
1178   }
1179 
1180   case Builtin::BIsprintf:
1181   case Builtin::BI__builtin___sprintf_chk: {
1182     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1183     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1184 
1185     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
1186 
1187       if (!Format->isAscii() && !Format->isUTF8())
1188         return;
1189 
1190       StringRef FormatStrRef = Format->getString();
1191       EstimateSizeFormatHandler H(FormatStrRef);
1192       const char *FormatBytes = FormatStrRef.data();
1193       const ConstantArrayType *T =
1194           Context.getAsConstantArrayType(Format->getType());
1195       assert(T && "String literal not of constant array type!");
1196       size_t TypeSize = T->getSize().getZExtValue();
1197 
1198       // In case there's a null byte somewhere.
1199       size_t StrLen =
1200           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1201       if (!analyze_format_string::ParsePrintfString(
1202               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1203               Context.getTargetInfo(), false)) {
1204         DiagID = diag::warn_fortify_source_format_overflow;
1205         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1206                          .extOrTrunc(SizeTypeWidth);
1207         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1208           DestinationSize = ComputeExplicitObjectSizeArgument(2);
1209           IsChkVariant = true;
1210         } else {
1211           DestinationSize = ComputeSizeArgument(0);
1212         }
1213         break;
1214       }
1215     }
1216     return;
1217   }
1218   case Builtin::BI__builtin___memcpy_chk:
1219   case Builtin::BI__builtin___memmove_chk:
1220   case Builtin::BI__builtin___memset_chk:
1221   case Builtin::BI__builtin___strlcat_chk:
1222   case Builtin::BI__builtin___strlcpy_chk:
1223   case Builtin::BI__builtin___strncat_chk:
1224   case Builtin::BI__builtin___strncpy_chk:
1225   case Builtin::BI__builtin___stpncpy_chk:
1226   case Builtin::BI__builtin___memccpy_chk:
1227   case Builtin::BI__builtin___mempcpy_chk: {
1228     DiagID = diag::warn_builtin_chk_overflow;
1229     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1230     DestinationSize =
1231         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1232     IsChkVariant = true;
1233     break;
1234   }
1235 
1236   case Builtin::BI__builtin___snprintf_chk:
1237   case Builtin::BI__builtin___vsnprintf_chk: {
1238     DiagID = diag::warn_builtin_chk_overflow;
1239     SourceSize = ComputeExplicitObjectSizeArgument(1);
1240     DestinationSize = ComputeExplicitObjectSizeArgument(3);
1241     IsChkVariant = true;
1242     break;
1243   }
1244 
1245   case Builtin::BIstrncat:
1246   case Builtin::BI__builtin_strncat:
1247   case Builtin::BIstrncpy:
1248   case Builtin::BI__builtin_strncpy:
1249   case Builtin::BIstpncpy:
1250   case Builtin::BI__builtin_stpncpy: {
1251     // Whether these functions overflow depends on the runtime strlen of the
1252     // string, not just the buffer size, so emitting the "always overflow"
1253     // diagnostic isn't quite right. We should still diagnose passing a buffer
1254     // size larger than the destination buffer though; this is a runtime abort
1255     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1256     DiagID = diag::warn_fortify_source_size_mismatch;
1257     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1258     DestinationSize = ComputeSizeArgument(0);
1259     break;
1260   }
1261 
1262   case Builtin::BImemcpy:
1263   case Builtin::BI__builtin_memcpy:
1264   case Builtin::BImemmove:
1265   case Builtin::BI__builtin_memmove:
1266   case Builtin::BImemset:
1267   case Builtin::BI__builtin_memset:
1268   case Builtin::BImempcpy:
1269   case Builtin::BI__builtin_mempcpy: {
1270     DiagID = diag::warn_fortify_source_overflow;
1271     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1272     DestinationSize = ComputeSizeArgument(0);
1273     break;
1274   }
1275   case Builtin::BIsnprintf:
1276   case Builtin::BI__builtin_snprintf:
1277   case Builtin::BIvsnprintf:
1278   case Builtin::BI__builtin_vsnprintf: {
1279     DiagID = diag::warn_fortify_source_size_mismatch;
1280     SourceSize = ComputeExplicitObjectSizeArgument(1);
1281     DestinationSize = ComputeSizeArgument(0);
1282     break;
1283   }
1284   }
1285 
1286   if (!SourceSize || !DestinationSize ||
1287       llvm::APSInt::compareValues(SourceSize.getValue(),
1288                                   DestinationSize.getValue()) <= 0)
1289     return;
1290 
1291   StringRef FunctionName = GetFunctionName();
1292 
1293   SmallString<16> DestinationStr;
1294   SmallString<16> SourceStr;
1295   DestinationSize->toString(DestinationStr, /*Radix=*/10);
1296   SourceSize->toString(SourceStr, /*Radix=*/10);
1297   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1298                       PDiag(DiagID)
1299                           << FunctionName << DestinationStr << SourceStr);
1300 }
1301 
1302 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1303                                      Scope::ScopeFlags NeededScopeFlags,
1304                                      unsigned DiagID) {
1305   // Scopes aren't available during instantiation. Fortunately, builtin
1306   // functions cannot be template args so they cannot be formed through template
1307   // instantiation. Therefore checking once during the parse is sufficient.
1308   if (SemaRef.inTemplateInstantiation())
1309     return false;
1310 
1311   Scope *S = SemaRef.getCurScope();
1312   while (S && !S->isSEHExceptScope())
1313     S = S->getParent();
1314   if (!S || !(S->getFlags() & NeededScopeFlags)) {
1315     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1316     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1317         << DRE->getDecl()->getIdentifier();
1318     return true;
1319   }
1320 
1321   return false;
1322 }
1323 
1324 static inline bool isBlockPointer(Expr *Arg) {
1325   return Arg->getType()->isBlockPointerType();
1326 }
1327 
1328 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
1329 /// void*, which is a requirement of device side enqueue.
1330 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
1331   const BlockPointerType *BPT =
1332       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1333   ArrayRef<QualType> Params =
1334       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
1335   unsigned ArgCounter = 0;
1336   bool IllegalParams = false;
1337   // Iterate through the block parameters until either one is found that is not
1338   // a local void*, or the block is valid.
1339   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
1340        I != E; ++I, ++ArgCounter) {
1341     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
1342         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1343             LangAS::opencl_local) {
1344       // Get the location of the error. If a block literal has been passed
1345       // (BlockExpr) then we can point straight to the offending argument,
1346       // else we just point to the variable reference.
1347       SourceLocation ErrorLoc;
1348       if (isa<BlockExpr>(BlockArg)) {
1349         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1350         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1351       } else if (isa<DeclRefExpr>(BlockArg)) {
1352         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1353       }
1354       S.Diag(ErrorLoc,
1355              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1356       IllegalParams = true;
1357     }
1358   }
1359 
1360   return IllegalParams;
1361 }
1362 
1363 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
1364   // OpenCL device can support extension but not the feature as extension
1365   // requires subgroup independent forward progress, but subgroup independent
1366   // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature.
1367   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) &&
1368       !S.getOpenCLOptions().isSupported("__opencl_c_subgroups",
1369                                         S.getLangOpts())) {
1370     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1371         << 1 << Call->getDirectCallee()
1372         << "cl_khr_subgroups or __opencl_c_subgroups";
1373     return true;
1374   }
1375   return false;
1376 }
1377 
1378 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1379   if (checkArgCount(S, TheCall, 2))
1380     return true;
1381 
1382   if (checkOpenCLSubgroupExt(S, TheCall))
1383     return true;
1384 
1385   // First argument is an ndrange_t type.
1386   Expr *NDRangeArg = TheCall->getArg(0);
1387   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1388     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1389         << TheCall->getDirectCallee() << "'ndrange_t'";
1390     return true;
1391   }
1392 
1393   Expr *BlockArg = TheCall->getArg(1);
1394   if (!isBlockPointer(BlockArg)) {
1395     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1396         << TheCall->getDirectCallee() << "block";
1397     return true;
1398   }
1399   return checkOpenCLBlockArgs(S, BlockArg);
1400 }
1401 
1402 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1403 /// get_kernel_work_group_size
1404 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1405 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1406   if (checkArgCount(S, TheCall, 1))
1407     return true;
1408 
1409   Expr *BlockArg = TheCall->getArg(0);
1410   if (!isBlockPointer(BlockArg)) {
1411     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1412         << TheCall->getDirectCallee() << "block";
1413     return true;
1414   }
1415   return checkOpenCLBlockArgs(S, BlockArg);
1416 }
1417 
1418 /// Diagnose integer type and any valid implicit conversion to it.
1419 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1420                                       const QualType &IntType);
1421 
1422 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1423                                             unsigned Start, unsigned End) {
1424   bool IllegalParams = false;
1425   for (unsigned I = Start; I <= End; ++I)
1426     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1427                                               S.Context.getSizeType());
1428   return IllegalParams;
1429 }
1430 
1431 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1432 /// 'local void*' parameter of passed block.
1433 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1434                                            Expr *BlockArg,
1435                                            unsigned NumNonVarArgs) {
1436   const BlockPointerType *BPT =
1437       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1438   unsigned NumBlockParams =
1439       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1440   unsigned TotalNumArgs = TheCall->getNumArgs();
1441 
1442   // For each argument passed to the block, a corresponding uint needs to
1443   // be passed to describe the size of the local memory.
1444   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1445     S.Diag(TheCall->getBeginLoc(),
1446            diag::err_opencl_enqueue_kernel_local_size_args);
1447     return true;
1448   }
1449 
1450   // Check that the sizes of the local memory are specified by integers.
1451   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1452                                          TotalNumArgs - 1);
1453 }
1454 
1455 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1456 /// overload formats specified in Table 6.13.17.1.
1457 /// int enqueue_kernel(queue_t queue,
1458 ///                    kernel_enqueue_flags_t flags,
1459 ///                    const ndrange_t ndrange,
1460 ///                    void (^block)(void))
1461 /// int enqueue_kernel(queue_t queue,
1462 ///                    kernel_enqueue_flags_t flags,
1463 ///                    const ndrange_t ndrange,
1464 ///                    uint num_events_in_wait_list,
1465 ///                    clk_event_t *event_wait_list,
1466 ///                    clk_event_t *event_ret,
1467 ///                    void (^block)(void))
1468 /// int enqueue_kernel(queue_t queue,
1469 ///                    kernel_enqueue_flags_t flags,
1470 ///                    const ndrange_t ndrange,
1471 ///                    void (^block)(local void*, ...),
1472 ///                    uint size0, ...)
1473 /// int enqueue_kernel(queue_t queue,
1474 ///                    kernel_enqueue_flags_t flags,
1475 ///                    const ndrange_t ndrange,
1476 ///                    uint num_events_in_wait_list,
1477 ///                    clk_event_t *event_wait_list,
1478 ///                    clk_event_t *event_ret,
1479 ///                    void (^block)(local void*, ...),
1480 ///                    uint size0, ...)
1481 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1482   unsigned NumArgs = TheCall->getNumArgs();
1483 
1484   if (NumArgs < 4) {
1485     S.Diag(TheCall->getBeginLoc(),
1486            diag::err_typecheck_call_too_few_args_at_least)
1487         << 0 << 4 << NumArgs;
1488     return true;
1489   }
1490 
1491   Expr *Arg0 = TheCall->getArg(0);
1492   Expr *Arg1 = TheCall->getArg(1);
1493   Expr *Arg2 = TheCall->getArg(2);
1494   Expr *Arg3 = TheCall->getArg(3);
1495 
1496   // First argument always needs to be a queue_t type.
1497   if (!Arg0->getType()->isQueueT()) {
1498     S.Diag(TheCall->getArg(0)->getBeginLoc(),
1499            diag::err_opencl_builtin_expected_type)
1500         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1501     return true;
1502   }
1503 
1504   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1505   if (!Arg1->getType()->isIntegerType()) {
1506     S.Diag(TheCall->getArg(1)->getBeginLoc(),
1507            diag::err_opencl_builtin_expected_type)
1508         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1509     return true;
1510   }
1511 
1512   // Third argument is always an ndrange_t type.
1513   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1514     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1515            diag::err_opencl_builtin_expected_type)
1516         << TheCall->getDirectCallee() << "'ndrange_t'";
1517     return true;
1518   }
1519 
1520   // With four arguments, there is only one form that the function could be
1521   // called in: no events and no variable arguments.
1522   if (NumArgs == 4) {
1523     // check that the last argument is the right block type.
1524     if (!isBlockPointer(Arg3)) {
1525       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1526           << TheCall->getDirectCallee() << "block";
1527       return true;
1528     }
1529     // we have a block type, check the prototype
1530     const BlockPointerType *BPT =
1531         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1532     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1533       S.Diag(Arg3->getBeginLoc(),
1534              diag::err_opencl_enqueue_kernel_blocks_no_args);
1535       return true;
1536     }
1537     return false;
1538   }
1539   // we can have block + varargs.
1540   if (isBlockPointer(Arg3))
1541     return (checkOpenCLBlockArgs(S, Arg3) ||
1542             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1543   // last two cases with either exactly 7 args or 7 args and varargs.
1544   if (NumArgs >= 7) {
1545     // check common block argument.
1546     Expr *Arg6 = TheCall->getArg(6);
1547     if (!isBlockPointer(Arg6)) {
1548       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1549           << TheCall->getDirectCallee() << "block";
1550       return true;
1551     }
1552     if (checkOpenCLBlockArgs(S, Arg6))
1553       return true;
1554 
1555     // Forth argument has to be any integer type.
1556     if (!Arg3->getType()->isIntegerType()) {
1557       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1558              diag::err_opencl_builtin_expected_type)
1559           << TheCall->getDirectCallee() << "integer";
1560       return true;
1561     }
1562     // check remaining common arguments.
1563     Expr *Arg4 = TheCall->getArg(4);
1564     Expr *Arg5 = TheCall->getArg(5);
1565 
1566     // Fifth argument is always passed as a pointer to clk_event_t.
1567     if (!Arg4->isNullPointerConstant(S.Context,
1568                                      Expr::NPC_ValueDependentIsNotNull) &&
1569         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1570       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1571              diag::err_opencl_builtin_expected_type)
1572           << TheCall->getDirectCallee()
1573           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1574       return true;
1575     }
1576 
1577     // Sixth argument is always passed as a pointer to clk_event_t.
1578     if (!Arg5->isNullPointerConstant(S.Context,
1579                                      Expr::NPC_ValueDependentIsNotNull) &&
1580         !(Arg5->getType()->isPointerType() &&
1581           Arg5->getType()->getPointeeType()->isClkEventT())) {
1582       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1583              diag::err_opencl_builtin_expected_type)
1584           << TheCall->getDirectCallee()
1585           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1586       return true;
1587     }
1588 
1589     if (NumArgs == 7)
1590       return false;
1591 
1592     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1593   }
1594 
1595   // None of the specific case has been detected, give generic error
1596   S.Diag(TheCall->getBeginLoc(),
1597          diag::err_opencl_enqueue_kernel_incorrect_args);
1598   return true;
1599 }
1600 
1601 /// Returns OpenCL access qual.
1602 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1603     return D->getAttr<OpenCLAccessAttr>();
1604 }
1605 
1606 /// Returns true if pipe element type is different from the pointer.
1607 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1608   const Expr *Arg0 = Call->getArg(0);
1609   // First argument type should always be pipe.
1610   if (!Arg0->getType()->isPipeType()) {
1611     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1612         << Call->getDirectCallee() << Arg0->getSourceRange();
1613     return true;
1614   }
1615   OpenCLAccessAttr *AccessQual =
1616       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1617   // Validates the access qualifier is compatible with the call.
1618   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1619   // read_only and write_only, and assumed to be read_only if no qualifier is
1620   // specified.
1621   switch (Call->getDirectCallee()->getBuiltinID()) {
1622   case Builtin::BIread_pipe:
1623   case Builtin::BIreserve_read_pipe:
1624   case Builtin::BIcommit_read_pipe:
1625   case Builtin::BIwork_group_reserve_read_pipe:
1626   case Builtin::BIsub_group_reserve_read_pipe:
1627   case Builtin::BIwork_group_commit_read_pipe:
1628   case Builtin::BIsub_group_commit_read_pipe:
1629     if (!(!AccessQual || AccessQual->isReadOnly())) {
1630       S.Diag(Arg0->getBeginLoc(),
1631              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1632           << "read_only" << Arg0->getSourceRange();
1633       return true;
1634     }
1635     break;
1636   case Builtin::BIwrite_pipe:
1637   case Builtin::BIreserve_write_pipe:
1638   case Builtin::BIcommit_write_pipe:
1639   case Builtin::BIwork_group_reserve_write_pipe:
1640   case Builtin::BIsub_group_reserve_write_pipe:
1641   case Builtin::BIwork_group_commit_write_pipe:
1642   case Builtin::BIsub_group_commit_write_pipe:
1643     if (!(AccessQual && AccessQual->isWriteOnly())) {
1644       S.Diag(Arg0->getBeginLoc(),
1645              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1646           << "write_only" << Arg0->getSourceRange();
1647       return true;
1648     }
1649     break;
1650   default:
1651     break;
1652   }
1653   return false;
1654 }
1655 
1656 /// Returns true if pipe element type is different from the pointer.
1657 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1658   const Expr *Arg0 = Call->getArg(0);
1659   const Expr *ArgIdx = Call->getArg(Idx);
1660   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1661   const QualType EltTy = PipeTy->getElementType();
1662   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1663   // The Idx argument should be a pointer and the type of the pointer and
1664   // the type of pipe element should also be the same.
1665   if (!ArgTy ||
1666       !S.Context.hasSameType(
1667           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1668     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1669         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1670         << ArgIdx->getType() << ArgIdx->getSourceRange();
1671     return true;
1672   }
1673   return false;
1674 }
1675 
1676 // Performs semantic analysis for the read/write_pipe call.
1677 // \param S Reference to the semantic analyzer.
1678 // \param Call A pointer to the builtin call.
1679 // \return True if a semantic error has been found, false otherwise.
1680 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1681   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1682   // functions have two forms.
1683   switch (Call->getNumArgs()) {
1684   case 2:
1685     if (checkOpenCLPipeArg(S, Call))
1686       return true;
1687     // The call with 2 arguments should be
1688     // read/write_pipe(pipe T, T*).
1689     // Check packet type T.
1690     if (checkOpenCLPipePacketType(S, Call, 1))
1691       return true;
1692     break;
1693 
1694   case 4: {
1695     if (checkOpenCLPipeArg(S, Call))
1696       return true;
1697     // The call with 4 arguments should be
1698     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1699     // Check reserve_id_t.
1700     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1701       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1702           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1703           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1704       return true;
1705     }
1706 
1707     // Check the index.
1708     const Expr *Arg2 = Call->getArg(2);
1709     if (!Arg2->getType()->isIntegerType() &&
1710         !Arg2->getType()->isUnsignedIntegerType()) {
1711       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1712           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1713           << Arg2->getType() << Arg2->getSourceRange();
1714       return true;
1715     }
1716 
1717     // Check packet type T.
1718     if (checkOpenCLPipePacketType(S, Call, 3))
1719       return true;
1720   } break;
1721   default:
1722     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1723         << Call->getDirectCallee() << Call->getSourceRange();
1724     return true;
1725   }
1726 
1727   return false;
1728 }
1729 
1730 // Performs a semantic analysis on the {work_group_/sub_group_
1731 //        /_}reserve_{read/write}_pipe
1732 // \param S Reference to the semantic analyzer.
1733 // \param Call The call to the builtin function to be analyzed.
1734 // \return True if a semantic error was found, false otherwise.
1735 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1736   if (checkArgCount(S, Call, 2))
1737     return true;
1738 
1739   if (checkOpenCLPipeArg(S, Call))
1740     return true;
1741 
1742   // Check the reserve size.
1743   if (!Call->getArg(1)->getType()->isIntegerType() &&
1744       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1745     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1746         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1747         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1748     return true;
1749   }
1750 
1751   // Since return type of reserve_read/write_pipe built-in function is
1752   // reserve_id_t, which is not defined in the builtin def file , we used int
1753   // as return type and need to override the return type of these functions.
1754   Call->setType(S.Context.OCLReserveIDTy);
1755 
1756   return false;
1757 }
1758 
1759 // Performs a semantic analysis on {work_group_/sub_group_
1760 //        /_}commit_{read/write}_pipe
1761 // \param S Reference to the semantic analyzer.
1762 // \param Call The call to the builtin function to be analyzed.
1763 // \return True if a semantic error was found, false otherwise.
1764 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1765   if (checkArgCount(S, Call, 2))
1766     return true;
1767 
1768   if (checkOpenCLPipeArg(S, Call))
1769     return true;
1770 
1771   // Check reserve_id_t.
1772   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1773     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1774         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1775         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1776     return true;
1777   }
1778 
1779   return false;
1780 }
1781 
1782 // Performs a semantic analysis on the call to built-in Pipe
1783 //        Query Functions.
1784 // \param S Reference to the semantic analyzer.
1785 // \param Call The call to the builtin function to be analyzed.
1786 // \return True if a semantic error was found, false otherwise.
1787 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1788   if (checkArgCount(S, Call, 1))
1789     return true;
1790 
1791   if (!Call->getArg(0)->getType()->isPipeType()) {
1792     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1793         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1794     return true;
1795   }
1796 
1797   return false;
1798 }
1799 
1800 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1801 // Performs semantic analysis for the to_global/local/private call.
1802 // \param S Reference to the semantic analyzer.
1803 // \param BuiltinID ID of the builtin function.
1804 // \param Call A pointer to the builtin call.
1805 // \return True if a semantic error has been found, false otherwise.
1806 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1807                                     CallExpr *Call) {
1808   if (checkArgCount(S, Call, 1))
1809     return true;
1810 
1811   auto RT = Call->getArg(0)->getType();
1812   if (!RT->isPointerType() || RT->getPointeeType()
1813       .getAddressSpace() == LangAS::opencl_constant) {
1814     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1815         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1816     return true;
1817   }
1818 
1819   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1820     S.Diag(Call->getArg(0)->getBeginLoc(),
1821            diag::warn_opencl_generic_address_space_arg)
1822         << Call->getDirectCallee()->getNameInfo().getAsString()
1823         << Call->getArg(0)->getSourceRange();
1824   }
1825 
1826   RT = RT->getPointeeType();
1827   auto Qual = RT.getQualifiers();
1828   switch (BuiltinID) {
1829   case Builtin::BIto_global:
1830     Qual.setAddressSpace(LangAS::opencl_global);
1831     break;
1832   case Builtin::BIto_local:
1833     Qual.setAddressSpace(LangAS::opencl_local);
1834     break;
1835   case Builtin::BIto_private:
1836     Qual.setAddressSpace(LangAS::opencl_private);
1837     break;
1838   default:
1839     llvm_unreachable("Invalid builtin function");
1840   }
1841   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1842       RT.getUnqualifiedType(), Qual)));
1843 
1844   return false;
1845 }
1846 
1847 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1848   if (checkArgCount(S, TheCall, 1))
1849     return ExprError();
1850 
1851   // Compute __builtin_launder's parameter type from the argument.
1852   // The parameter type is:
1853   //  * The type of the argument if it's not an array or function type,
1854   //  Otherwise,
1855   //  * The decayed argument type.
1856   QualType ParamTy = [&]() {
1857     QualType ArgTy = TheCall->getArg(0)->getType();
1858     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1859       return S.Context.getPointerType(Ty->getElementType());
1860     if (ArgTy->isFunctionType()) {
1861       return S.Context.getPointerType(ArgTy);
1862     }
1863     return ArgTy;
1864   }();
1865 
1866   TheCall->setType(ParamTy);
1867 
1868   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1869     if (!ParamTy->isPointerType())
1870       return 0;
1871     if (ParamTy->isFunctionPointerType())
1872       return 1;
1873     if (ParamTy->isVoidPointerType())
1874       return 2;
1875     return llvm::Optional<unsigned>{};
1876   }();
1877   if (DiagSelect.hasValue()) {
1878     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1879         << DiagSelect.getValue() << TheCall->getSourceRange();
1880     return ExprError();
1881   }
1882 
1883   // We either have an incomplete class type, or we have a class template
1884   // whose instantiation has not been forced. Example:
1885   //
1886   //   template <class T> struct Foo { T value; };
1887   //   Foo<int> *p = nullptr;
1888   //   auto *d = __builtin_launder(p);
1889   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1890                             diag::err_incomplete_type))
1891     return ExprError();
1892 
1893   assert(ParamTy->getPointeeType()->isObjectType() &&
1894          "Unhandled non-object pointer case");
1895 
1896   InitializedEntity Entity =
1897       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1898   ExprResult Arg =
1899       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1900   if (Arg.isInvalid())
1901     return ExprError();
1902   TheCall->setArg(0, Arg.get());
1903 
1904   return TheCall;
1905 }
1906 
1907 // Emit an error and return true if the current object format type is in the
1908 // list of unsupported types.
1909 static bool CheckBuiltinTargetNotInUnsupported(
1910     Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1911     ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
1912   llvm::Triple::ObjectFormatType CurObjFormat =
1913       S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
1914   if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
1915     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1916         << TheCall->getSourceRange();
1917     return true;
1918   }
1919   return false;
1920 }
1921 
1922 // Emit an error and return true if the current architecture is not in the list
1923 // of supported architectures.
1924 static bool
1925 CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1926                               ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1927   llvm::Triple::ArchType CurArch =
1928       S.getASTContext().getTargetInfo().getTriple().getArch();
1929   if (llvm::is_contained(SupportedArchs, CurArch))
1930     return false;
1931   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1932       << TheCall->getSourceRange();
1933   return true;
1934 }
1935 
1936 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1937                                  SourceLocation CallSiteLoc);
1938 
1939 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1940                                       CallExpr *TheCall) {
1941   switch (TI.getTriple().getArch()) {
1942   default:
1943     // Some builtins don't require additional checking, so just consider these
1944     // acceptable.
1945     return false;
1946   case llvm::Triple::arm:
1947   case llvm::Triple::armeb:
1948   case llvm::Triple::thumb:
1949   case llvm::Triple::thumbeb:
1950     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1951   case llvm::Triple::aarch64:
1952   case llvm::Triple::aarch64_32:
1953   case llvm::Triple::aarch64_be:
1954     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1955   case llvm::Triple::bpfeb:
1956   case llvm::Triple::bpfel:
1957     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1958   case llvm::Triple::hexagon:
1959     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1960   case llvm::Triple::mips:
1961   case llvm::Triple::mipsel:
1962   case llvm::Triple::mips64:
1963   case llvm::Triple::mips64el:
1964     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1965   case llvm::Triple::systemz:
1966     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1967   case llvm::Triple::x86:
1968   case llvm::Triple::x86_64:
1969     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1970   case llvm::Triple::ppc:
1971   case llvm::Triple::ppcle:
1972   case llvm::Triple::ppc64:
1973   case llvm::Triple::ppc64le:
1974     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1975   case llvm::Triple::amdgcn:
1976     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1977   case llvm::Triple::riscv32:
1978   case llvm::Triple::riscv64:
1979     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1980   }
1981 }
1982 
1983 ExprResult
1984 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1985                                CallExpr *TheCall) {
1986   ExprResult TheCallResult(TheCall);
1987 
1988   // Find out if any arguments are required to be integer constant expressions.
1989   unsigned ICEArguments = 0;
1990   ASTContext::GetBuiltinTypeError Error;
1991   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1992   if (Error != ASTContext::GE_None)
1993     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1994 
1995   // If any arguments are required to be ICE's, check and diagnose.
1996   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1997     // Skip arguments not required to be ICE's.
1998     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1999 
2000     llvm::APSInt Result;
2001     // If we don't have enough arguments, continue so we can issue better
2002     // diagnostic in checkArgCount(...)
2003     if (ArgNo < TheCall->getNumArgs() &&
2004         SemaBuiltinConstantArg(TheCall, ArgNo, Result))
2005       return true;
2006     ICEArguments &= ~(1 << ArgNo);
2007   }
2008 
2009   switch (BuiltinID) {
2010   case Builtin::BI__builtin___CFStringMakeConstantString:
2011     // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2012     // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2013     if (CheckBuiltinTargetNotInUnsupported(
2014             *this, BuiltinID, TheCall,
2015             {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2016       return ExprError();
2017     assert(TheCall->getNumArgs() == 1 &&
2018            "Wrong # arguments to builtin CFStringMakeConstantString");
2019     if (CheckObjCString(TheCall->getArg(0)))
2020       return ExprError();
2021     break;
2022   case Builtin::BI__builtin_ms_va_start:
2023   case Builtin::BI__builtin_stdarg_start:
2024   case Builtin::BI__builtin_va_start:
2025     if (SemaBuiltinVAStart(BuiltinID, TheCall))
2026       return ExprError();
2027     break;
2028   case Builtin::BI__va_start: {
2029     switch (Context.getTargetInfo().getTriple().getArch()) {
2030     case llvm::Triple::aarch64:
2031     case llvm::Triple::arm:
2032     case llvm::Triple::thumb:
2033       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
2034         return ExprError();
2035       break;
2036     default:
2037       if (SemaBuiltinVAStart(BuiltinID, TheCall))
2038         return ExprError();
2039       break;
2040     }
2041     break;
2042   }
2043 
2044   // The acquire, release, and no fence variants are ARM and AArch64 only.
2045   case Builtin::BI_interlockedbittestandset_acq:
2046   case Builtin::BI_interlockedbittestandset_rel:
2047   case Builtin::BI_interlockedbittestandset_nf:
2048   case Builtin::BI_interlockedbittestandreset_acq:
2049   case Builtin::BI_interlockedbittestandreset_rel:
2050   case Builtin::BI_interlockedbittestandreset_nf:
2051     if (CheckBuiltinTargetInSupported(
2052             *this, BuiltinID, TheCall,
2053             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2054       return ExprError();
2055     break;
2056 
2057   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2058   case Builtin::BI_bittest64:
2059   case Builtin::BI_bittestandcomplement64:
2060   case Builtin::BI_bittestandreset64:
2061   case Builtin::BI_bittestandset64:
2062   case Builtin::BI_interlockedbittestandreset64:
2063   case Builtin::BI_interlockedbittestandset64:
2064     if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
2065                                       {llvm::Triple::x86_64, llvm::Triple::arm,
2066                                        llvm::Triple::thumb,
2067                                        llvm::Triple::aarch64}))
2068       return ExprError();
2069     break;
2070 
2071   case Builtin::BI__builtin_isgreater:
2072   case Builtin::BI__builtin_isgreaterequal:
2073   case Builtin::BI__builtin_isless:
2074   case Builtin::BI__builtin_islessequal:
2075   case Builtin::BI__builtin_islessgreater:
2076   case Builtin::BI__builtin_isunordered:
2077     if (SemaBuiltinUnorderedCompare(TheCall))
2078       return ExprError();
2079     break;
2080   case Builtin::BI__builtin_fpclassify:
2081     if (SemaBuiltinFPClassification(TheCall, 6))
2082       return ExprError();
2083     break;
2084   case Builtin::BI__builtin_isfinite:
2085   case Builtin::BI__builtin_isinf:
2086   case Builtin::BI__builtin_isinf_sign:
2087   case Builtin::BI__builtin_isnan:
2088   case Builtin::BI__builtin_isnormal:
2089   case Builtin::BI__builtin_signbit:
2090   case Builtin::BI__builtin_signbitf:
2091   case Builtin::BI__builtin_signbitl:
2092     if (SemaBuiltinFPClassification(TheCall, 1))
2093       return ExprError();
2094     break;
2095   case Builtin::BI__builtin_shufflevector:
2096     return SemaBuiltinShuffleVector(TheCall);
2097     // TheCall will be freed by the smart pointer here, but that's fine, since
2098     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
2099   case Builtin::BI__builtin_prefetch:
2100     if (SemaBuiltinPrefetch(TheCall))
2101       return ExprError();
2102     break;
2103   case Builtin::BI__builtin_alloca_with_align:
2104   case Builtin::BI__builtin_alloca_with_align_uninitialized:
2105     if (SemaBuiltinAllocaWithAlign(TheCall))
2106       return ExprError();
2107     LLVM_FALLTHROUGH;
2108   case Builtin::BI__builtin_alloca:
2109   case Builtin::BI__builtin_alloca_uninitialized:
2110     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2111         << TheCall->getDirectCallee();
2112     break;
2113   case Builtin::BI__arithmetic_fence:
2114     if (SemaBuiltinArithmeticFence(TheCall))
2115       return ExprError();
2116     break;
2117   case Builtin::BI__assume:
2118   case Builtin::BI__builtin_assume:
2119     if (SemaBuiltinAssume(TheCall))
2120       return ExprError();
2121     break;
2122   case Builtin::BI__builtin_assume_aligned:
2123     if (SemaBuiltinAssumeAligned(TheCall))
2124       return ExprError();
2125     break;
2126   case Builtin::BI__builtin_dynamic_object_size:
2127   case Builtin::BI__builtin_object_size:
2128     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
2129       return ExprError();
2130     break;
2131   case Builtin::BI__builtin_longjmp:
2132     if (SemaBuiltinLongjmp(TheCall))
2133       return ExprError();
2134     break;
2135   case Builtin::BI__builtin_setjmp:
2136     if (SemaBuiltinSetjmp(TheCall))
2137       return ExprError();
2138     break;
2139   case Builtin::BI__builtin_classify_type:
2140     if (checkArgCount(*this, TheCall, 1)) return true;
2141     TheCall->setType(Context.IntTy);
2142     break;
2143   case Builtin::BI__builtin_complex:
2144     if (SemaBuiltinComplex(TheCall))
2145       return ExprError();
2146     break;
2147   case Builtin::BI__builtin_constant_p: {
2148     if (checkArgCount(*this, TheCall, 1)) return true;
2149     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
2150     if (Arg.isInvalid()) return true;
2151     TheCall->setArg(0, Arg.get());
2152     TheCall->setType(Context.IntTy);
2153     break;
2154   }
2155   case Builtin::BI__builtin_launder:
2156     return SemaBuiltinLaunder(*this, TheCall);
2157   case Builtin::BI__sync_fetch_and_add:
2158   case Builtin::BI__sync_fetch_and_add_1:
2159   case Builtin::BI__sync_fetch_and_add_2:
2160   case Builtin::BI__sync_fetch_and_add_4:
2161   case Builtin::BI__sync_fetch_and_add_8:
2162   case Builtin::BI__sync_fetch_and_add_16:
2163   case Builtin::BI__sync_fetch_and_sub:
2164   case Builtin::BI__sync_fetch_and_sub_1:
2165   case Builtin::BI__sync_fetch_and_sub_2:
2166   case Builtin::BI__sync_fetch_and_sub_4:
2167   case Builtin::BI__sync_fetch_and_sub_8:
2168   case Builtin::BI__sync_fetch_and_sub_16:
2169   case Builtin::BI__sync_fetch_and_or:
2170   case Builtin::BI__sync_fetch_and_or_1:
2171   case Builtin::BI__sync_fetch_and_or_2:
2172   case Builtin::BI__sync_fetch_and_or_4:
2173   case Builtin::BI__sync_fetch_and_or_8:
2174   case Builtin::BI__sync_fetch_and_or_16:
2175   case Builtin::BI__sync_fetch_and_and:
2176   case Builtin::BI__sync_fetch_and_and_1:
2177   case Builtin::BI__sync_fetch_and_and_2:
2178   case Builtin::BI__sync_fetch_and_and_4:
2179   case Builtin::BI__sync_fetch_and_and_8:
2180   case Builtin::BI__sync_fetch_and_and_16:
2181   case Builtin::BI__sync_fetch_and_xor:
2182   case Builtin::BI__sync_fetch_and_xor_1:
2183   case Builtin::BI__sync_fetch_and_xor_2:
2184   case Builtin::BI__sync_fetch_and_xor_4:
2185   case Builtin::BI__sync_fetch_and_xor_8:
2186   case Builtin::BI__sync_fetch_and_xor_16:
2187   case Builtin::BI__sync_fetch_and_nand:
2188   case Builtin::BI__sync_fetch_and_nand_1:
2189   case Builtin::BI__sync_fetch_and_nand_2:
2190   case Builtin::BI__sync_fetch_and_nand_4:
2191   case Builtin::BI__sync_fetch_and_nand_8:
2192   case Builtin::BI__sync_fetch_and_nand_16:
2193   case Builtin::BI__sync_add_and_fetch:
2194   case Builtin::BI__sync_add_and_fetch_1:
2195   case Builtin::BI__sync_add_and_fetch_2:
2196   case Builtin::BI__sync_add_and_fetch_4:
2197   case Builtin::BI__sync_add_and_fetch_8:
2198   case Builtin::BI__sync_add_and_fetch_16:
2199   case Builtin::BI__sync_sub_and_fetch:
2200   case Builtin::BI__sync_sub_and_fetch_1:
2201   case Builtin::BI__sync_sub_and_fetch_2:
2202   case Builtin::BI__sync_sub_and_fetch_4:
2203   case Builtin::BI__sync_sub_and_fetch_8:
2204   case Builtin::BI__sync_sub_and_fetch_16:
2205   case Builtin::BI__sync_and_and_fetch:
2206   case Builtin::BI__sync_and_and_fetch_1:
2207   case Builtin::BI__sync_and_and_fetch_2:
2208   case Builtin::BI__sync_and_and_fetch_4:
2209   case Builtin::BI__sync_and_and_fetch_8:
2210   case Builtin::BI__sync_and_and_fetch_16:
2211   case Builtin::BI__sync_or_and_fetch:
2212   case Builtin::BI__sync_or_and_fetch_1:
2213   case Builtin::BI__sync_or_and_fetch_2:
2214   case Builtin::BI__sync_or_and_fetch_4:
2215   case Builtin::BI__sync_or_and_fetch_8:
2216   case Builtin::BI__sync_or_and_fetch_16:
2217   case Builtin::BI__sync_xor_and_fetch:
2218   case Builtin::BI__sync_xor_and_fetch_1:
2219   case Builtin::BI__sync_xor_and_fetch_2:
2220   case Builtin::BI__sync_xor_and_fetch_4:
2221   case Builtin::BI__sync_xor_and_fetch_8:
2222   case Builtin::BI__sync_xor_and_fetch_16:
2223   case Builtin::BI__sync_nand_and_fetch:
2224   case Builtin::BI__sync_nand_and_fetch_1:
2225   case Builtin::BI__sync_nand_and_fetch_2:
2226   case Builtin::BI__sync_nand_and_fetch_4:
2227   case Builtin::BI__sync_nand_and_fetch_8:
2228   case Builtin::BI__sync_nand_and_fetch_16:
2229   case Builtin::BI__sync_val_compare_and_swap:
2230   case Builtin::BI__sync_val_compare_and_swap_1:
2231   case Builtin::BI__sync_val_compare_and_swap_2:
2232   case Builtin::BI__sync_val_compare_and_swap_4:
2233   case Builtin::BI__sync_val_compare_and_swap_8:
2234   case Builtin::BI__sync_val_compare_and_swap_16:
2235   case Builtin::BI__sync_bool_compare_and_swap:
2236   case Builtin::BI__sync_bool_compare_and_swap_1:
2237   case Builtin::BI__sync_bool_compare_and_swap_2:
2238   case Builtin::BI__sync_bool_compare_and_swap_4:
2239   case Builtin::BI__sync_bool_compare_and_swap_8:
2240   case Builtin::BI__sync_bool_compare_and_swap_16:
2241   case Builtin::BI__sync_lock_test_and_set:
2242   case Builtin::BI__sync_lock_test_and_set_1:
2243   case Builtin::BI__sync_lock_test_and_set_2:
2244   case Builtin::BI__sync_lock_test_and_set_4:
2245   case Builtin::BI__sync_lock_test_and_set_8:
2246   case Builtin::BI__sync_lock_test_and_set_16:
2247   case Builtin::BI__sync_lock_release:
2248   case Builtin::BI__sync_lock_release_1:
2249   case Builtin::BI__sync_lock_release_2:
2250   case Builtin::BI__sync_lock_release_4:
2251   case Builtin::BI__sync_lock_release_8:
2252   case Builtin::BI__sync_lock_release_16:
2253   case Builtin::BI__sync_swap:
2254   case Builtin::BI__sync_swap_1:
2255   case Builtin::BI__sync_swap_2:
2256   case Builtin::BI__sync_swap_4:
2257   case Builtin::BI__sync_swap_8:
2258   case Builtin::BI__sync_swap_16:
2259     return SemaBuiltinAtomicOverloaded(TheCallResult);
2260   case Builtin::BI__sync_synchronize:
2261     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2262         << TheCall->getCallee()->getSourceRange();
2263     break;
2264   case Builtin::BI__builtin_nontemporal_load:
2265   case Builtin::BI__builtin_nontemporal_store:
2266     return SemaBuiltinNontemporalOverloaded(TheCallResult);
2267   case Builtin::BI__builtin_memcpy_inline: {
2268     clang::Expr *SizeOp = TheCall->getArg(2);
2269     // We warn about copying to or from `nullptr` pointers when `size` is
2270     // greater than 0. When `size` is value dependent we cannot evaluate its
2271     // value so we bail out.
2272     if (SizeOp->isValueDependent())
2273       break;
2274     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2275       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2276       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2277     }
2278     break;
2279   }
2280 #define BUILTIN(ID, TYPE, ATTRS)
2281 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
2282   case Builtin::BI##ID: \
2283     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
2284 #include "clang/Basic/Builtins.def"
2285   case Builtin::BI__annotation:
2286     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
2287       return ExprError();
2288     break;
2289   case Builtin::BI__builtin_annotation:
2290     if (SemaBuiltinAnnotation(*this, TheCall))
2291       return ExprError();
2292     break;
2293   case Builtin::BI__builtin_addressof:
2294     if (SemaBuiltinAddressof(*this, TheCall))
2295       return ExprError();
2296     break;
2297   case Builtin::BI__builtin_function_start:
2298     if (SemaBuiltinFunctionStart(*this, TheCall))
2299       return ExprError();
2300     break;
2301   case Builtin::BI__builtin_is_aligned:
2302   case Builtin::BI__builtin_align_up:
2303   case Builtin::BI__builtin_align_down:
2304     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
2305       return ExprError();
2306     break;
2307   case Builtin::BI__builtin_add_overflow:
2308   case Builtin::BI__builtin_sub_overflow:
2309   case Builtin::BI__builtin_mul_overflow:
2310     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
2311       return ExprError();
2312     break;
2313   case Builtin::BI__builtin_operator_new:
2314   case Builtin::BI__builtin_operator_delete: {
2315     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2316     ExprResult Res =
2317         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2318     if (Res.isInvalid())
2319       CorrectDelayedTyposInExpr(TheCallResult.get());
2320     return Res;
2321   }
2322   case Builtin::BI__builtin_dump_struct:
2323     return SemaBuiltinDumpStruct(*this, TheCall);
2324   case Builtin::BI__builtin_expect_with_probability: {
2325     // We first want to ensure we are called with 3 arguments
2326     if (checkArgCount(*this, TheCall, 3))
2327       return ExprError();
2328     // then check probability is constant float in range [0.0, 1.0]
2329     const Expr *ProbArg = TheCall->getArg(2);
2330     SmallVector<PartialDiagnosticAt, 8> Notes;
2331     Expr::EvalResult Eval;
2332     Eval.Diag = &Notes;
2333     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2334         !Eval.Val.isFloat()) {
2335       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2336           << ProbArg->getSourceRange();
2337       for (const PartialDiagnosticAt &PDiag : Notes)
2338         Diag(PDiag.first, PDiag.second);
2339       return ExprError();
2340     }
2341     llvm::APFloat Probability = Eval.Val.getFloat();
2342     bool LoseInfo = false;
2343     Probability.convert(llvm::APFloat::IEEEdouble(),
2344                         llvm::RoundingMode::Dynamic, &LoseInfo);
2345     if (!(Probability >= llvm::APFloat(0.0) &&
2346           Probability <= llvm::APFloat(1.0))) {
2347       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2348           << ProbArg->getSourceRange();
2349       return ExprError();
2350     }
2351     break;
2352   }
2353   case Builtin::BI__builtin_preserve_access_index:
2354     if (SemaBuiltinPreserveAI(*this, TheCall))
2355       return ExprError();
2356     break;
2357   case Builtin::BI__builtin_call_with_static_chain:
2358     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2359       return ExprError();
2360     break;
2361   case Builtin::BI__exception_code:
2362   case Builtin::BI_exception_code:
2363     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2364                                  diag::err_seh___except_block))
2365       return ExprError();
2366     break;
2367   case Builtin::BI__exception_info:
2368   case Builtin::BI_exception_info:
2369     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2370                                  diag::err_seh___except_filter))
2371       return ExprError();
2372     break;
2373   case Builtin::BI__GetExceptionInfo:
2374     if (checkArgCount(*this, TheCall, 1))
2375       return ExprError();
2376 
2377     if (CheckCXXThrowOperand(
2378             TheCall->getBeginLoc(),
2379             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2380             TheCall))
2381       return ExprError();
2382 
2383     TheCall->setType(Context.VoidPtrTy);
2384     break;
2385   case Builtin::BIaddressof:
2386   case Builtin::BI__addressof:
2387   case Builtin::BIforward:
2388   case Builtin::BImove:
2389   case Builtin::BImove_if_noexcept:
2390   case Builtin::BIas_const: {
2391     // These are all expected to be of the form
2392     //   T &/&&/* f(U &/&&)
2393     // where T and U only differ in qualification.
2394     if (checkArgCount(*this, TheCall, 1))
2395       return ExprError();
2396     QualType Param = FDecl->getParamDecl(0)->getType();
2397     QualType Result = FDecl->getReturnType();
2398     bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
2399                           BuiltinID == Builtin::BI__addressof;
2400     if (!(Param->isReferenceType() &&
2401           (ReturnsPointer ? Result->isPointerType()
2402                           : Result->isReferenceType()) &&
2403           Context.hasSameUnqualifiedType(Param->getPointeeType(),
2404                                          Result->getPointeeType()))) {
2405       Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
2406           << FDecl;
2407       return ExprError();
2408     }
2409     break;
2410   }
2411   // OpenCL v2.0, s6.13.16 - Pipe functions
2412   case Builtin::BIread_pipe:
2413   case Builtin::BIwrite_pipe:
2414     // Since those two functions are declared with var args, we need a semantic
2415     // check for the argument.
2416     if (SemaBuiltinRWPipe(*this, TheCall))
2417       return ExprError();
2418     break;
2419   case Builtin::BIreserve_read_pipe:
2420   case Builtin::BIreserve_write_pipe:
2421   case Builtin::BIwork_group_reserve_read_pipe:
2422   case Builtin::BIwork_group_reserve_write_pipe:
2423     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2424       return ExprError();
2425     break;
2426   case Builtin::BIsub_group_reserve_read_pipe:
2427   case Builtin::BIsub_group_reserve_write_pipe:
2428     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2429         SemaBuiltinReserveRWPipe(*this, TheCall))
2430       return ExprError();
2431     break;
2432   case Builtin::BIcommit_read_pipe:
2433   case Builtin::BIcommit_write_pipe:
2434   case Builtin::BIwork_group_commit_read_pipe:
2435   case Builtin::BIwork_group_commit_write_pipe:
2436     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2437       return ExprError();
2438     break;
2439   case Builtin::BIsub_group_commit_read_pipe:
2440   case Builtin::BIsub_group_commit_write_pipe:
2441     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2442         SemaBuiltinCommitRWPipe(*this, TheCall))
2443       return ExprError();
2444     break;
2445   case Builtin::BIget_pipe_num_packets:
2446   case Builtin::BIget_pipe_max_packets:
2447     if (SemaBuiltinPipePackets(*this, TheCall))
2448       return ExprError();
2449     break;
2450   case Builtin::BIto_global:
2451   case Builtin::BIto_local:
2452   case Builtin::BIto_private:
2453     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2454       return ExprError();
2455     break;
2456   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2457   case Builtin::BIenqueue_kernel:
2458     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2459       return ExprError();
2460     break;
2461   case Builtin::BIget_kernel_work_group_size:
2462   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2463     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2464       return ExprError();
2465     break;
2466   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2467   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2468     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2469       return ExprError();
2470     break;
2471   case Builtin::BI__builtin_os_log_format:
2472     Cleanup.setExprNeedsCleanups(true);
2473     LLVM_FALLTHROUGH;
2474   case Builtin::BI__builtin_os_log_format_buffer_size:
2475     if (SemaBuiltinOSLogFormat(TheCall))
2476       return ExprError();
2477     break;
2478   case Builtin::BI__builtin_frame_address:
2479   case Builtin::BI__builtin_return_address: {
2480     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2481       return ExprError();
2482 
2483     // -Wframe-address warning if non-zero passed to builtin
2484     // return/frame address.
2485     Expr::EvalResult Result;
2486     if (!TheCall->getArg(0)->isValueDependent() &&
2487         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2488         Result.Val.getInt() != 0)
2489       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2490           << ((BuiltinID == Builtin::BI__builtin_return_address)
2491                   ? "__builtin_return_address"
2492                   : "__builtin_frame_address")
2493           << TheCall->getSourceRange();
2494     break;
2495   }
2496 
2497   // __builtin_elementwise_abs restricts the element type to signed integers or
2498   // floating point types only.
2499   case Builtin::BI__builtin_elementwise_abs: {
2500     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2501       return ExprError();
2502 
2503     QualType ArgTy = TheCall->getArg(0)->getType();
2504     QualType EltTy = ArgTy;
2505 
2506     if (auto *VecTy = EltTy->getAs<VectorType>())
2507       EltTy = VecTy->getElementType();
2508     if (EltTy->isUnsignedIntegerType()) {
2509       Diag(TheCall->getArg(0)->getBeginLoc(),
2510            diag::err_builtin_invalid_arg_type)
2511           << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2512       return ExprError();
2513     }
2514     break;
2515   }
2516 
2517   // These builtins restrict the element type to floating point
2518   // types only.
2519   case Builtin::BI__builtin_elementwise_ceil:
2520   case Builtin::BI__builtin_elementwise_floor:
2521   case Builtin::BI__builtin_elementwise_roundeven:
2522   case Builtin::BI__builtin_elementwise_trunc: {
2523     if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2524       return ExprError();
2525 
2526     QualType ArgTy = TheCall->getArg(0)->getType();
2527     QualType EltTy = ArgTy;
2528 
2529     if (auto *VecTy = EltTy->getAs<VectorType>())
2530       EltTy = VecTy->getElementType();
2531     if (!EltTy->isFloatingType()) {
2532       Diag(TheCall->getArg(0)->getBeginLoc(),
2533            diag::err_builtin_invalid_arg_type)
2534           << 1 << /* float ty*/ 5 << ArgTy;
2535 
2536       return ExprError();
2537     }
2538     break;
2539   }
2540 
2541   // These builtins restrict the element type to integer
2542   // types only.
2543   case Builtin::BI__builtin_elementwise_add_sat:
2544   case Builtin::BI__builtin_elementwise_sub_sat: {
2545     if (SemaBuiltinElementwiseMath(TheCall))
2546       return ExprError();
2547 
2548     const Expr *Arg = TheCall->getArg(0);
2549     QualType ArgTy = Arg->getType();
2550     QualType EltTy = ArgTy;
2551 
2552     if (auto *VecTy = EltTy->getAs<VectorType>())
2553       EltTy = VecTy->getElementType();
2554 
2555     if (!EltTy->isIntegerType()) {
2556       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2557           << 1 << /* integer ty */ 6 << ArgTy;
2558       return ExprError();
2559     }
2560     break;
2561   }
2562 
2563   case Builtin::BI__builtin_elementwise_min:
2564   case Builtin::BI__builtin_elementwise_max:
2565     if (SemaBuiltinElementwiseMath(TheCall))
2566       return ExprError();
2567     break;
2568   case Builtin::BI__builtin_reduce_max:
2569   case Builtin::BI__builtin_reduce_min: {
2570     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2571       return ExprError();
2572 
2573     const Expr *Arg = TheCall->getArg(0);
2574     const auto *TyA = Arg->getType()->getAs<VectorType>();
2575     if (!TyA) {
2576       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2577           << 1 << /* vector ty*/ 4 << Arg->getType();
2578       return ExprError();
2579     }
2580 
2581     TheCall->setType(TyA->getElementType());
2582     break;
2583   }
2584 
2585   // These builtins support vectors of integers only.
2586   // TODO: ADD/MUL should support floating-point types.
2587   case Builtin::BI__builtin_reduce_add:
2588   case Builtin::BI__builtin_reduce_mul:
2589   case Builtin::BI__builtin_reduce_xor:
2590   case Builtin::BI__builtin_reduce_or:
2591   case Builtin::BI__builtin_reduce_and: {
2592     if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2593       return ExprError();
2594 
2595     const Expr *Arg = TheCall->getArg(0);
2596     const auto *TyA = Arg->getType()->getAs<VectorType>();
2597     if (!TyA || !TyA->getElementType()->isIntegerType()) {
2598       Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2599           << 1  << /* vector of integers */ 6 << Arg->getType();
2600       return ExprError();
2601     }
2602     TheCall->setType(TyA->getElementType());
2603     break;
2604   }
2605 
2606   case Builtin::BI__builtin_matrix_transpose:
2607     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2608 
2609   case Builtin::BI__builtin_matrix_column_major_load:
2610     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2611 
2612   case Builtin::BI__builtin_matrix_column_major_store:
2613     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2614 
2615   case Builtin::BI__builtin_get_device_side_mangled_name: {
2616     auto Check = [](CallExpr *TheCall) {
2617       if (TheCall->getNumArgs() != 1)
2618         return false;
2619       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2620       if (!DRE)
2621         return false;
2622       auto *D = DRE->getDecl();
2623       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2624         return false;
2625       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2626              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2627     };
2628     if (!Check(TheCall)) {
2629       Diag(TheCall->getBeginLoc(),
2630            diag::err_hip_invalid_args_builtin_mangled_name);
2631       return ExprError();
2632     }
2633   }
2634   }
2635 
2636   // Since the target specific builtins for each arch overlap, only check those
2637   // of the arch we are compiling for.
2638   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2639     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2640       assert(Context.getAuxTargetInfo() &&
2641              "Aux Target Builtin, but not an aux target?");
2642 
2643       if (CheckTSBuiltinFunctionCall(
2644               *Context.getAuxTargetInfo(),
2645               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2646         return ExprError();
2647     } else {
2648       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2649                                      TheCall))
2650         return ExprError();
2651     }
2652   }
2653 
2654   return TheCallResult;
2655 }
2656 
2657 // Get the valid immediate range for the specified NEON type code.
2658 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2659   NeonTypeFlags Type(t);
2660   int IsQuad = ForceQuad ? true : Type.isQuad();
2661   switch (Type.getEltType()) {
2662   case NeonTypeFlags::Int8:
2663   case NeonTypeFlags::Poly8:
2664     return shift ? 7 : (8 << IsQuad) - 1;
2665   case NeonTypeFlags::Int16:
2666   case NeonTypeFlags::Poly16:
2667     return shift ? 15 : (4 << IsQuad) - 1;
2668   case NeonTypeFlags::Int32:
2669     return shift ? 31 : (2 << IsQuad) - 1;
2670   case NeonTypeFlags::Int64:
2671   case NeonTypeFlags::Poly64:
2672     return shift ? 63 : (1 << IsQuad) - 1;
2673   case NeonTypeFlags::Poly128:
2674     return shift ? 127 : (1 << IsQuad) - 1;
2675   case NeonTypeFlags::Float16:
2676     assert(!shift && "cannot shift float types!");
2677     return (4 << IsQuad) - 1;
2678   case NeonTypeFlags::Float32:
2679     assert(!shift && "cannot shift float types!");
2680     return (2 << IsQuad) - 1;
2681   case NeonTypeFlags::Float64:
2682     assert(!shift && "cannot shift float types!");
2683     return (1 << IsQuad) - 1;
2684   case NeonTypeFlags::BFloat16:
2685     assert(!shift && "cannot shift float types!");
2686     return (4 << IsQuad) - 1;
2687   }
2688   llvm_unreachable("Invalid NeonTypeFlag!");
2689 }
2690 
2691 /// getNeonEltType - Return the QualType corresponding to the elements of
2692 /// the vector type specified by the NeonTypeFlags.  This is used to check
2693 /// the pointer arguments for Neon load/store intrinsics.
2694 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2695                                bool IsPolyUnsigned, bool IsInt64Long) {
2696   switch (Flags.getEltType()) {
2697   case NeonTypeFlags::Int8:
2698     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2699   case NeonTypeFlags::Int16:
2700     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2701   case NeonTypeFlags::Int32:
2702     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2703   case NeonTypeFlags::Int64:
2704     if (IsInt64Long)
2705       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2706     else
2707       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2708                                 : Context.LongLongTy;
2709   case NeonTypeFlags::Poly8:
2710     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2711   case NeonTypeFlags::Poly16:
2712     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2713   case NeonTypeFlags::Poly64:
2714     if (IsInt64Long)
2715       return Context.UnsignedLongTy;
2716     else
2717       return Context.UnsignedLongLongTy;
2718   case NeonTypeFlags::Poly128:
2719     break;
2720   case NeonTypeFlags::Float16:
2721     return Context.HalfTy;
2722   case NeonTypeFlags::Float32:
2723     return Context.FloatTy;
2724   case NeonTypeFlags::Float64:
2725     return Context.DoubleTy;
2726   case NeonTypeFlags::BFloat16:
2727     return Context.BFloat16Ty;
2728   }
2729   llvm_unreachable("Invalid NeonTypeFlag!");
2730 }
2731 
2732 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2733   // Range check SVE intrinsics that take immediate values.
2734   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2735 
2736   switch (BuiltinID) {
2737   default:
2738     return false;
2739 #define GET_SVE_IMMEDIATE_CHECK
2740 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2741 #undef GET_SVE_IMMEDIATE_CHECK
2742   }
2743 
2744   // Perform all the immediate checks for this builtin call.
2745   bool HasError = false;
2746   for (auto &I : ImmChecks) {
2747     int ArgNum, CheckTy, ElementSizeInBits;
2748     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2749 
2750     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2751 
2752     // Function that checks whether the operand (ArgNum) is an immediate
2753     // that is one of the predefined values.
2754     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2755                                    int ErrDiag) -> bool {
2756       // We can't check the value of a dependent argument.
2757       Expr *Arg = TheCall->getArg(ArgNum);
2758       if (Arg->isTypeDependent() || Arg->isValueDependent())
2759         return false;
2760 
2761       // Check constant-ness first.
2762       llvm::APSInt Imm;
2763       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2764         return true;
2765 
2766       if (!CheckImm(Imm.getSExtValue()))
2767         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2768       return false;
2769     };
2770 
2771     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2772     case SVETypeFlags::ImmCheck0_31:
2773       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2774         HasError = true;
2775       break;
2776     case SVETypeFlags::ImmCheck0_13:
2777       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2778         HasError = true;
2779       break;
2780     case SVETypeFlags::ImmCheck1_16:
2781       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2782         HasError = true;
2783       break;
2784     case SVETypeFlags::ImmCheck0_7:
2785       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2786         HasError = true;
2787       break;
2788     case SVETypeFlags::ImmCheckExtract:
2789       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2790                                       (2048 / ElementSizeInBits) - 1))
2791         HasError = true;
2792       break;
2793     case SVETypeFlags::ImmCheckShiftRight:
2794       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2795         HasError = true;
2796       break;
2797     case SVETypeFlags::ImmCheckShiftRightNarrow:
2798       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2799                                       ElementSizeInBits / 2))
2800         HasError = true;
2801       break;
2802     case SVETypeFlags::ImmCheckShiftLeft:
2803       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2804                                       ElementSizeInBits - 1))
2805         HasError = true;
2806       break;
2807     case SVETypeFlags::ImmCheckLaneIndex:
2808       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2809                                       (128 / (1 * ElementSizeInBits)) - 1))
2810         HasError = true;
2811       break;
2812     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2813       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2814                                       (128 / (2 * ElementSizeInBits)) - 1))
2815         HasError = true;
2816       break;
2817     case SVETypeFlags::ImmCheckLaneIndexDot:
2818       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2819                                       (128 / (4 * ElementSizeInBits)) - 1))
2820         HasError = true;
2821       break;
2822     case SVETypeFlags::ImmCheckComplexRot90_270:
2823       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2824                               diag::err_rotation_argument_to_cadd))
2825         HasError = true;
2826       break;
2827     case SVETypeFlags::ImmCheckComplexRotAll90:
2828       if (CheckImmediateInSet(
2829               [](int64_t V) {
2830                 return V == 0 || V == 90 || V == 180 || V == 270;
2831               },
2832               diag::err_rotation_argument_to_cmla))
2833         HasError = true;
2834       break;
2835     case SVETypeFlags::ImmCheck0_1:
2836       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2837         HasError = true;
2838       break;
2839     case SVETypeFlags::ImmCheck0_2:
2840       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2841         HasError = true;
2842       break;
2843     case SVETypeFlags::ImmCheck0_3:
2844       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2845         HasError = true;
2846       break;
2847     }
2848   }
2849 
2850   return HasError;
2851 }
2852 
2853 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2854                                         unsigned BuiltinID, CallExpr *TheCall) {
2855   llvm::APSInt Result;
2856   uint64_t mask = 0;
2857   unsigned TV = 0;
2858   int PtrArgNum = -1;
2859   bool HasConstPtr = false;
2860   switch (BuiltinID) {
2861 #define GET_NEON_OVERLOAD_CHECK
2862 #include "clang/Basic/arm_neon.inc"
2863 #include "clang/Basic/arm_fp16.inc"
2864 #undef GET_NEON_OVERLOAD_CHECK
2865   }
2866 
2867   // For NEON intrinsics which are overloaded on vector element type, validate
2868   // the immediate which specifies which variant to emit.
2869   unsigned ImmArg = TheCall->getNumArgs()-1;
2870   if (mask) {
2871     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2872       return true;
2873 
2874     TV = Result.getLimitedValue(64);
2875     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2876       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2877              << TheCall->getArg(ImmArg)->getSourceRange();
2878   }
2879 
2880   if (PtrArgNum >= 0) {
2881     // Check that pointer arguments have the specified type.
2882     Expr *Arg = TheCall->getArg(PtrArgNum);
2883     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2884       Arg = ICE->getSubExpr();
2885     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2886     QualType RHSTy = RHS.get()->getType();
2887 
2888     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2889     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2890                           Arch == llvm::Triple::aarch64_32 ||
2891                           Arch == llvm::Triple::aarch64_be;
2892     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2893     QualType EltTy =
2894         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2895     if (HasConstPtr)
2896       EltTy = EltTy.withConst();
2897     QualType LHSTy = Context.getPointerType(EltTy);
2898     AssignConvertType ConvTy;
2899     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2900     if (RHS.isInvalid())
2901       return true;
2902     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2903                                  RHS.get(), AA_Assigning))
2904       return true;
2905   }
2906 
2907   // For NEON intrinsics which take an immediate value as part of the
2908   // instruction, range check them here.
2909   unsigned i = 0, l = 0, u = 0;
2910   switch (BuiltinID) {
2911   default:
2912     return false;
2913   #define GET_NEON_IMMEDIATE_CHECK
2914   #include "clang/Basic/arm_neon.inc"
2915   #include "clang/Basic/arm_fp16.inc"
2916   #undef GET_NEON_IMMEDIATE_CHECK
2917   }
2918 
2919   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2920 }
2921 
2922 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2923   switch (BuiltinID) {
2924   default:
2925     return false;
2926   #include "clang/Basic/arm_mve_builtin_sema.inc"
2927   }
2928 }
2929 
2930 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2931                                        CallExpr *TheCall) {
2932   bool Err = false;
2933   switch (BuiltinID) {
2934   default:
2935     return false;
2936 #include "clang/Basic/arm_cde_builtin_sema.inc"
2937   }
2938 
2939   if (Err)
2940     return true;
2941 
2942   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2943 }
2944 
2945 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2946                                         const Expr *CoprocArg, bool WantCDE) {
2947   if (isConstantEvaluated())
2948     return false;
2949 
2950   // We can't check the value of a dependent argument.
2951   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2952     return false;
2953 
2954   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2955   int64_t CoprocNo = CoprocNoAP.getExtValue();
2956   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2957 
2958   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2959   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2960 
2961   if (IsCDECoproc != WantCDE)
2962     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2963            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2964 
2965   return false;
2966 }
2967 
2968 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2969                                         unsigned MaxWidth) {
2970   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2971           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2972           BuiltinID == ARM::BI__builtin_arm_strex ||
2973           BuiltinID == ARM::BI__builtin_arm_stlex ||
2974           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2975           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2976           BuiltinID == AArch64::BI__builtin_arm_strex ||
2977           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2978          "unexpected ARM builtin");
2979   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2980                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2981                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2982                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2983 
2984   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2985 
2986   // Ensure that we have the proper number of arguments.
2987   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2988     return true;
2989 
2990   // Inspect the pointer argument of the atomic builtin.  This should always be
2991   // a pointer type, whose element is an integral scalar or pointer type.
2992   // Because it is a pointer type, we don't have to worry about any implicit
2993   // casts here.
2994   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2995   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2996   if (PointerArgRes.isInvalid())
2997     return true;
2998   PointerArg = PointerArgRes.get();
2999 
3000   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3001   if (!pointerType) {
3002     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
3003         << PointerArg->getType() << PointerArg->getSourceRange();
3004     return true;
3005   }
3006 
3007   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
3008   // task is to insert the appropriate casts into the AST. First work out just
3009   // what the appropriate type is.
3010   QualType ValType = pointerType->getPointeeType();
3011   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
3012   if (IsLdrex)
3013     AddrType.addConst();
3014 
3015   // Issue a warning if the cast is dodgy.
3016   CastKind CastNeeded = CK_NoOp;
3017   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
3018     CastNeeded = CK_BitCast;
3019     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
3020         << PointerArg->getType() << Context.getPointerType(AddrType)
3021         << AA_Passing << PointerArg->getSourceRange();
3022   }
3023 
3024   // Finally, do the cast and replace the argument with the corrected version.
3025   AddrType = Context.getPointerType(AddrType);
3026   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
3027   if (PointerArgRes.isInvalid())
3028     return true;
3029   PointerArg = PointerArgRes.get();
3030 
3031   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
3032 
3033   // In general, we allow ints, floats and pointers to be loaded and stored.
3034   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3035       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
3036     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
3037         << PointerArg->getType() << PointerArg->getSourceRange();
3038     return true;
3039   }
3040 
3041   // But ARM doesn't have instructions to deal with 128-bit versions.
3042   if (Context.getTypeSize(ValType) > MaxWidth) {
3043     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
3044     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
3045         << PointerArg->getType() << PointerArg->getSourceRange();
3046     return true;
3047   }
3048 
3049   switch (ValType.getObjCLifetime()) {
3050   case Qualifiers::OCL_None:
3051   case Qualifiers::OCL_ExplicitNone:
3052     // okay
3053     break;
3054 
3055   case Qualifiers::OCL_Weak:
3056   case Qualifiers::OCL_Strong:
3057   case Qualifiers::OCL_Autoreleasing:
3058     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
3059         << ValType << PointerArg->getSourceRange();
3060     return true;
3061   }
3062 
3063   if (IsLdrex) {
3064     TheCall->setType(ValType);
3065     return false;
3066   }
3067 
3068   // Initialize the argument to be stored.
3069   ExprResult ValArg = TheCall->getArg(0);
3070   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3071       Context, ValType, /*consume*/ false);
3072   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3073   if (ValArg.isInvalid())
3074     return true;
3075   TheCall->setArg(0, ValArg.get());
3076 
3077   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
3078   // but the custom checker bypasses all default analysis.
3079   TheCall->setType(Context.IntTy);
3080   return false;
3081 }
3082 
3083 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3084                                        CallExpr *TheCall) {
3085   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
3086       BuiltinID == ARM::BI__builtin_arm_ldaex ||
3087       BuiltinID == ARM::BI__builtin_arm_strex ||
3088       BuiltinID == ARM::BI__builtin_arm_stlex) {
3089     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
3090   }
3091 
3092   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
3093     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3094       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
3095   }
3096 
3097   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3098       BuiltinID == ARM::BI__builtin_arm_wsr64)
3099     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
3100 
3101   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
3102       BuiltinID == ARM::BI__builtin_arm_rsrp ||
3103       BuiltinID == ARM::BI__builtin_arm_wsr ||
3104       BuiltinID == ARM::BI__builtin_arm_wsrp)
3105     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
3106 
3107   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
3108     return true;
3109   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
3110     return true;
3111   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
3112     return true;
3113 
3114   // For intrinsics which take an immediate value as part of the instruction,
3115   // range check them here.
3116   // FIXME: VFP Intrinsics should error if VFP not present.
3117   switch (BuiltinID) {
3118   default: return false;
3119   case ARM::BI__builtin_arm_ssat:
3120     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
3121   case ARM::BI__builtin_arm_usat:
3122     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
3123   case ARM::BI__builtin_arm_ssat16:
3124     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3125   case ARM::BI__builtin_arm_usat16:
3126     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3127   case ARM::BI__builtin_arm_vcvtr_f:
3128   case ARM::BI__builtin_arm_vcvtr_d:
3129     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3130   case ARM::BI__builtin_arm_dmb:
3131   case ARM::BI__builtin_arm_dsb:
3132   case ARM::BI__builtin_arm_isb:
3133   case ARM::BI__builtin_arm_dbg:
3134     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
3135   case ARM::BI__builtin_arm_cdp:
3136   case ARM::BI__builtin_arm_cdp2:
3137   case ARM::BI__builtin_arm_mcr:
3138   case ARM::BI__builtin_arm_mcr2:
3139   case ARM::BI__builtin_arm_mrc:
3140   case ARM::BI__builtin_arm_mrc2:
3141   case ARM::BI__builtin_arm_mcrr:
3142   case ARM::BI__builtin_arm_mcrr2:
3143   case ARM::BI__builtin_arm_mrrc:
3144   case ARM::BI__builtin_arm_mrrc2:
3145   case ARM::BI__builtin_arm_ldc:
3146   case ARM::BI__builtin_arm_ldcl:
3147   case ARM::BI__builtin_arm_ldc2:
3148   case ARM::BI__builtin_arm_ldc2l:
3149   case ARM::BI__builtin_arm_stc:
3150   case ARM::BI__builtin_arm_stcl:
3151   case ARM::BI__builtin_arm_stc2:
3152   case ARM::BI__builtin_arm_stc2l:
3153     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
3154            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
3155                                         /*WantCDE*/ false);
3156   }
3157 }
3158 
3159 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
3160                                            unsigned BuiltinID,
3161                                            CallExpr *TheCall) {
3162   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
3163       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
3164       BuiltinID == AArch64::BI__builtin_arm_strex ||
3165       BuiltinID == AArch64::BI__builtin_arm_stlex) {
3166     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
3167   }
3168 
3169   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
3170     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3171       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
3172       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
3173       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
3174   }
3175 
3176   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3177       BuiltinID == AArch64::BI__builtin_arm_wsr64)
3178     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
3179 
3180   // Memory Tagging Extensions (MTE) Intrinsics
3181   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
3182       BuiltinID == AArch64::BI__builtin_arm_addg ||
3183       BuiltinID == AArch64::BI__builtin_arm_gmi ||
3184       BuiltinID == AArch64::BI__builtin_arm_ldg ||
3185       BuiltinID == AArch64::BI__builtin_arm_stg ||
3186       BuiltinID == AArch64::BI__builtin_arm_subp) {
3187     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
3188   }
3189 
3190   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
3191       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3192       BuiltinID == AArch64::BI__builtin_arm_wsr ||
3193       BuiltinID == AArch64::BI__builtin_arm_wsrp)
3194     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
3195 
3196   // Only check the valid encoding range. Any constant in this range would be
3197   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
3198   // an exception for incorrect registers. This matches MSVC behavior.
3199   if (BuiltinID == AArch64::BI_ReadStatusReg ||
3200       BuiltinID == AArch64::BI_WriteStatusReg)
3201     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
3202 
3203   if (BuiltinID == AArch64::BI__getReg)
3204     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3205 
3206   if (BuiltinID == AArch64::BI__break)
3207     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xffff);
3208 
3209   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
3210     return true;
3211 
3212   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
3213     return true;
3214 
3215   // For intrinsics which take an immediate value as part of the instruction,
3216   // range check them here.
3217   unsigned i = 0, l = 0, u = 0;
3218   switch (BuiltinID) {
3219   default: return false;
3220   case AArch64::BI__builtin_arm_dmb:
3221   case AArch64::BI__builtin_arm_dsb:
3222   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
3223   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
3224   }
3225 
3226   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
3227 }
3228 
3229 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
3230   if (Arg->getType()->getAsPlaceholderType())
3231     return false;
3232 
3233   // The first argument needs to be a record field access.
3234   // If it is an array element access, we delay decision
3235   // to BPF backend to check whether the access is a
3236   // field access or not.
3237   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
3238           isa<MemberExpr>(Arg->IgnoreParens()) ||
3239           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
3240 }
3241 
3242 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
3243                             QualType VectorTy, QualType EltTy) {
3244   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
3245   if (!Context.hasSameType(VectorEltTy, EltTy)) {
3246     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
3247         << Call->getSourceRange() << VectorEltTy << EltTy;
3248     return false;
3249   }
3250   return true;
3251 }
3252 
3253 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
3254   QualType ArgType = Arg->getType();
3255   if (ArgType->getAsPlaceholderType())
3256     return false;
3257 
3258   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
3259   // format:
3260   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
3261   //   2. <type> var;
3262   //      __builtin_preserve_type_info(var, flag);
3263   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
3264       !isa<UnaryOperator>(Arg->IgnoreParens()))
3265     return false;
3266 
3267   // Typedef type.
3268   if (ArgType->getAs<TypedefType>())
3269     return true;
3270 
3271   // Record type or Enum type.
3272   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3273   if (const auto *RT = Ty->getAs<RecordType>()) {
3274     if (!RT->getDecl()->getDeclName().isEmpty())
3275       return true;
3276   } else if (const auto *ET = Ty->getAs<EnumType>()) {
3277     if (!ET->getDecl()->getDeclName().isEmpty())
3278       return true;
3279   }
3280 
3281   return false;
3282 }
3283 
3284 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
3285   QualType ArgType = Arg->getType();
3286   if (ArgType->getAsPlaceholderType())
3287     return false;
3288 
3289   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
3290   // format:
3291   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
3292   //                                 flag);
3293   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
3294   if (!UO)
3295     return false;
3296 
3297   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
3298   if (!CE)
3299     return false;
3300   if (CE->getCastKind() != CK_IntegralToPointer &&
3301       CE->getCastKind() != CK_NullToPointer)
3302     return false;
3303 
3304   // The integer must be from an EnumConstantDecl.
3305   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
3306   if (!DR)
3307     return false;
3308 
3309   const EnumConstantDecl *Enumerator =
3310       dyn_cast<EnumConstantDecl>(DR->getDecl());
3311   if (!Enumerator)
3312     return false;
3313 
3314   // The type must be EnumType.
3315   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3316   const auto *ET = Ty->getAs<EnumType>();
3317   if (!ET)
3318     return false;
3319 
3320   // The enum value must be supported.
3321   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
3322 }
3323 
3324 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
3325                                        CallExpr *TheCall) {
3326   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
3327           BuiltinID == BPF::BI__builtin_btf_type_id ||
3328           BuiltinID == BPF::BI__builtin_preserve_type_info ||
3329           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
3330          "unexpected BPF builtin");
3331 
3332   if (checkArgCount(*this, TheCall, 2))
3333     return true;
3334 
3335   // The second argument needs to be a constant int
3336   Expr *Arg = TheCall->getArg(1);
3337   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
3338   diag::kind kind;
3339   if (!Value) {
3340     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
3341       kind = diag::err_preserve_field_info_not_const;
3342     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
3343       kind = diag::err_btf_type_id_not_const;
3344     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
3345       kind = diag::err_preserve_type_info_not_const;
3346     else
3347       kind = diag::err_preserve_enum_value_not_const;
3348     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
3349     return true;
3350   }
3351 
3352   // The first argument
3353   Arg = TheCall->getArg(0);
3354   bool InvalidArg = false;
3355   bool ReturnUnsignedInt = true;
3356   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
3357     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
3358       InvalidArg = true;
3359       kind = diag::err_preserve_field_info_not_field;
3360     }
3361   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3362     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
3363       InvalidArg = true;
3364       kind = diag::err_preserve_type_info_invalid;
3365     }
3366   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3367     if (!isValidBPFPreserveEnumValueArg(Arg)) {
3368       InvalidArg = true;
3369       kind = diag::err_preserve_enum_value_invalid;
3370     }
3371     ReturnUnsignedInt = false;
3372   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3373     ReturnUnsignedInt = false;
3374   }
3375 
3376   if (InvalidArg) {
3377     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3378     return true;
3379   }
3380 
3381   if (ReturnUnsignedInt)
3382     TheCall->setType(Context.UnsignedIntTy);
3383   else
3384     TheCall->setType(Context.UnsignedLongTy);
3385   return false;
3386 }
3387 
3388 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3389   struct ArgInfo {
3390     uint8_t OpNum;
3391     bool IsSigned;
3392     uint8_t BitWidth;
3393     uint8_t Align;
3394   };
3395   struct BuiltinInfo {
3396     unsigned BuiltinID;
3397     ArgInfo Infos[2];
3398   };
3399 
3400   static BuiltinInfo Infos[] = {
3401     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
3402     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
3403     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
3404     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
3405     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
3406     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
3407     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
3408     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
3409     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
3410     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
3411     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
3412 
3413     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
3414     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
3415     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
3416     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
3417     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
3418     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
3419     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
3420     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
3421     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
3422     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
3423     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
3424 
3425     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
3426     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
3427     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
3428     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
3429     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
3430     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
3431     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
3432     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
3433     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
3434     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
3435     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
3436     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
3437     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
3438     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
3439     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
3440     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
3441     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
3442     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
3443     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
3444     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
3445     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
3446     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
3447     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
3448     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
3449     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
3450     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
3451     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
3452     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
3453     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
3454     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
3455     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
3456     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
3457     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
3458     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
3459     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
3460     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
3461     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
3462     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
3463     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
3464     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
3465     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
3466     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
3467     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
3468     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
3469     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
3470     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
3471     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
3472     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
3473     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
3474     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
3475     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
3476     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3477                                                       {{ 1, false, 6,  0 }} },
3478     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
3479     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
3480     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
3481     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
3482     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
3483     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
3484     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3485                                                       {{ 1, false, 5,  0 }} },
3486     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
3487     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
3488     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
3489     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
3490     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
3491     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
3492                                                        { 2, false, 5,  0 }} },
3493     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3494                                                        { 2, false, 6,  0 }} },
3495     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3496                                                        { 3, false, 5,  0 }} },
3497     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3498                                                        { 3, false, 6,  0 }} },
3499     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3500     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3501     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3502     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3503     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3504     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3505     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3506     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3507     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3508     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3509     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3510     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3511     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3512     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3513     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3514     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3515                                                       {{ 2, false, 4,  0 },
3516                                                        { 3, false, 5,  0 }} },
3517     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3518                                                       {{ 2, false, 4,  0 },
3519                                                        { 3, false, 5,  0 }} },
3520     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3521                                                       {{ 2, false, 4,  0 },
3522                                                        { 3, false, 5,  0 }} },
3523     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3524                                                       {{ 2, false, 4,  0 },
3525                                                        { 3, false, 5,  0 }} },
3526     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3527     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3528     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3529     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3530     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3531     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3532     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3533     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3534     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3535     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3536     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3537                                                        { 2, false, 5,  0 }} },
3538     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3539                                                        { 2, false, 6,  0 }} },
3540     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3541     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3542     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3543     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3544     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3545     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3546     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3547     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3548     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3549                                                       {{ 1, false, 4,  0 }} },
3550     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3551     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3552                                                       {{ 1, false, 4,  0 }} },
3553     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3554     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3555     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3556     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3557     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3558     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3559     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3560     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3561     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3562     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3563     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3564     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3565     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3566     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3567     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3568     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3569     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3570     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3571     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3572     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3573                                                       {{ 3, false, 1,  0 }} },
3574     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3575     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3576     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3577     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3578                                                       {{ 3, false, 1,  0 }} },
3579     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3580     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3581     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3582     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3583                                                       {{ 3, false, 1,  0 }} },
3584   };
3585 
3586   // Use a dynamically initialized static to sort the table exactly once on
3587   // first run.
3588   static const bool SortOnce =
3589       (llvm::sort(Infos,
3590                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3591                    return LHS.BuiltinID < RHS.BuiltinID;
3592                  }),
3593        true);
3594   (void)SortOnce;
3595 
3596   const BuiltinInfo *F = llvm::partition_point(
3597       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3598   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3599     return false;
3600 
3601   bool Error = false;
3602 
3603   for (const ArgInfo &A : F->Infos) {
3604     // Ignore empty ArgInfo elements.
3605     if (A.BitWidth == 0)
3606       continue;
3607 
3608     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3609     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3610     if (!A.Align) {
3611       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3612     } else {
3613       unsigned M = 1 << A.Align;
3614       Min *= M;
3615       Max *= M;
3616       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3617       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3618     }
3619   }
3620   return Error;
3621 }
3622 
3623 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3624                                            CallExpr *TheCall) {
3625   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3626 }
3627 
3628 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3629                                         unsigned BuiltinID, CallExpr *TheCall) {
3630   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3631          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3632 }
3633 
3634 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3635                                CallExpr *TheCall) {
3636 
3637   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3638       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3639     if (!TI.hasFeature("dsp"))
3640       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3641   }
3642 
3643   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3644       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3645     if (!TI.hasFeature("dspr2"))
3646       return Diag(TheCall->getBeginLoc(),
3647                   diag::err_mips_builtin_requires_dspr2);
3648   }
3649 
3650   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3651       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3652     if (!TI.hasFeature("msa"))
3653       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3654   }
3655 
3656   return false;
3657 }
3658 
3659 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3660 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3661 // ordering for DSP is unspecified. MSA is ordered by the data format used
3662 // by the underlying instruction i.e., df/m, df/n and then by size.
3663 //
3664 // FIXME: The size tests here should instead be tablegen'd along with the
3665 //        definitions from include/clang/Basic/BuiltinsMips.def.
3666 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3667 //        be too.
3668 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3669   unsigned i = 0, l = 0, u = 0, m = 0;
3670   switch (BuiltinID) {
3671   default: return false;
3672   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3673   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3674   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3675   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3676   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3677   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3678   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3679   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3680   // df/m field.
3681   // These intrinsics take an unsigned 3 bit immediate.
3682   case Mips::BI__builtin_msa_bclri_b:
3683   case Mips::BI__builtin_msa_bnegi_b:
3684   case Mips::BI__builtin_msa_bseti_b:
3685   case Mips::BI__builtin_msa_sat_s_b:
3686   case Mips::BI__builtin_msa_sat_u_b:
3687   case Mips::BI__builtin_msa_slli_b:
3688   case Mips::BI__builtin_msa_srai_b:
3689   case Mips::BI__builtin_msa_srari_b:
3690   case Mips::BI__builtin_msa_srli_b:
3691   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3692   case Mips::BI__builtin_msa_binsli_b:
3693   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3694   // These intrinsics take an unsigned 4 bit immediate.
3695   case Mips::BI__builtin_msa_bclri_h:
3696   case Mips::BI__builtin_msa_bnegi_h:
3697   case Mips::BI__builtin_msa_bseti_h:
3698   case Mips::BI__builtin_msa_sat_s_h:
3699   case Mips::BI__builtin_msa_sat_u_h:
3700   case Mips::BI__builtin_msa_slli_h:
3701   case Mips::BI__builtin_msa_srai_h:
3702   case Mips::BI__builtin_msa_srari_h:
3703   case Mips::BI__builtin_msa_srli_h:
3704   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3705   case Mips::BI__builtin_msa_binsli_h:
3706   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3707   // These intrinsics take an unsigned 5 bit immediate.
3708   // The first block of intrinsics actually have an unsigned 5 bit field,
3709   // not a df/n field.
3710   case Mips::BI__builtin_msa_cfcmsa:
3711   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3712   case Mips::BI__builtin_msa_clei_u_b:
3713   case Mips::BI__builtin_msa_clei_u_h:
3714   case Mips::BI__builtin_msa_clei_u_w:
3715   case Mips::BI__builtin_msa_clei_u_d:
3716   case Mips::BI__builtin_msa_clti_u_b:
3717   case Mips::BI__builtin_msa_clti_u_h:
3718   case Mips::BI__builtin_msa_clti_u_w:
3719   case Mips::BI__builtin_msa_clti_u_d:
3720   case Mips::BI__builtin_msa_maxi_u_b:
3721   case Mips::BI__builtin_msa_maxi_u_h:
3722   case Mips::BI__builtin_msa_maxi_u_w:
3723   case Mips::BI__builtin_msa_maxi_u_d:
3724   case Mips::BI__builtin_msa_mini_u_b:
3725   case Mips::BI__builtin_msa_mini_u_h:
3726   case Mips::BI__builtin_msa_mini_u_w:
3727   case Mips::BI__builtin_msa_mini_u_d:
3728   case Mips::BI__builtin_msa_addvi_b:
3729   case Mips::BI__builtin_msa_addvi_h:
3730   case Mips::BI__builtin_msa_addvi_w:
3731   case Mips::BI__builtin_msa_addvi_d:
3732   case Mips::BI__builtin_msa_bclri_w:
3733   case Mips::BI__builtin_msa_bnegi_w:
3734   case Mips::BI__builtin_msa_bseti_w:
3735   case Mips::BI__builtin_msa_sat_s_w:
3736   case Mips::BI__builtin_msa_sat_u_w:
3737   case Mips::BI__builtin_msa_slli_w:
3738   case Mips::BI__builtin_msa_srai_w:
3739   case Mips::BI__builtin_msa_srari_w:
3740   case Mips::BI__builtin_msa_srli_w:
3741   case Mips::BI__builtin_msa_srlri_w:
3742   case Mips::BI__builtin_msa_subvi_b:
3743   case Mips::BI__builtin_msa_subvi_h:
3744   case Mips::BI__builtin_msa_subvi_w:
3745   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3746   case Mips::BI__builtin_msa_binsli_w:
3747   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3748   // These intrinsics take an unsigned 6 bit immediate.
3749   case Mips::BI__builtin_msa_bclri_d:
3750   case Mips::BI__builtin_msa_bnegi_d:
3751   case Mips::BI__builtin_msa_bseti_d:
3752   case Mips::BI__builtin_msa_sat_s_d:
3753   case Mips::BI__builtin_msa_sat_u_d:
3754   case Mips::BI__builtin_msa_slli_d:
3755   case Mips::BI__builtin_msa_srai_d:
3756   case Mips::BI__builtin_msa_srari_d:
3757   case Mips::BI__builtin_msa_srli_d:
3758   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3759   case Mips::BI__builtin_msa_binsli_d:
3760   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3761   // These intrinsics take a signed 5 bit immediate.
3762   case Mips::BI__builtin_msa_ceqi_b:
3763   case Mips::BI__builtin_msa_ceqi_h:
3764   case Mips::BI__builtin_msa_ceqi_w:
3765   case Mips::BI__builtin_msa_ceqi_d:
3766   case Mips::BI__builtin_msa_clti_s_b:
3767   case Mips::BI__builtin_msa_clti_s_h:
3768   case Mips::BI__builtin_msa_clti_s_w:
3769   case Mips::BI__builtin_msa_clti_s_d:
3770   case Mips::BI__builtin_msa_clei_s_b:
3771   case Mips::BI__builtin_msa_clei_s_h:
3772   case Mips::BI__builtin_msa_clei_s_w:
3773   case Mips::BI__builtin_msa_clei_s_d:
3774   case Mips::BI__builtin_msa_maxi_s_b:
3775   case Mips::BI__builtin_msa_maxi_s_h:
3776   case Mips::BI__builtin_msa_maxi_s_w:
3777   case Mips::BI__builtin_msa_maxi_s_d:
3778   case Mips::BI__builtin_msa_mini_s_b:
3779   case Mips::BI__builtin_msa_mini_s_h:
3780   case Mips::BI__builtin_msa_mini_s_w:
3781   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3782   // These intrinsics take an unsigned 8 bit immediate.
3783   case Mips::BI__builtin_msa_andi_b:
3784   case Mips::BI__builtin_msa_nori_b:
3785   case Mips::BI__builtin_msa_ori_b:
3786   case Mips::BI__builtin_msa_shf_b:
3787   case Mips::BI__builtin_msa_shf_h:
3788   case Mips::BI__builtin_msa_shf_w:
3789   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3790   case Mips::BI__builtin_msa_bseli_b:
3791   case Mips::BI__builtin_msa_bmnzi_b:
3792   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3793   // df/n format
3794   // These intrinsics take an unsigned 4 bit immediate.
3795   case Mips::BI__builtin_msa_copy_s_b:
3796   case Mips::BI__builtin_msa_copy_u_b:
3797   case Mips::BI__builtin_msa_insve_b:
3798   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3799   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3800   // These intrinsics take an unsigned 3 bit immediate.
3801   case Mips::BI__builtin_msa_copy_s_h:
3802   case Mips::BI__builtin_msa_copy_u_h:
3803   case Mips::BI__builtin_msa_insve_h:
3804   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3805   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3806   // These intrinsics take an unsigned 2 bit immediate.
3807   case Mips::BI__builtin_msa_copy_s_w:
3808   case Mips::BI__builtin_msa_copy_u_w:
3809   case Mips::BI__builtin_msa_insve_w:
3810   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3811   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3812   // These intrinsics take an unsigned 1 bit immediate.
3813   case Mips::BI__builtin_msa_copy_s_d:
3814   case Mips::BI__builtin_msa_copy_u_d:
3815   case Mips::BI__builtin_msa_insve_d:
3816   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3817   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3818   // Memory offsets and immediate loads.
3819   // These intrinsics take a signed 10 bit immediate.
3820   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3821   case Mips::BI__builtin_msa_ldi_h:
3822   case Mips::BI__builtin_msa_ldi_w:
3823   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3824   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3825   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3826   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3827   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3828   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3829   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3830   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3831   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3832   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3833   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3834   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3835   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3836   }
3837 
3838   if (!m)
3839     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3840 
3841   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3842          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3843 }
3844 
3845 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3846 /// advancing the pointer over the consumed characters. The decoded type is
3847 /// returned. If the decoded type represents a constant integer with a
3848 /// constraint on its value then Mask is set to that value. The type descriptors
3849 /// used in Str are specific to PPC MMA builtins and are documented in the file
3850 /// defining the PPC builtins.
3851 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3852                                         unsigned &Mask) {
3853   bool RequireICE = false;
3854   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3855   switch (*Str++) {
3856   case 'V':
3857     return Context.getVectorType(Context.UnsignedCharTy, 16,
3858                                  VectorType::VectorKind::AltiVecVector);
3859   case 'i': {
3860     char *End;
3861     unsigned size = strtoul(Str, &End, 10);
3862     assert(End != Str && "Missing constant parameter constraint");
3863     Str = End;
3864     Mask = size;
3865     return Context.IntTy;
3866   }
3867   case 'W': {
3868     char *End;
3869     unsigned size = strtoul(Str, &End, 10);
3870     assert(End != Str && "Missing PowerPC MMA type size");
3871     Str = End;
3872     QualType Type;
3873     switch (size) {
3874   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3875     case size: Type = Context.Id##Ty; break;
3876   #include "clang/Basic/PPCTypes.def"
3877     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3878     }
3879     bool CheckVectorArgs = false;
3880     while (!CheckVectorArgs) {
3881       switch (*Str++) {
3882       case '*':
3883         Type = Context.getPointerType(Type);
3884         break;
3885       case 'C':
3886         Type = Type.withConst();
3887         break;
3888       default:
3889         CheckVectorArgs = true;
3890         --Str;
3891         break;
3892       }
3893     }
3894     return Type;
3895   }
3896   default:
3897     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3898   }
3899 }
3900 
3901 static bool isPPC_64Builtin(unsigned BuiltinID) {
3902   // These builtins only work on PPC 64bit targets.
3903   switch (BuiltinID) {
3904   case PPC::BI__builtin_divde:
3905   case PPC::BI__builtin_divdeu:
3906   case PPC::BI__builtin_bpermd:
3907   case PPC::BI__builtin_pdepd:
3908   case PPC::BI__builtin_pextd:
3909   case PPC::BI__builtin_ppc_ldarx:
3910   case PPC::BI__builtin_ppc_stdcx:
3911   case PPC::BI__builtin_ppc_tdw:
3912   case PPC::BI__builtin_ppc_trapd:
3913   case PPC::BI__builtin_ppc_cmpeqb:
3914   case PPC::BI__builtin_ppc_setb:
3915   case PPC::BI__builtin_ppc_mulhd:
3916   case PPC::BI__builtin_ppc_mulhdu:
3917   case PPC::BI__builtin_ppc_maddhd:
3918   case PPC::BI__builtin_ppc_maddhdu:
3919   case PPC::BI__builtin_ppc_maddld:
3920   case PPC::BI__builtin_ppc_load8r:
3921   case PPC::BI__builtin_ppc_store8r:
3922   case PPC::BI__builtin_ppc_insert_exp:
3923   case PPC::BI__builtin_ppc_extract_sig:
3924   case PPC::BI__builtin_ppc_addex:
3925   case PPC::BI__builtin_darn:
3926   case PPC::BI__builtin_darn_raw:
3927   case PPC::BI__builtin_ppc_compare_and_swaplp:
3928   case PPC::BI__builtin_ppc_fetch_and_addlp:
3929   case PPC::BI__builtin_ppc_fetch_and_andlp:
3930   case PPC::BI__builtin_ppc_fetch_and_orlp:
3931   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3932     return true;
3933   }
3934   return false;
3935 }
3936 
3937 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3938                              StringRef FeatureToCheck, unsigned DiagID,
3939                              StringRef DiagArg = "") {
3940   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3941     return false;
3942 
3943   if (DiagArg.empty())
3944     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3945   else
3946     S.Diag(TheCall->getBeginLoc(), DiagID)
3947         << DiagArg << TheCall->getSourceRange();
3948 
3949   return true;
3950 }
3951 
3952 /// Returns true if the argument consists of one contiguous run of 1s with any
3953 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3954 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3955 /// since all 1s are not contiguous.
3956 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3957   llvm::APSInt Result;
3958   // We can't check the value of a dependent argument.
3959   Expr *Arg = TheCall->getArg(ArgNum);
3960   if (Arg->isTypeDependent() || Arg->isValueDependent())
3961     return false;
3962 
3963   // Check constant-ness first.
3964   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3965     return true;
3966 
3967   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3968   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3969     return false;
3970 
3971   return Diag(TheCall->getBeginLoc(),
3972               diag::err_argument_not_contiguous_bit_field)
3973          << ArgNum << Arg->getSourceRange();
3974 }
3975 
3976 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3977                                        CallExpr *TheCall) {
3978   unsigned i = 0, l = 0, u = 0;
3979   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3980   llvm::APSInt Result;
3981 
3982   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3983     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3984            << TheCall->getSourceRange();
3985 
3986   switch (BuiltinID) {
3987   default: return false;
3988   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3989   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3990     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3991            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3992   case PPC::BI__builtin_altivec_dss:
3993     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3994   case PPC::BI__builtin_tbegin:
3995   case PPC::BI__builtin_tend:
3996     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
3997            SemaFeatureCheck(*this, TheCall, "htm",
3998                             diag::err_ppc_builtin_requires_htm);
3999   case PPC::BI__builtin_tsr:
4000     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
4001            SemaFeatureCheck(*this, TheCall, "htm",
4002                             diag::err_ppc_builtin_requires_htm);
4003   case PPC::BI__builtin_tabortwc:
4004   case PPC::BI__builtin_tabortdc:
4005     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
4006            SemaFeatureCheck(*this, TheCall, "htm",
4007                             diag::err_ppc_builtin_requires_htm);
4008   case PPC::BI__builtin_tabortwci:
4009   case PPC::BI__builtin_tabortdci:
4010     return SemaFeatureCheck(*this, TheCall, "htm",
4011                             diag::err_ppc_builtin_requires_htm) ||
4012            (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
4013             SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
4014   case PPC::BI__builtin_tabort:
4015   case PPC::BI__builtin_tcheck:
4016   case PPC::BI__builtin_treclaim:
4017   case PPC::BI__builtin_trechkpt:
4018   case PPC::BI__builtin_tendall:
4019   case PPC::BI__builtin_tresume:
4020   case PPC::BI__builtin_tsuspend:
4021   case PPC::BI__builtin_get_texasr:
4022   case PPC::BI__builtin_get_texasru:
4023   case PPC::BI__builtin_get_tfhar:
4024   case PPC::BI__builtin_get_tfiar:
4025   case PPC::BI__builtin_set_texasr:
4026   case PPC::BI__builtin_set_texasru:
4027   case PPC::BI__builtin_set_tfhar:
4028   case PPC::BI__builtin_set_tfiar:
4029   case PPC::BI__builtin_ttest:
4030     return SemaFeatureCheck(*this, TheCall, "htm",
4031                             diag::err_ppc_builtin_requires_htm);
4032   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
4033   // __builtin_(un)pack_longdouble are available only if long double uses IBM
4034   // extended double representation.
4035   case PPC::BI__builtin_unpack_longdouble:
4036     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
4037       return true;
4038     LLVM_FALLTHROUGH;
4039   case PPC::BI__builtin_pack_longdouble:
4040     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
4041       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
4042              << "ibmlongdouble";
4043     return false;
4044   case PPC::BI__builtin_altivec_dst:
4045   case PPC::BI__builtin_altivec_dstt:
4046   case PPC::BI__builtin_altivec_dstst:
4047   case PPC::BI__builtin_altivec_dststt:
4048     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
4049   case PPC::BI__builtin_vsx_xxpermdi:
4050   case PPC::BI__builtin_vsx_xxsldwi:
4051     return SemaBuiltinVSX(TheCall);
4052   case PPC::BI__builtin_divwe:
4053   case PPC::BI__builtin_divweu:
4054   case PPC::BI__builtin_divde:
4055   case PPC::BI__builtin_divdeu:
4056     return SemaFeatureCheck(*this, TheCall, "extdiv",
4057                             diag::err_ppc_builtin_only_on_arch, "7");
4058   case PPC::BI__builtin_bpermd:
4059     return SemaFeatureCheck(*this, TheCall, "bpermd",
4060                             diag::err_ppc_builtin_only_on_arch, "7");
4061   case PPC::BI__builtin_unpack_vector_int128:
4062     return SemaFeatureCheck(*this, TheCall, "vsx",
4063                             diag::err_ppc_builtin_only_on_arch, "7") ||
4064            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
4065   case PPC::BI__builtin_pack_vector_int128:
4066     return SemaFeatureCheck(*this, TheCall, "vsx",
4067                             diag::err_ppc_builtin_only_on_arch, "7");
4068   case PPC::BI__builtin_pdepd:
4069   case PPC::BI__builtin_pextd:
4070     return SemaFeatureCheck(*this, TheCall, "isa-v31-instructions",
4071                             diag::err_ppc_builtin_only_on_arch, "10");
4072   case PPC::BI__builtin_altivec_vgnb:
4073      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
4074   case PPC::BI__builtin_altivec_vec_replace_elt:
4075   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
4076     QualType VecTy = TheCall->getArg(0)->getType();
4077     QualType EltTy = TheCall->getArg(1)->getType();
4078     unsigned Width = Context.getIntWidth(EltTy);
4079     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
4080            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
4081   }
4082   case PPC::BI__builtin_vsx_xxeval:
4083      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
4084   case PPC::BI__builtin_altivec_vsldbi:
4085      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
4086   case PPC::BI__builtin_altivec_vsrdbi:
4087      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
4088   case PPC::BI__builtin_vsx_xxpermx:
4089      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
4090   case PPC::BI__builtin_ppc_tw:
4091   case PPC::BI__builtin_ppc_tdw:
4092     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
4093   case PPC::BI__builtin_ppc_cmpeqb:
4094   case PPC::BI__builtin_ppc_setb:
4095   case PPC::BI__builtin_ppc_maddhd:
4096   case PPC::BI__builtin_ppc_maddhdu:
4097   case PPC::BI__builtin_ppc_maddld:
4098     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
4099                             diag::err_ppc_builtin_only_on_arch, "9");
4100   case PPC::BI__builtin_ppc_cmprb:
4101     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
4102                             diag::err_ppc_builtin_only_on_arch, "9") ||
4103            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
4104   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
4105   // be a constant that represents a contiguous bit field.
4106   case PPC::BI__builtin_ppc_rlwnm:
4107     return SemaValueIsRunOfOnes(TheCall, 2);
4108   case PPC::BI__builtin_ppc_rlwimi:
4109   case PPC::BI__builtin_ppc_rldimi:
4110     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
4111            SemaValueIsRunOfOnes(TheCall, 3);
4112   case PPC::BI__builtin_ppc_extract_exp:
4113   case PPC::BI__builtin_ppc_extract_sig:
4114   case PPC::BI__builtin_ppc_insert_exp:
4115     return SemaFeatureCheck(*this, TheCall, "power9-vector",
4116                             diag::err_ppc_builtin_only_on_arch, "9");
4117   case PPC::BI__builtin_ppc_addex: {
4118     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
4119                          diag::err_ppc_builtin_only_on_arch, "9") ||
4120         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
4121       return true;
4122     // Output warning for reserved values 1 to 3.
4123     int ArgValue =
4124         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
4125     if (ArgValue != 0)
4126       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
4127           << ArgValue;
4128     return false;
4129   }
4130   case PPC::BI__builtin_ppc_mtfsb0:
4131   case PPC::BI__builtin_ppc_mtfsb1:
4132     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
4133   case PPC::BI__builtin_ppc_mtfsf:
4134     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
4135   case PPC::BI__builtin_ppc_mtfsfi:
4136     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
4137            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4138   case PPC::BI__builtin_ppc_alignx:
4139     return SemaBuiltinConstantArgPower2(TheCall, 0);
4140   case PPC::BI__builtin_ppc_rdlam:
4141     return SemaValueIsRunOfOnes(TheCall, 2);
4142   case PPC::BI__builtin_ppc_icbt:
4143   case PPC::BI__builtin_ppc_sthcx:
4144   case PPC::BI__builtin_ppc_stbcx:
4145   case PPC::BI__builtin_ppc_lharx:
4146   case PPC::BI__builtin_ppc_lbarx:
4147     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
4148                             diag::err_ppc_builtin_only_on_arch, "8");
4149   case PPC::BI__builtin_vsx_ldrmb:
4150   case PPC::BI__builtin_vsx_strmb:
4151     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
4152                             diag::err_ppc_builtin_only_on_arch, "8") ||
4153            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
4154   case PPC::BI__builtin_altivec_vcntmbb:
4155   case PPC::BI__builtin_altivec_vcntmbh:
4156   case PPC::BI__builtin_altivec_vcntmbw:
4157   case PPC::BI__builtin_altivec_vcntmbd:
4158     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
4159   case PPC::BI__builtin_darn:
4160   case PPC::BI__builtin_darn_raw:
4161   case PPC::BI__builtin_darn_32:
4162     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
4163                             diag::err_ppc_builtin_only_on_arch, "9");
4164   case PPC::BI__builtin_vsx_xxgenpcvbm:
4165   case PPC::BI__builtin_vsx_xxgenpcvhm:
4166   case PPC::BI__builtin_vsx_xxgenpcvwm:
4167   case PPC::BI__builtin_vsx_xxgenpcvdm:
4168     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
4169   case PPC::BI__builtin_ppc_compare_exp_uo:
4170   case PPC::BI__builtin_ppc_compare_exp_lt:
4171   case PPC::BI__builtin_ppc_compare_exp_gt:
4172   case PPC::BI__builtin_ppc_compare_exp_eq:
4173     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
4174                             diag::err_ppc_builtin_only_on_arch, "9") ||
4175            SemaFeatureCheck(*this, TheCall, "vsx",
4176                             diag::err_ppc_builtin_requires_vsx);
4177   case PPC::BI__builtin_ppc_test_data_class: {
4178     // Check if the first argument of the __builtin_ppc_test_data_class call is
4179     // valid. The argument must be either a 'float' or a 'double'.
4180     QualType ArgType = TheCall->getArg(0)->getType();
4181     if (ArgType != QualType(Context.FloatTy) &&
4182         ArgType != QualType(Context.DoubleTy))
4183       return Diag(TheCall->getBeginLoc(),
4184                   diag::err_ppc_invalid_test_data_class_type);
4185     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
4186                             diag::err_ppc_builtin_only_on_arch, "9") ||
4187            SemaFeatureCheck(*this, TheCall, "vsx",
4188                             diag::err_ppc_builtin_requires_vsx) ||
4189            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
4190   }
4191   case PPC::BI__builtin_ppc_maxfe:
4192   case PPC::BI__builtin_ppc_minfe:
4193   case PPC::BI__builtin_ppc_maxfl:
4194   case PPC::BI__builtin_ppc_minfl:
4195   case PPC::BI__builtin_ppc_maxfs:
4196   case PPC::BI__builtin_ppc_minfs: {
4197     if (Context.getTargetInfo().getTriple().isOSAIX() &&
4198         (BuiltinID == PPC::BI__builtin_ppc_maxfe ||
4199          BuiltinID == PPC::BI__builtin_ppc_minfe))
4200       return Diag(TheCall->getBeginLoc(), diag::err_target_unsupported_type)
4201              << "builtin" << true << 128 << QualType(Context.LongDoubleTy)
4202              << false << Context.getTargetInfo().getTriple().str();
4203     // Argument type should be exact.
4204     QualType ArgType = QualType(Context.LongDoubleTy);
4205     if (BuiltinID == PPC::BI__builtin_ppc_maxfl ||
4206         BuiltinID == PPC::BI__builtin_ppc_minfl)
4207       ArgType = QualType(Context.DoubleTy);
4208     else if (BuiltinID == PPC::BI__builtin_ppc_maxfs ||
4209              BuiltinID == PPC::BI__builtin_ppc_minfs)
4210       ArgType = QualType(Context.FloatTy);
4211     for (unsigned I = 0, E = TheCall->getNumArgs(); I < E; ++I)
4212       if (TheCall->getArg(I)->getType() != ArgType)
4213         return Diag(TheCall->getBeginLoc(),
4214                     diag::err_typecheck_convert_incompatible)
4215                << TheCall->getArg(I)->getType() << ArgType << 1 << 0 << 0;
4216     return false;
4217   }
4218   case PPC::BI__builtin_ppc_load8r:
4219   case PPC::BI__builtin_ppc_store8r:
4220     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
4221                             diag::err_ppc_builtin_only_on_arch, "7");
4222 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
4223   case PPC::BI__builtin_##Name:                                                \
4224     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
4225 #include "clang/Basic/BuiltinsPPC.def"
4226   }
4227   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4228 }
4229 
4230 // Check if the given type is a non-pointer PPC MMA type. This function is used
4231 // in Sema to prevent invalid uses of restricted PPC MMA types.
4232 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
4233   if (Type->isPointerType() || Type->isArrayType())
4234     return false;
4235 
4236   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
4237 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
4238   if (false
4239 #include "clang/Basic/PPCTypes.def"
4240      ) {
4241     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
4242     return true;
4243   }
4244   return false;
4245 }
4246 
4247 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
4248                                           CallExpr *TheCall) {
4249   // position of memory order and scope arguments in the builtin
4250   unsigned OrderIndex, ScopeIndex;
4251   switch (BuiltinID) {
4252   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
4253   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
4254   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
4255   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
4256     OrderIndex = 2;
4257     ScopeIndex = 3;
4258     break;
4259   case AMDGPU::BI__builtin_amdgcn_fence:
4260     OrderIndex = 0;
4261     ScopeIndex = 1;
4262     break;
4263   default:
4264     return false;
4265   }
4266 
4267   ExprResult Arg = TheCall->getArg(OrderIndex);
4268   auto ArgExpr = Arg.get();
4269   Expr::EvalResult ArgResult;
4270 
4271   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
4272     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
4273            << ArgExpr->getType();
4274   auto Ord = ArgResult.Val.getInt().getZExtValue();
4275 
4276   // Check validity of memory ordering as per C11 / C++11's memody model.
4277   // Only fence needs check. Atomic dec/inc allow all memory orders.
4278   if (!llvm::isValidAtomicOrderingCABI(Ord))
4279     return Diag(ArgExpr->getBeginLoc(),
4280                 diag::warn_atomic_op_has_invalid_memory_order)
4281            << ArgExpr->getSourceRange();
4282   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
4283   case llvm::AtomicOrderingCABI::relaxed:
4284   case llvm::AtomicOrderingCABI::consume:
4285     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
4286       return Diag(ArgExpr->getBeginLoc(),
4287                   diag::warn_atomic_op_has_invalid_memory_order)
4288              << ArgExpr->getSourceRange();
4289     break;
4290   case llvm::AtomicOrderingCABI::acquire:
4291   case llvm::AtomicOrderingCABI::release:
4292   case llvm::AtomicOrderingCABI::acq_rel:
4293   case llvm::AtomicOrderingCABI::seq_cst:
4294     break;
4295   }
4296 
4297   Arg = TheCall->getArg(ScopeIndex);
4298   ArgExpr = Arg.get();
4299   Expr::EvalResult ArgResult1;
4300   // Check that sync scope is a constant literal
4301   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
4302     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
4303            << ArgExpr->getType();
4304 
4305   return false;
4306 }
4307 
4308 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
4309   llvm::APSInt Result;
4310 
4311   // We can't check the value of a dependent argument.
4312   Expr *Arg = TheCall->getArg(ArgNum);
4313   if (Arg->isTypeDependent() || Arg->isValueDependent())
4314     return false;
4315 
4316   // Check constant-ness first.
4317   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4318     return true;
4319 
4320   int64_t Val = Result.getSExtValue();
4321   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
4322     return false;
4323 
4324   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
4325          << Arg->getSourceRange();
4326 }
4327 
4328 static bool isRISCV32Builtin(unsigned BuiltinID) {
4329   // These builtins only work on riscv32 targets.
4330   switch (BuiltinID) {
4331   case RISCV::BI__builtin_riscv_zip_32:
4332   case RISCV::BI__builtin_riscv_unzip_32:
4333   case RISCV::BI__builtin_riscv_aes32dsi_32:
4334   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4335   case RISCV::BI__builtin_riscv_aes32esi_32:
4336   case RISCV::BI__builtin_riscv_aes32esmi_32:
4337   case RISCV::BI__builtin_riscv_sha512sig0h_32:
4338   case RISCV::BI__builtin_riscv_sha512sig0l_32:
4339   case RISCV::BI__builtin_riscv_sha512sig1h_32:
4340   case RISCV::BI__builtin_riscv_sha512sig1l_32:
4341   case RISCV::BI__builtin_riscv_sha512sum0r_32:
4342   case RISCV::BI__builtin_riscv_sha512sum1r_32:
4343     return true;
4344   }
4345 
4346   return false;
4347 }
4348 
4349 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
4350                                          unsigned BuiltinID,
4351                                          CallExpr *TheCall) {
4352   // CodeGenFunction can also detect this, but this gives a better error
4353   // message.
4354   bool FeatureMissing = false;
4355   SmallVector<StringRef> ReqFeatures;
4356   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
4357   Features.split(ReqFeatures, ',');
4358 
4359   // Check for 32-bit only builtins on a 64-bit target.
4360   const llvm::Triple &TT = TI.getTriple();
4361   if (TT.getArch() != llvm::Triple::riscv32 && isRISCV32Builtin(BuiltinID))
4362     return Diag(TheCall->getCallee()->getBeginLoc(),
4363                 diag::err_32_bit_builtin_64_bit_tgt);
4364 
4365   // Check if each required feature is included
4366   for (StringRef F : ReqFeatures) {
4367     SmallVector<StringRef> ReqOpFeatures;
4368     F.split(ReqOpFeatures, '|');
4369     bool HasFeature = false;
4370     for (StringRef OF : ReqOpFeatures) {
4371       if (TI.hasFeature(OF)) {
4372         HasFeature = true;
4373         continue;
4374       }
4375     }
4376 
4377     if (!HasFeature) {
4378       std::string FeatureStrs;
4379       for (StringRef OF : ReqOpFeatures) {
4380         // If the feature is 64bit, alter the string so it will print better in
4381         // the diagnostic.
4382         if (OF == "64bit")
4383           OF = "RV64";
4384 
4385         // Convert features like "zbr" and "experimental-zbr" to "Zbr".
4386         OF.consume_front("experimental-");
4387         std::string FeatureStr = OF.str();
4388         FeatureStr[0] = std::toupper(FeatureStr[0]);
4389         // Combine strings.
4390         FeatureStrs += FeatureStrs == "" ? "" : ", ";
4391         FeatureStrs += "'";
4392         FeatureStrs += FeatureStr;
4393         FeatureStrs += "'";
4394       }
4395       // Error message
4396       FeatureMissing = true;
4397       Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
4398           << TheCall->getSourceRange() << StringRef(FeatureStrs);
4399     }
4400   }
4401 
4402   if (FeatureMissing)
4403     return true;
4404 
4405   switch (BuiltinID) {
4406   case RISCVVector::BI__builtin_rvv_vsetvli:
4407     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
4408            CheckRISCVLMUL(TheCall, 2);
4409   case RISCVVector::BI__builtin_rvv_vsetvlimax:
4410     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
4411            CheckRISCVLMUL(TheCall, 1);
4412   case RISCVVector::BI__builtin_rvv_vget_v: {
4413     ASTContext::BuiltinVectorTypeInfo ResVecInfo =
4414         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4415             TheCall->getType().getCanonicalType().getTypePtr()));
4416     ASTContext::BuiltinVectorTypeInfo VecInfo =
4417         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4418             TheCall->getArg(0)->getType().getCanonicalType().getTypePtr()));
4419     unsigned MaxIndex =
4420         (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors) /
4421         (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors);
4422     return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
4423   }
4424   case RISCVVector::BI__builtin_rvv_vset_v: {
4425     ASTContext::BuiltinVectorTypeInfo ResVecInfo =
4426         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4427             TheCall->getType().getCanonicalType().getTypePtr()));
4428     ASTContext::BuiltinVectorTypeInfo VecInfo =
4429         Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
4430             TheCall->getArg(2)->getType().getCanonicalType().getTypePtr()));
4431     unsigned MaxIndex =
4432         (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors) /
4433         (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors);
4434     return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
4435   }
4436   // Check if byteselect is in [0, 3]
4437   case RISCV::BI__builtin_riscv_aes32dsi_32:
4438   case RISCV::BI__builtin_riscv_aes32dsmi_32:
4439   case RISCV::BI__builtin_riscv_aes32esi_32:
4440   case RISCV::BI__builtin_riscv_aes32esmi_32:
4441   case RISCV::BI__builtin_riscv_sm4ks:
4442   case RISCV::BI__builtin_riscv_sm4ed:
4443     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
4444   // Check if rnum is in [0, 10]
4445   case RISCV::BI__builtin_riscv_aes64ks1i_64:
4446     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 10);
4447   }
4448 
4449   return false;
4450 }
4451 
4452 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
4453                                            CallExpr *TheCall) {
4454   if (BuiltinID == SystemZ::BI__builtin_tabort) {
4455     Expr *Arg = TheCall->getArg(0);
4456     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
4457       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
4458         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
4459                << Arg->getSourceRange();
4460   }
4461 
4462   // For intrinsics which take an immediate value as part of the instruction,
4463   // range check them here.
4464   unsigned i = 0, l = 0, u = 0;
4465   switch (BuiltinID) {
4466   default: return false;
4467   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
4468   case SystemZ::BI__builtin_s390_verimb:
4469   case SystemZ::BI__builtin_s390_verimh:
4470   case SystemZ::BI__builtin_s390_verimf:
4471   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
4472   case SystemZ::BI__builtin_s390_vfaeb:
4473   case SystemZ::BI__builtin_s390_vfaeh:
4474   case SystemZ::BI__builtin_s390_vfaef:
4475   case SystemZ::BI__builtin_s390_vfaebs:
4476   case SystemZ::BI__builtin_s390_vfaehs:
4477   case SystemZ::BI__builtin_s390_vfaefs:
4478   case SystemZ::BI__builtin_s390_vfaezb:
4479   case SystemZ::BI__builtin_s390_vfaezh:
4480   case SystemZ::BI__builtin_s390_vfaezf:
4481   case SystemZ::BI__builtin_s390_vfaezbs:
4482   case SystemZ::BI__builtin_s390_vfaezhs:
4483   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
4484   case SystemZ::BI__builtin_s390_vfisb:
4485   case SystemZ::BI__builtin_s390_vfidb:
4486     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
4487            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4488   case SystemZ::BI__builtin_s390_vftcisb:
4489   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
4490   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
4491   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
4492   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
4493   case SystemZ::BI__builtin_s390_vstrcb:
4494   case SystemZ::BI__builtin_s390_vstrch:
4495   case SystemZ::BI__builtin_s390_vstrcf:
4496   case SystemZ::BI__builtin_s390_vstrczb:
4497   case SystemZ::BI__builtin_s390_vstrczh:
4498   case SystemZ::BI__builtin_s390_vstrczf:
4499   case SystemZ::BI__builtin_s390_vstrcbs:
4500   case SystemZ::BI__builtin_s390_vstrchs:
4501   case SystemZ::BI__builtin_s390_vstrcfs:
4502   case SystemZ::BI__builtin_s390_vstrczbs:
4503   case SystemZ::BI__builtin_s390_vstrczhs:
4504   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
4505   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
4506   case SystemZ::BI__builtin_s390_vfminsb:
4507   case SystemZ::BI__builtin_s390_vfmaxsb:
4508   case SystemZ::BI__builtin_s390_vfmindb:
4509   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
4510   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
4511   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
4512   case SystemZ::BI__builtin_s390_vclfnhs:
4513   case SystemZ::BI__builtin_s390_vclfnls:
4514   case SystemZ::BI__builtin_s390_vcfn:
4515   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
4516   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
4517   }
4518   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4519 }
4520 
4521 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
4522 /// This checks that the target supports __builtin_cpu_supports and
4523 /// that the string argument is constant and valid.
4524 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
4525                                    CallExpr *TheCall) {
4526   Expr *Arg = TheCall->getArg(0);
4527 
4528   // Check if the argument is a string literal.
4529   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4530     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4531            << Arg->getSourceRange();
4532 
4533   // Check the contents of the string.
4534   StringRef Feature =
4535       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4536   if (!TI.validateCpuSupports(Feature))
4537     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
4538            << Arg->getSourceRange();
4539   return false;
4540 }
4541 
4542 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
4543 /// This checks that the target supports __builtin_cpu_is and
4544 /// that the string argument is constant and valid.
4545 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
4546   Expr *Arg = TheCall->getArg(0);
4547 
4548   // Check if the argument is a string literal.
4549   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4550     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4551            << Arg->getSourceRange();
4552 
4553   // Check the contents of the string.
4554   StringRef Feature =
4555       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4556   if (!TI.validateCpuIs(Feature))
4557     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
4558            << Arg->getSourceRange();
4559   return false;
4560 }
4561 
4562 // Check if the rounding mode is legal.
4563 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
4564   // Indicates if this instruction has rounding control or just SAE.
4565   bool HasRC = false;
4566 
4567   unsigned ArgNum = 0;
4568   switch (BuiltinID) {
4569   default:
4570     return false;
4571   case X86::BI__builtin_ia32_vcvttsd2si32:
4572   case X86::BI__builtin_ia32_vcvttsd2si64:
4573   case X86::BI__builtin_ia32_vcvttsd2usi32:
4574   case X86::BI__builtin_ia32_vcvttsd2usi64:
4575   case X86::BI__builtin_ia32_vcvttss2si32:
4576   case X86::BI__builtin_ia32_vcvttss2si64:
4577   case X86::BI__builtin_ia32_vcvttss2usi32:
4578   case X86::BI__builtin_ia32_vcvttss2usi64:
4579   case X86::BI__builtin_ia32_vcvttsh2si32:
4580   case X86::BI__builtin_ia32_vcvttsh2si64:
4581   case X86::BI__builtin_ia32_vcvttsh2usi32:
4582   case X86::BI__builtin_ia32_vcvttsh2usi64:
4583     ArgNum = 1;
4584     break;
4585   case X86::BI__builtin_ia32_maxpd512:
4586   case X86::BI__builtin_ia32_maxps512:
4587   case X86::BI__builtin_ia32_minpd512:
4588   case X86::BI__builtin_ia32_minps512:
4589   case X86::BI__builtin_ia32_maxph512:
4590   case X86::BI__builtin_ia32_minph512:
4591     ArgNum = 2;
4592     break;
4593   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
4594   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
4595   case X86::BI__builtin_ia32_cvtps2pd512_mask:
4596   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
4597   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
4598   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
4599   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
4600   case X86::BI__builtin_ia32_cvttps2dq512_mask:
4601   case X86::BI__builtin_ia32_cvttps2qq512_mask:
4602   case X86::BI__builtin_ia32_cvttps2udq512_mask:
4603   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
4604   case X86::BI__builtin_ia32_vcvttph2w512_mask:
4605   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
4606   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
4607   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
4608   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
4609   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
4610   case X86::BI__builtin_ia32_exp2pd_mask:
4611   case X86::BI__builtin_ia32_exp2ps_mask:
4612   case X86::BI__builtin_ia32_getexppd512_mask:
4613   case X86::BI__builtin_ia32_getexpps512_mask:
4614   case X86::BI__builtin_ia32_getexpph512_mask:
4615   case X86::BI__builtin_ia32_rcp28pd_mask:
4616   case X86::BI__builtin_ia32_rcp28ps_mask:
4617   case X86::BI__builtin_ia32_rsqrt28pd_mask:
4618   case X86::BI__builtin_ia32_rsqrt28ps_mask:
4619   case X86::BI__builtin_ia32_vcomisd:
4620   case X86::BI__builtin_ia32_vcomiss:
4621   case X86::BI__builtin_ia32_vcomish:
4622   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
4623     ArgNum = 3;
4624     break;
4625   case X86::BI__builtin_ia32_cmppd512_mask:
4626   case X86::BI__builtin_ia32_cmpps512_mask:
4627   case X86::BI__builtin_ia32_cmpsd_mask:
4628   case X86::BI__builtin_ia32_cmpss_mask:
4629   case X86::BI__builtin_ia32_cmpsh_mask:
4630   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
4631   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
4632   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
4633   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4634   case X86::BI__builtin_ia32_getexpss128_round_mask:
4635   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4636   case X86::BI__builtin_ia32_getmantpd512_mask:
4637   case X86::BI__builtin_ia32_getmantps512_mask:
4638   case X86::BI__builtin_ia32_getmantph512_mask:
4639   case X86::BI__builtin_ia32_maxsd_round_mask:
4640   case X86::BI__builtin_ia32_maxss_round_mask:
4641   case X86::BI__builtin_ia32_maxsh_round_mask:
4642   case X86::BI__builtin_ia32_minsd_round_mask:
4643   case X86::BI__builtin_ia32_minss_round_mask:
4644   case X86::BI__builtin_ia32_minsh_round_mask:
4645   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4646   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4647   case X86::BI__builtin_ia32_reducepd512_mask:
4648   case X86::BI__builtin_ia32_reduceps512_mask:
4649   case X86::BI__builtin_ia32_reduceph512_mask:
4650   case X86::BI__builtin_ia32_rndscalepd_mask:
4651   case X86::BI__builtin_ia32_rndscaleps_mask:
4652   case X86::BI__builtin_ia32_rndscaleph_mask:
4653   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4654   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4655     ArgNum = 4;
4656     break;
4657   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4658   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4659   case X86::BI__builtin_ia32_fixupimmps512_mask:
4660   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4661   case X86::BI__builtin_ia32_fixupimmsd_mask:
4662   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4663   case X86::BI__builtin_ia32_fixupimmss_mask:
4664   case X86::BI__builtin_ia32_fixupimmss_maskz:
4665   case X86::BI__builtin_ia32_getmantsd_round_mask:
4666   case X86::BI__builtin_ia32_getmantss_round_mask:
4667   case X86::BI__builtin_ia32_getmantsh_round_mask:
4668   case X86::BI__builtin_ia32_rangepd512_mask:
4669   case X86::BI__builtin_ia32_rangeps512_mask:
4670   case X86::BI__builtin_ia32_rangesd128_round_mask:
4671   case X86::BI__builtin_ia32_rangess128_round_mask:
4672   case X86::BI__builtin_ia32_reducesd_mask:
4673   case X86::BI__builtin_ia32_reducess_mask:
4674   case X86::BI__builtin_ia32_reducesh_mask:
4675   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4676   case X86::BI__builtin_ia32_rndscaless_round_mask:
4677   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4678     ArgNum = 5;
4679     break;
4680   case X86::BI__builtin_ia32_vcvtsd2si64:
4681   case X86::BI__builtin_ia32_vcvtsd2si32:
4682   case X86::BI__builtin_ia32_vcvtsd2usi32:
4683   case X86::BI__builtin_ia32_vcvtsd2usi64:
4684   case X86::BI__builtin_ia32_vcvtss2si32:
4685   case X86::BI__builtin_ia32_vcvtss2si64:
4686   case X86::BI__builtin_ia32_vcvtss2usi32:
4687   case X86::BI__builtin_ia32_vcvtss2usi64:
4688   case X86::BI__builtin_ia32_vcvtsh2si32:
4689   case X86::BI__builtin_ia32_vcvtsh2si64:
4690   case X86::BI__builtin_ia32_vcvtsh2usi32:
4691   case X86::BI__builtin_ia32_vcvtsh2usi64:
4692   case X86::BI__builtin_ia32_sqrtpd512:
4693   case X86::BI__builtin_ia32_sqrtps512:
4694   case X86::BI__builtin_ia32_sqrtph512:
4695     ArgNum = 1;
4696     HasRC = true;
4697     break;
4698   case X86::BI__builtin_ia32_addph512:
4699   case X86::BI__builtin_ia32_divph512:
4700   case X86::BI__builtin_ia32_mulph512:
4701   case X86::BI__builtin_ia32_subph512:
4702   case X86::BI__builtin_ia32_addpd512:
4703   case X86::BI__builtin_ia32_addps512:
4704   case X86::BI__builtin_ia32_divpd512:
4705   case X86::BI__builtin_ia32_divps512:
4706   case X86::BI__builtin_ia32_mulpd512:
4707   case X86::BI__builtin_ia32_mulps512:
4708   case X86::BI__builtin_ia32_subpd512:
4709   case X86::BI__builtin_ia32_subps512:
4710   case X86::BI__builtin_ia32_cvtsi2sd64:
4711   case X86::BI__builtin_ia32_cvtsi2ss32:
4712   case X86::BI__builtin_ia32_cvtsi2ss64:
4713   case X86::BI__builtin_ia32_cvtusi2sd64:
4714   case X86::BI__builtin_ia32_cvtusi2ss32:
4715   case X86::BI__builtin_ia32_cvtusi2ss64:
4716   case X86::BI__builtin_ia32_vcvtusi2sh:
4717   case X86::BI__builtin_ia32_vcvtusi642sh:
4718   case X86::BI__builtin_ia32_vcvtsi2sh:
4719   case X86::BI__builtin_ia32_vcvtsi642sh:
4720     ArgNum = 2;
4721     HasRC = true;
4722     break;
4723   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4724   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4725   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4726   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4727   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4728   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4729   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4730   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4731   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4732   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4733   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4734   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4735   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4736   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4737   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4738   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4739   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4740   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4741   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4742   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4743   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4744   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4745   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4746   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4747   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4748   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4749   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4750   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4751   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4752     ArgNum = 3;
4753     HasRC = true;
4754     break;
4755   case X86::BI__builtin_ia32_addsh_round_mask:
4756   case X86::BI__builtin_ia32_addss_round_mask:
4757   case X86::BI__builtin_ia32_addsd_round_mask:
4758   case X86::BI__builtin_ia32_divsh_round_mask:
4759   case X86::BI__builtin_ia32_divss_round_mask:
4760   case X86::BI__builtin_ia32_divsd_round_mask:
4761   case X86::BI__builtin_ia32_mulsh_round_mask:
4762   case X86::BI__builtin_ia32_mulss_round_mask:
4763   case X86::BI__builtin_ia32_mulsd_round_mask:
4764   case X86::BI__builtin_ia32_subsh_round_mask:
4765   case X86::BI__builtin_ia32_subss_round_mask:
4766   case X86::BI__builtin_ia32_subsd_round_mask:
4767   case X86::BI__builtin_ia32_scalefph512_mask:
4768   case X86::BI__builtin_ia32_scalefpd512_mask:
4769   case X86::BI__builtin_ia32_scalefps512_mask:
4770   case X86::BI__builtin_ia32_scalefsd_round_mask:
4771   case X86::BI__builtin_ia32_scalefss_round_mask:
4772   case X86::BI__builtin_ia32_scalefsh_round_mask:
4773   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4774   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4775   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4776   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4777   case X86::BI__builtin_ia32_sqrtss_round_mask:
4778   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4779   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4780   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4781   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4782   case X86::BI__builtin_ia32_vfmaddss3_mask:
4783   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4784   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4785   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4786   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4787   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4788   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4789   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4790   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4791   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4792   case X86::BI__builtin_ia32_vfmaddps512_mask:
4793   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4794   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4795   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4796   case X86::BI__builtin_ia32_vfmaddph512_mask:
4797   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4798   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4799   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4800   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4801   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4802   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4803   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4804   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4805   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4806   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4807   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4808   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4809   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4810   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4811   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4812   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4813   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4814   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4815   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4816   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4817   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4818   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4819   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4820   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4821   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4822   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4823   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4824   case X86::BI__builtin_ia32_vfmulcsh_mask:
4825   case X86::BI__builtin_ia32_vfmulcph512_mask:
4826   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4827   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4828     ArgNum = 4;
4829     HasRC = true;
4830     break;
4831   }
4832 
4833   llvm::APSInt Result;
4834 
4835   // We can't check the value of a dependent argument.
4836   Expr *Arg = TheCall->getArg(ArgNum);
4837   if (Arg->isTypeDependent() || Arg->isValueDependent())
4838     return false;
4839 
4840   // Check constant-ness first.
4841   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4842     return true;
4843 
4844   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4845   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4846   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4847   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4848   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4849       Result == 8/*ROUND_NO_EXC*/ ||
4850       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4851       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4852     return false;
4853 
4854   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4855          << Arg->getSourceRange();
4856 }
4857 
4858 // Check if the gather/scatter scale is legal.
4859 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4860                                              CallExpr *TheCall) {
4861   unsigned ArgNum = 0;
4862   switch (BuiltinID) {
4863   default:
4864     return false;
4865   case X86::BI__builtin_ia32_gatherpfdpd:
4866   case X86::BI__builtin_ia32_gatherpfdps:
4867   case X86::BI__builtin_ia32_gatherpfqpd:
4868   case X86::BI__builtin_ia32_gatherpfqps:
4869   case X86::BI__builtin_ia32_scatterpfdpd:
4870   case X86::BI__builtin_ia32_scatterpfdps:
4871   case X86::BI__builtin_ia32_scatterpfqpd:
4872   case X86::BI__builtin_ia32_scatterpfqps:
4873     ArgNum = 3;
4874     break;
4875   case X86::BI__builtin_ia32_gatherd_pd:
4876   case X86::BI__builtin_ia32_gatherd_pd256:
4877   case X86::BI__builtin_ia32_gatherq_pd:
4878   case X86::BI__builtin_ia32_gatherq_pd256:
4879   case X86::BI__builtin_ia32_gatherd_ps:
4880   case X86::BI__builtin_ia32_gatherd_ps256:
4881   case X86::BI__builtin_ia32_gatherq_ps:
4882   case X86::BI__builtin_ia32_gatherq_ps256:
4883   case X86::BI__builtin_ia32_gatherd_q:
4884   case X86::BI__builtin_ia32_gatherd_q256:
4885   case X86::BI__builtin_ia32_gatherq_q:
4886   case X86::BI__builtin_ia32_gatherq_q256:
4887   case X86::BI__builtin_ia32_gatherd_d:
4888   case X86::BI__builtin_ia32_gatherd_d256:
4889   case X86::BI__builtin_ia32_gatherq_d:
4890   case X86::BI__builtin_ia32_gatherq_d256:
4891   case X86::BI__builtin_ia32_gather3div2df:
4892   case X86::BI__builtin_ia32_gather3div2di:
4893   case X86::BI__builtin_ia32_gather3div4df:
4894   case X86::BI__builtin_ia32_gather3div4di:
4895   case X86::BI__builtin_ia32_gather3div4sf:
4896   case X86::BI__builtin_ia32_gather3div4si:
4897   case X86::BI__builtin_ia32_gather3div8sf:
4898   case X86::BI__builtin_ia32_gather3div8si:
4899   case X86::BI__builtin_ia32_gather3siv2df:
4900   case X86::BI__builtin_ia32_gather3siv2di:
4901   case X86::BI__builtin_ia32_gather3siv4df:
4902   case X86::BI__builtin_ia32_gather3siv4di:
4903   case X86::BI__builtin_ia32_gather3siv4sf:
4904   case X86::BI__builtin_ia32_gather3siv4si:
4905   case X86::BI__builtin_ia32_gather3siv8sf:
4906   case X86::BI__builtin_ia32_gather3siv8si:
4907   case X86::BI__builtin_ia32_gathersiv8df:
4908   case X86::BI__builtin_ia32_gathersiv16sf:
4909   case X86::BI__builtin_ia32_gatherdiv8df:
4910   case X86::BI__builtin_ia32_gatherdiv16sf:
4911   case X86::BI__builtin_ia32_gathersiv8di:
4912   case X86::BI__builtin_ia32_gathersiv16si:
4913   case X86::BI__builtin_ia32_gatherdiv8di:
4914   case X86::BI__builtin_ia32_gatherdiv16si:
4915   case X86::BI__builtin_ia32_scatterdiv2df:
4916   case X86::BI__builtin_ia32_scatterdiv2di:
4917   case X86::BI__builtin_ia32_scatterdiv4df:
4918   case X86::BI__builtin_ia32_scatterdiv4di:
4919   case X86::BI__builtin_ia32_scatterdiv4sf:
4920   case X86::BI__builtin_ia32_scatterdiv4si:
4921   case X86::BI__builtin_ia32_scatterdiv8sf:
4922   case X86::BI__builtin_ia32_scatterdiv8si:
4923   case X86::BI__builtin_ia32_scattersiv2df:
4924   case X86::BI__builtin_ia32_scattersiv2di:
4925   case X86::BI__builtin_ia32_scattersiv4df:
4926   case X86::BI__builtin_ia32_scattersiv4di:
4927   case X86::BI__builtin_ia32_scattersiv4sf:
4928   case X86::BI__builtin_ia32_scattersiv4si:
4929   case X86::BI__builtin_ia32_scattersiv8sf:
4930   case X86::BI__builtin_ia32_scattersiv8si:
4931   case X86::BI__builtin_ia32_scattersiv8df:
4932   case X86::BI__builtin_ia32_scattersiv16sf:
4933   case X86::BI__builtin_ia32_scatterdiv8df:
4934   case X86::BI__builtin_ia32_scatterdiv16sf:
4935   case X86::BI__builtin_ia32_scattersiv8di:
4936   case X86::BI__builtin_ia32_scattersiv16si:
4937   case X86::BI__builtin_ia32_scatterdiv8di:
4938   case X86::BI__builtin_ia32_scatterdiv16si:
4939     ArgNum = 4;
4940     break;
4941   }
4942 
4943   llvm::APSInt Result;
4944 
4945   // We can't check the value of a dependent argument.
4946   Expr *Arg = TheCall->getArg(ArgNum);
4947   if (Arg->isTypeDependent() || Arg->isValueDependent())
4948     return false;
4949 
4950   // Check constant-ness first.
4951   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4952     return true;
4953 
4954   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4955     return false;
4956 
4957   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4958          << Arg->getSourceRange();
4959 }
4960 
4961 enum { TileRegLow = 0, TileRegHigh = 7 };
4962 
4963 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4964                                              ArrayRef<int> ArgNums) {
4965   for (int ArgNum : ArgNums) {
4966     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4967       return true;
4968   }
4969   return false;
4970 }
4971 
4972 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4973                                         ArrayRef<int> ArgNums) {
4974   // Because the max number of tile register is TileRegHigh + 1, so here we use
4975   // each bit to represent the usage of them in bitset.
4976   std::bitset<TileRegHigh + 1> ArgValues;
4977   for (int ArgNum : ArgNums) {
4978     Expr *Arg = TheCall->getArg(ArgNum);
4979     if (Arg->isTypeDependent() || Arg->isValueDependent())
4980       continue;
4981 
4982     llvm::APSInt Result;
4983     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4984       return true;
4985     int ArgExtValue = Result.getExtValue();
4986     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4987            "Incorrect tile register num.");
4988     if (ArgValues.test(ArgExtValue))
4989       return Diag(TheCall->getBeginLoc(),
4990                   diag::err_x86_builtin_tile_arg_duplicate)
4991              << TheCall->getArg(ArgNum)->getSourceRange();
4992     ArgValues.set(ArgExtValue);
4993   }
4994   return false;
4995 }
4996 
4997 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4998                                                 ArrayRef<int> ArgNums) {
4999   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
5000          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
5001 }
5002 
5003 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
5004   switch (BuiltinID) {
5005   default:
5006     return false;
5007   case X86::BI__builtin_ia32_tileloadd64:
5008   case X86::BI__builtin_ia32_tileloaddt164:
5009   case X86::BI__builtin_ia32_tilestored64:
5010   case X86::BI__builtin_ia32_tilezero:
5011     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
5012   case X86::BI__builtin_ia32_tdpbssd:
5013   case X86::BI__builtin_ia32_tdpbsud:
5014   case X86::BI__builtin_ia32_tdpbusd:
5015   case X86::BI__builtin_ia32_tdpbuud:
5016   case X86::BI__builtin_ia32_tdpbf16ps:
5017     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
5018   }
5019 }
5020 static bool isX86_32Builtin(unsigned BuiltinID) {
5021   // These builtins only work on x86-32 targets.
5022   switch (BuiltinID) {
5023   case X86::BI__builtin_ia32_readeflags_u32:
5024   case X86::BI__builtin_ia32_writeeflags_u32:
5025     return true;
5026   }
5027 
5028   return false;
5029 }
5030 
5031 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
5032                                        CallExpr *TheCall) {
5033   if (BuiltinID == X86::BI__builtin_cpu_supports)
5034     return SemaBuiltinCpuSupports(*this, TI, TheCall);
5035 
5036   if (BuiltinID == X86::BI__builtin_cpu_is)
5037     return SemaBuiltinCpuIs(*this, TI, TheCall);
5038 
5039   // Check for 32-bit only builtins on a 64-bit target.
5040   const llvm::Triple &TT = TI.getTriple();
5041   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
5042     return Diag(TheCall->getCallee()->getBeginLoc(),
5043                 diag::err_32_bit_builtin_64_bit_tgt);
5044 
5045   // If the intrinsic has rounding or SAE make sure its valid.
5046   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
5047     return true;
5048 
5049   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
5050   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
5051     return true;
5052 
5053   // If the intrinsic has a tile arguments, make sure they are valid.
5054   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
5055     return true;
5056 
5057   // For intrinsics which take an immediate value as part of the instruction,
5058   // range check them here.
5059   int i = 0, l = 0, u = 0;
5060   switch (BuiltinID) {
5061   default:
5062     return false;
5063   case X86::BI__builtin_ia32_vec_ext_v2si:
5064   case X86::BI__builtin_ia32_vec_ext_v2di:
5065   case X86::BI__builtin_ia32_vextractf128_pd256:
5066   case X86::BI__builtin_ia32_vextractf128_ps256:
5067   case X86::BI__builtin_ia32_vextractf128_si256:
5068   case X86::BI__builtin_ia32_extract128i256:
5069   case X86::BI__builtin_ia32_extractf64x4_mask:
5070   case X86::BI__builtin_ia32_extracti64x4_mask:
5071   case X86::BI__builtin_ia32_extractf32x8_mask:
5072   case X86::BI__builtin_ia32_extracti32x8_mask:
5073   case X86::BI__builtin_ia32_extractf64x2_256_mask:
5074   case X86::BI__builtin_ia32_extracti64x2_256_mask:
5075   case X86::BI__builtin_ia32_extractf32x4_256_mask:
5076   case X86::BI__builtin_ia32_extracti32x4_256_mask:
5077     i = 1; l = 0; u = 1;
5078     break;
5079   case X86::BI__builtin_ia32_vec_set_v2di:
5080   case X86::BI__builtin_ia32_vinsertf128_pd256:
5081   case X86::BI__builtin_ia32_vinsertf128_ps256:
5082   case X86::BI__builtin_ia32_vinsertf128_si256:
5083   case X86::BI__builtin_ia32_insert128i256:
5084   case X86::BI__builtin_ia32_insertf32x8:
5085   case X86::BI__builtin_ia32_inserti32x8:
5086   case X86::BI__builtin_ia32_insertf64x4:
5087   case X86::BI__builtin_ia32_inserti64x4:
5088   case X86::BI__builtin_ia32_insertf64x2_256:
5089   case X86::BI__builtin_ia32_inserti64x2_256:
5090   case X86::BI__builtin_ia32_insertf32x4_256:
5091   case X86::BI__builtin_ia32_inserti32x4_256:
5092     i = 2; l = 0; u = 1;
5093     break;
5094   case X86::BI__builtin_ia32_vpermilpd:
5095   case X86::BI__builtin_ia32_vec_ext_v4hi:
5096   case X86::BI__builtin_ia32_vec_ext_v4si:
5097   case X86::BI__builtin_ia32_vec_ext_v4sf:
5098   case X86::BI__builtin_ia32_vec_ext_v4di:
5099   case X86::BI__builtin_ia32_extractf32x4_mask:
5100   case X86::BI__builtin_ia32_extracti32x4_mask:
5101   case X86::BI__builtin_ia32_extractf64x2_512_mask:
5102   case X86::BI__builtin_ia32_extracti64x2_512_mask:
5103     i = 1; l = 0; u = 3;
5104     break;
5105   case X86::BI_mm_prefetch:
5106   case X86::BI__builtin_ia32_vec_ext_v8hi:
5107   case X86::BI__builtin_ia32_vec_ext_v8si:
5108     i = 1; l = 0; u = 7;
5109     break;
5110   case X86::BI__builtin_ia32_sha1rnds4:
5111   case X86::BI__builtin_ia32_blendpd:
5112   case X86::BI__builtin_ia32_shufpd:
5113   case X86::BI__builtin_ia32_vec_set_v4hi:
5114   case X86::BI__builtin_ia32_vec_set_v4si:
5115   case X86::BI__builtin_ia32_vec_set_v4di:
5116   case X86::BI__builtin_ia32_shuf_f32x4_256:
5117   case X86::BI__builtin_ia32_shuf_f64x2_256:
5118   case X86::BI__builtin_ia32_shuf_i32x4_256:
5119   case X86::BI__builtin_ia32_shuf_i64x2_256:
5120   case X86::BI__builtin_ia32_insertf64x2_512:
5121   case X86::BI__builtin_ia32_inserti64x2_512:
5122   case X86::BI__builtin_ia32_insertf32x4:
5123   case X86::BI__builtin_ia32_inserti32x4:
5124     i = 2; l = 0; u = 3;
5125     break;
5126   case X86::BI__builtin_ia32_vpermil2pd:
5127   case X86::BI__builtin_ia32_vpermil2pd256:
5128   case X86::BI__builtin_ia32_vpermil2ps:
5129   case X86::BI__builtin_ia32_vpermil2ps256:
5130     i = 3; l = 0; u = 3;
5131     break;
5132   case X86::BI__builtin_ia32_cmpb128_mask:
5133   case X86::BI__builtin_ia32_cmpw128_mask:
5134   case X86::BI__builtin_ia32_cmpd128_mask:
5135   case X86::BI__builtin_ia32_cmpq128_mask:
5136   case X86::BI__builtin_ia32_cmpb256_mask:
5137   case X86::BI__builtin_ia32_cmpw256_mask:
5138   case X86::BI__builtin_ia32_cmpd256_mask:
5139   case X86::BI__builtin_ia32_cmpq256_mask:
5140   case X86::BI__builtin_ia32_cmpb512_mask:
5141   case X86::BI__builtin_ia32_cmpw512_mask:
5142   case X86::BI__builtin_ia32_cmpd512_mask:
5143   case X86::BI__builtin_ia32_cmpq512_mask:
5144   case X86::BI__builtin_ia32_ucmpb128_mask:
5145   case X86::BI__builtin_ia32_ucmpw128_mask:
5146   case X86::BI__builtin_ia32_ucmpd128_mask:
5147   case X86::BI__builtin_ia32_ucmpq128_mask:
5148   case X86::BI__builtin_ia32_ucmpb256_mask:
5149   case X86::BI__builtin_ia32_ucmpw256_mask:
5150   case X86::BI__builtin_ia32_ucmpd256_mask:
5151   case X86::BI__builtin_ia32_ucmpq256_mask:
5152   case X86::BI__builtin_ia32_ucmpb512_mask:
5153   case X86::BI__builtin_ia32_ucmpw512_mask:
5154   case X86::BI__builtin_ia32_ucmpd512_mask:
5155   case X86::BI__builtin_ia32_ucmpq512_mask:
5156   case X86::BI__builtin_ia32_vpcomub:
5157   case X86::BI__builtin_ia32_vpcomuw:
5158   case X86::BI__builtin_ia32_vpcomud:
5159   case X86::BI__builtin_ia32_vpcomuq:
5160   case X86::BI__builtin_ia32_vpcomb:
5161   case X86::BI__builtin_ia32_vpcomw:
5162   case X86::BI__builtin_ia32_vpcomd:
5163   case X86::BI__builtin_ia32_vpcomq:
5164   case X86::BI__builtin_ia32_vec_set_v8hi:
5165   case X86::BI__builtin_ia32_vec_set_v8si:
5166     i = 2; l = 0; u = 7;
5167     break;
5168   case X86::BI__builtin_ia32_vpermilpd256:
5169   case X86::BI__builtin_ia32_roundps:
5170   case X86::BI__builtin_ia32_roundpd:
5171   case X86::BI__builtin_ia32_roundps256:
5172   case X86::BI__builtin_ia32_roundpd256:
5173   case X86::BI__builtin_ia32_getmantpd128_mask:
5174   case X86::BI__builtin_ia32_getmantpd256_mask:
5175   case X86::BI__builtin_ia32_getmantps128_mask:
5176   case X86::BI__builtin_ia32_getmantps256_mask:
5177   case X86::BI__builtin_ia32_getmantpd512_mask:
5178   case X86::BI__builtin_ia32_getmantps512_mask:
5179   case X86::BI__builtin_ia32_getmantph128_mask:
5180   case X86::BI__builtin_ia32_getmantph256_mask:
5181   case X86::BI__builtin_ia32_getmantph512_mask:
5182   case X86::BI__builtin_ia32_vec_ext_v16qi:
5183   case X86::BI__builtin_ia32_vec_ext_v16hi:
5184     i = 1; l = 0; u = 15;
5185     break;
5186   case X86::BI__builtin_ia32_pblendd128:
5187   case X86::BI__builtin_ia32_blendps:
5188   case X86::BI__builtin_ia32_blendpd256:
5189   case X86::BI__builtin_ia32_shufpd256:
5190   case X86::BI__builtin_ia32_roundss:
5191   case X86::BI__builtin_ia32_roundsd:
5192   case X86::BI__builtin_ia32_rangepd128_mask:
5193   case X86::BI__builtin_ia32_rangepd256_mask:
5194   case X86::BI__builtin_ia32_rangepd512_mask:
5195   case X86::BI__builtin_ia32_rangeps128_mask:
5196   case X86::BI__builtin_ia32_rangeps256_mask:
5197   case X86::BI__builtin_ia32_rangeps512_mask:
5198   case X86::BI__builtin_ia32_getmantsd_round_mask:
5199   case X86::BI__builtin_ia32_getmantss_round_mask:
5200   case X86::BI__builtin_ia32_getmantsh_round_mask:
5201   case X86::BI__builtin_ia32_vec_set_v16qi:
5202   case X86::BI__builtin_ia32_vec_set_v16hi:
5203     i = 2; l = 0; u = 15;
5204     break;
5205   case X86::BI__builtin_ia32_vec_ext_v32qi:
5206     i = 1; l = 0; u = 31;
5207     break;
5208   case X86::BI__builtin_ia32_cmpps:
5209   case X86::BI__builtin_ia32_cmpss:
5210   case X86::BI__builtin_ia32_cmppd:
5211   case X86::BI__builtin_ia32_cmpsd:
5212   case X86::BI__builtin_ia32_cmpps256:
5213   case X86::BI__builtin_ia32_cmppd256:
5214   case X86::BI__builtin_ia32_cmpps128_mask:
5215   case X86::BI__builtin_ia32_cmppd128_mask:
5216   case X86::BI__builtin_ia32_cmpps256_mask:
5217   case X86::BI__builtin_ia32_cmppd256_mask:
5218   case X86::BI__builtin_ia32_cmpps512_mask:
5219   case X86::BI__builtin_ia32_cmppd512_mask:
5220   case X86::BI__builtin_ia32_cmpsd_mask:
5221   case X86::BI__builtin_ia32_cmpss_mask:
5222   case X86::BI__builtin_ia32_vec_set_v32qi:
5223     i = 2; l = 0; u = 31;
5224     break;
5225   case X86::BI__builtin_ia32_permdf256:
5226   case X86::BI__builtin_ia32_permdi256:
5227   case X86::BI__builtin_ia32_permdf512:
5228   case X86::BI__builtin_ia32_permdi512:
5229   case X86::BI__builtin_ia32_vpermilps:
5230   case X86::BI__builtin_ia32_vpermilps256:
5231   case X86::BI__builtin_ia32_vpermilpd512:
5232   case X86::BI__builtin_ia32_vpermilps512:
5233   case X86::BI__builtin_ia32_pshufd:
5234   case X86::BI__builtin_ia32_pshufd256:
5235   case X86::BI__builtin_ia32_pshufd512:
5236   case X86::BI__builtin_ia32_pshufhw:
5237   case X86::BI__builtin_ia32_pshufhw256:
5238   case X86::BI__builtin_ia32_pshufhw512:
5239   case X86::BI__builtin_ia32_pshuflw:
5240   case X86::BI__builtin_ia32_pshuflw256:
5241   case X86::BI__builtin_ia32_pshuflw512:
5242   case X86::BI__builtin_ia32_vcvtps2ph:
5243   case X86::BI__builtin_ia32_vcvtps2ph_mask:
5244   case X86::BI__builtin_ia32_vcvtps2ph256:
5245   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
5246   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
5247   case X86::BI__builtin_ia32_rndscaleps_128_mask:
5248   case X86::BI__builtin_ia32_rndscalepd_128_mask:
5249   case X86::BI__builtin_ia32_rndscaleps_256_mask:
5250   case X86::BI__builtin_ia32_rndscalepd_256_mask:
5251   case X86::BI__builtin_ia32_rndscaleps_mask:
5252   case X86::BI__builtin_ia32_rndscalepd_mask:
5253   case X86::BI__builtin_ia32_rndscaleph_mask:
5254   case X86::BI__builtin_ia32_reducepd128_mask:
5255   case X86::BI__builtin_ia32_reducepd256_mask:
5256   case X86::BI__builtin_ia32_reducepd512_mask:
5257   case X86::BI__builtin_ia32_reduceps128_mask:
5258   case X86::BI__builtin_ia32_reduceps256_mask:
5259   case X86::BI__builtin_ia32_reduceps512_mask:
5260   case X86::BI__builtin_ia32_reduceph128_mask:
5261   case X86::BI__builtin_ia32_reduceph256_mask:
5262   case X86::BI__builtin_ia32_reduceph512_mask:
5263   case X86::BI__builtin_ia32_prold512:
5264   case X86::BI__builtin_ia32_prolq512:
5265   case X86::BI__builtin_ia32_prold128:
5266   case X86::BI__builtin_ia32_prold256:
5267   case X86::BI__builtin_ia32_prolq128:
5268   case X86::BI__builtin_ia32_prolq256:
5269   case X86::BI__builtin_ia32_prord512:
5270   case X86::BI__builtin_ia32_prorq512:
5271   case X86::BI__builtin_ia32_prord128:
5272   case X86::BI__builtin_ia32_prord256:
5273   case X86::BI__builtin_ia32_prorq128:
5274   case X86::BI__builtin_ia32_prorq256:
5275   case X86::BI__builtin_ia32_fpclasspd128_mask:
5276   case X86::BI__builtin_ia32_fpclasspd256_mask:
5277   case X86::BI__builtin_ia32_fpclassps128_mask:
5278   case X86::BI__builtin_ia32_fpclassps256_mask:
5279   case X86::BI__builtin_ia32_fpclassps512_mask:
5280   case X86::BI__builtin_ia32_fpclasspd512_mask:
5281   case X86::BI__builtin_ia32_fpclassph128_mask:
5282   case X86::BI__builtin_ia32_fpclassph256_mask:
5283   case X86::BI__builtin_ia32_fpclassph512_mask:
5284   case X86::BI__builtin_ia32_fpclasssd_mask:
5285   case X86::BI__builtin_ia32_fpclassss_mask:
5286   case X86::BI__builtin_ia32_fpclasssh_mask:
5287   case X86::BI__builtin_ia32_pslldqi128_byteshift:
5288   case X86::BI__builtin_ia32_pslldqi256_byteshift:
5289   case X86::BI__builtin_ia32_pslldqi512_byteshift:
5290   case X86::BI__builtin_ia32_psrldqi128_byteshift:
5291   case X86::BI__builtin_ia32_psrldqi256_byteshift:
5292   case X86::BI__builtin_ia32_psrldqi512_byteshift:
5293   case X86::BI__builtin_ia32_kshiftliqi:
5294   case X86::BI__builtin_ia32_kshiftlihi:
5295   case X86::BI__builtin_ia32_kshiftlisi:
5296   case X86::BI__builtin_ia32_kshiftlidi:
5297   case X86::BI__builtin_ia32_kshiftriqi:
5298   case X86::BI__builtin_ia32_kshiftrihi:
5299   case X86::BI__builtin_ia32_kshiftrisi:
5300   case X86::BI__builtin_ia32_kshiftridi:
5301     i = 1; l = 0; u = 255;
5302     break;
5303   case X86::BI__builtin_ia32_vperm2f128_pd256:
5304   case X86::BI__builtin_ia32_vperm2f128_ps256:
5305   case X86::BI__builtin_ia32_vperm2f128_si256:
5306   case X86::BI__builtin_ia32_permti256:
5307   case X86::BI__builtin_ia32_pblendw128:
5308   case X86::BI__builtin_ia32_pblendw256:
5309   case X86::BI__builtin_ia32_blendps256:
5310   case X86::BI__builtin_ia32_pblendd256:
5311   case X86::BI__builtin_ia32_palignr128:
5312   case X86::BI__builtin_ia32_palignr256:
5313   case X86::BI__builtin_ia32_palignr512:
5314   case X86::BI__builtin_ia32_alignq512:
5315   case X86::BI__builtin_ia32_alignd512:
5316   case X86::BI__builtin_ia32_alignd128:
5317   case X86::BI__builtin_ia32_alignd256:
5318   case X86::BI__builtin_ia32_alignq128:
5319   case X86::BI__builtin_ia32_alignq256:
5320   case X86::BI__builtin_ia32_vcomisd:
5321   case X86::BI__builtin_ia32_vcomiss:
5322   case X86::BI__builtin_ia32_shuf_f32x4:
5323   case X86::BI__builtin_ia32_shuf_f64x2:
5324   case X86::BI__builtin_ia32_shuf_i32x4:
5325   case X86::BI__builtin_ia32_shuf_i64x2:
5326   case X86::BI__builtin_ia32_shufpd512:
5327   case X86::BI__builtin_ia32_shufps:
5328   case X86::BI__builtin_ia32_shufps256:
5329   case X86::BI__builtin_ia32_shufps512:
5330   case X86::BI__builtin_ia32_dbpsadbw128:
5331   case X86::BI__builtin_ia32_dbpsadbw256:
5332   case X86::BI__builtin_ia32_dbpsadbw512:
5333   case X86::BI__builtin_ia32_vpshldd128:
5334   case X86::BI__builtin_ia32_vpshldd256:
5335   case X86::BI__builtin_ia32_vpshldd512:
5336   case X86::BI__builtin_ia32_vpshldq128:
5337   case X86::BI__builtin_ia32_vpshldq256:
5338   case X86::BI__builtin_ia32_vpshldq512:
5339   case X86::BI__builtin_ia32_vpshldw128:
5340   case X86::BI__builtin_ia32_vpshldw256:
5341   case X86::BI__builtin_ia32_vpshldw512:
5342   case X86::BI__builtin_ia32_vpshrdd128:
5343   case X86::BI__builtin_ia32_vpshrdd256:
5344   case X86::BI__builtin_ia32_vpshrdd512:
5345   case X86::BI__builtin_ia32_vpshrdq128:
5346   case X86::BI__builtin_ia32_vpshrdq256:
5347   case X86::BI__builtin_ia32_vpshrdq512:
5348   case X86::BI__builtin_ia32_vpshrdw128:
5349   case X86::BI__builtin_ia32_vpshrdw256:
5350   case X86::BI__builtin_ia32_vpshrdw512:
5351     i = 2; l = 0; u = 255;
5352     break;
5353   case X86::BI__builtin_ia32_fixupimmpd512_mask:
5354   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
5355   case X86::BI__builtin_ia32_fixupimmps512_mask:
5356   case X86::BI__builtin_ia32_fixupimmps512_maskz:
5357   case X86::BI__builtin_ia32_fixupimmsd_mask:
5358   case X86::BI__builtin_ia32_fixupimmsd_maskz:
5359   case X86::BI__builtin_ia32_fixupimmss_mask:
5360   case X86::BI__builtin_ia32_fixupimmss_maskz:
5361   case X86::BI__builtin_ia32_fixupimmpd128_mask:
5362   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
5363   case X86::BI__builtin_ia32_fixupimmpd256_mask:
5364   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
5365   case X86::BI__builtin_ia32_fixupimmps128_mask:
5366   case X86::BI__builtin_ia32_fixupimmps128_maskz:
5367   case X86::BI__builtin_ia32_fixupimmps256_mask:
5368   case X86::BI__builtin_ia32_fixupimmps256_maskz:
5369   case X86::BI__builtin_ia32_pternlogd512_mask:
5370   case X86::BI__builtin_ia32_pternlogd512_maskz:
5371   case X86::BI__builtin_ia32_pternlogq512_mask:
5372   case X86::BI__builtin_ia32_pternlogq512_maskz:
5373   case X86::BI__builtin_ia32_pternlogd128_mask:
5374   case X86::BI__builtin_ia32_pternlogd128_maskz:
5375   case X86::BI__builtin_ia32_pternlogd256_mask:
5376   case X86::BI__builtin_ia32_pternlogd256_maskz:
5377   case X86::BI__builtin_ia32_pternlogq128_mask:
5378   case X86::BI__builtin_ia32_pternlogq128_maskz:
5379   case X86::BI__builtin_ia32_pternlogq256_mask:
5380   case X86::BI__builtin_ia32_pternlogq256_maskz:
5381     i = 3; l = 0; u = 255;
5382     break;
5383   case X86::BI__builtin_ia32_gatherpfdpd:
5384   case X86::BI__builtin_ia32_gatherpfdps:
5385   case X86::BI__builtin_ia32_gatherpfqpd:
5386   case X86::BI__builtin_ia32_gatherpfqps:
5387   case X86::BI__builtin_ia32_scatterpfdpd:
5388   case X86::BI__builtin_ia32_scatterpfdps:
5389   case X86::BI__builtin_ia32_scatterpfqpd:
5390   case X86::BI__builtin_ia32_scatterpfqps:
5391     i = 4; l = 2; u = 3;
5392     break;
5393   case X86::BI__builtin_ia32_reducesd_mask:
5394   case X86::BI__builtin_ia32_reducess_mask:
5395   case X86::BI__builtin_ia32_rndscalesd_round_mask:
5396   case X86::BI__builtin_ia32_rndscaless_round_mask:
5397   case X86::BI__builtin_ia32_rndscalesh_round_mask:
5398   case X86::BI__builtin_ia32_reducesh_mask:
5399     i = 4; l = 0; u = 255;
5400     break;
5401   }
5402 
5403   // Note that we don't force a hard error on the range check here, allowing
5404   // template-generated or macro-generated dead code to potentially have out-of-
5405   // range values. These need to code generate, but don't need to necessarily
5406   // make any sense. We use a warning that defaults to an error.
5407   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
5408 }
5409 
5410 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
5411 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
5412 /// Returns true when the format fits the function and the FormatStringInfo has
5413 /// been populated.
5414 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
5415                                FormatStringInfo *FSI) {
5416   FSI->HasVAListArg = Format->getFirstArg() == 0;
5417   FSI->FormatIdx = Format->getFormatIdx() - 1;
5418   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
5419 
5420   // The way the format attribute works in GCC, the implicit this argument
5421   // of member functions is counted. However, it doesn't appear in our own
5422   // lists, so decrement format_idx in that case.
5423   if (IsCXXMember) {
5424     if(FSI->FormatIdx == 0)
5425       return false;
5426     --FSI->FormatIdx;
5427     if (FSI->FirstDataArg != 0)
5428       --FSI->FirstDataArg;
5429   }
5430   return true;
5431 }
5432 
5433 /// Checks if a the given expression evaluates to null.
5434 ///
5435 /// Returns true if the value evaluates to null.
5436 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
5437   // If the expression has non-null type, it doesn't evaluate to null.
5438   if (auto nullability
5439         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
5440     if (*nullability == NullabilityKind::NonNull)
5441       return false;
5442   }
5443 
5444   // As a special case, transparent unions initialized with zero are
5445   // considered null for the purposes of the nonnull attribute.
5446   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
5447     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
5448       if (const CompoundLiteralExpr *CLE =
5449           dyn_cast<CompoundLiteralExpr>(Expr))
5450         if (const InitListExpr *ILE =
5451             dyn_cast<InitListExpr>(CLE->getInitializer()))
5452           Expr = ILE->getInit(0);
5453   }
5454 
5455   bool Result;
5456   return (!Expr->isValueDependent() &&
5457           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
5458           !Result);
5459 }
5460 
5461 static void CheckNonNullArgument(Sema &S,
5462                                  const Expr *ArgExpr,
5463                                  SourceLocation CallSiteLoc) {
5464   if (CheckNonNullExpr(S, ArgExpr))
5465     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
5466                           S.PDiag(diag::warn_null_arg)
5467                               << ArgExpr->getSourceRange());
5468 }
5469 
5470 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
5471   FormatStringInfo FSI;
5472   if ((GetFormatStringType(Format) == FST_NSString) &&
5473       getFormatStringInfo(Format, false, &FSI)) {
5474     Idx = FSI.FormatIdx;
5475     return true;
5476   }
5477   return false;
5478 }
5479 
5480 /// Diagnose use of %s directive in an NSString which is being passed
5481 /// as formatting string to formatting method.
5482 static void
5483 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
5484                                         const NamedDecl *FDecl,
5485                                         Expr **Args,
5486                                         unsigned NumArgs) {
5487   unsigned Idx = 0;
5488   bool Format = false;
5489   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
5490   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
5491     Idx = 2;
5492     Format = true;
5493   }
5494   else
5495     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5496       if (S.GetFormatNSStringIdx(I, Idx)) {
5497         Format = true;
5498         break;
5499       }
5500     }
5501   if (!Format || NumArgs <= Idx)
5502     return;
5503   const Expr *FormatExpr = Args[Idx];
5504   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
5505     FormatExpr = CSCE->getSubExpr();
5506   const StringLiteral *FormatString;
5507   if (const ObjCStringLiteral *OSL =
5508       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
5509     FormatString = OSL->getString();
5510   else
5511     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
5512   if (!FormatString)
5513     return;
5514   if (S.FormatStringHasSArg(FormatString)) {
5515     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
5516       << "%s" << 1 << 1;
5517     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
5518       << FDecl->getDeclName();
5519   }
5520 }
5521 
5522 /// Determine whether the given type has a non-null nullability annotation.
5523 static bool isNonNullType(ASTContext &ctx, QualType type) {
5524   if (auto nullability = type->getNullability(ctx))
5525     return *nullability == NullabilityKind::NonNull;
5526 
5527   return false;
5528 }
5529 
5530 static void CheckNonNullArguments(Sema &S,
5531                                   const NamedDecl *FDecl,
5532                                   const FunctionProtoType *Proto,
5533                                   ArrayRef<const Expr *> Args,
5534                                   SourceLocation CallSiteLoc) {
5535   assert((FDecl || Proto) && "Need a function declaration or prototype");
5536 
5537   // Already checked by by constant evaluator.
5538   if (S.isConstantEvaluated())
5539     return;
5540   // Check the attributes attached to the method/function itself.
5541   llvm::SmallBitVector NonNullArgs;
5542   if (FDecl) {
5543     // Handle the nonnull attribute on the function/method declaration itself.
5544     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
5545       if (!NonNull->args_size()) {
5546         // Easy case: all pointer arguments are nonnull.
5547         for (const auto *Arg : Args)
5548           if (S.isValidPointerAttrType(Arg->getType()))
5549             CheckNonNullArgument(S, Arg, CallSiteLoc);
5550         return;
5551       }
5552 
5553       for (const ParamIdx &Idx : NonNull->args()) {
5554         unsigned IdxAST = Idx.getASTIndex();
5555         if (IdxAST >= Args.size())
5556           continue;
5557         if (NonNullArgs.empty())
5558           NonNullArgs.resize(Args.size());
5559         NonNullArgs.set(IdxAST);
5560       }
5561     }
5562   }
5563 
5564   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
5565     // Handle the nonnull attribute on the parameters of the
5566     // function/method.
5567     ArrayRef<ParmVarDecl*> parms;
5568     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
5569       parms = FD->parameters();
5570     else
5571       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
5572 
5573     unsigned ParamIndex = 0;
5574     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
5575          I != E; ++I, ++ParamIndex) {
5576       const ParmVarDecl *PVD = *I;
5577       if (PVD->hasAttr<NonNullAttr>() ||
5578           isNonNullType(S.Context, PVD->getType())) {
5579         if (NonNullArgs.empty())
5580           NonNullArgs.resize(Args.size());
5581 
5582         NonNullArgs.set(ParamIndex);
5583       }
5584     }
5585   } else {
5586     // If we have a non-function, non-method declaration but no
5587     // function prototype, try to dig out the function prototype.
5588     if (!Proto) {
5589       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
5590         QualType type = VD->getType().getNonReferenceType();
5591         if (auto pointerType = type->getAs<PointerType>())
5592           type = pointerType->getPointeeType();
5593         else if (auto blockType = type->getAs<BlockPointerType>())
5594           type = blockType->getPointeeType();
5595         // FIXME: data member pointers?
5596 
5597         // Dig out the function prototype, if there is one.
5598         Proto = type->getAs<FunctionProtoType>();
5599       }
5600     }
5601 
5602     // Fill in non-null argument information from the nullability
5603     // information on the parameter types (if we have them).
5604     if (Proto) {
5605       unsigned Index = 0;
5606       for (auto paramType : Proto->getParamTypes()) {
5607         if (isNonNullType(S.Context, paramType)) {
5608           if (NonNullArgs.empty())
5609             NonNullArgs.resize(Args.size());
5610 
5611           NonNullArgs.set(Index);
5612         }
5613 
5614         ++Index;
5615       }
5616     }
5617   }
5618 
5619   // Check for non-null arguments.
5620   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
5621        ArgIndex != ArgIndexEnd; ++ArgIndex) {
5622     if (NonNullArgs[ArgIndex])
5623       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
5624   }
5625 }
5626 
5627 /// Warn if a pointer or reference argument passed to a function points to an
5628 /// object that is less aligned than the parameter. This can happen when
5629 /// creating a typedef with a lower alignment than the original type and then
5630 /// calling functions defined in terms of the original type.
5631 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
5632                              StringRef ParamName, QualType ArgTy,
5633                              QualType ParamTy) {
5634 
5635   // If a function accepts a pointer or reference type
5636   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5637     return;
5638 
5639   // If the parameter is a pointer type, get the pointee type for the
5640   // argument too. If the parameter is a reference type, don't try to get
5641   // the pointee type for the argument.
5642   if (ParamTy->isPointerType())
5643     ArgTy = ArgTy->getPointeeType();
5644 
5645   // Remove reference or pointer
5646   ParamTy = ParamTy->getPointeeType();
5647 
5648   // Find expected alignment, and the actual alignment of the passed object.
5649   // getTypeAlignInChars requires complete types
5650   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5651       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5652       ArgTy->isUndeducedType())
5653     return;
5654 
5655   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5656   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5657 
5658   // If the argument is less aligned than the parameter, there is a
5659   // potential alignment issue.
5660   if (ArgAlign < ParamAlign)
5661     Diag(Loc, diag::warn_param_mismatched_alignment)
5662         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5663         << ParamName << (FDecl != nullptr) << FDecl;
5664 }
5665 
5666 /// Handles the checks for format strings, non-POD arguments to vararg
5667 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5668 /// attributes.
5669 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5670                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5671                      bool IsMemberFunction, SourceLocation Loc,
5672                      SourceRange Range, VariadicCallType CallType) {
5673   // FIXME: We should check as much as we can in the template definition.
5674   if (CurContext->isDependentContext())
5675     return;
5676 
5677   // Printf and scanf checking.
5678   llvm::SmallBitVector CheckedVarArgs;
5679   if (FDecl) {
5680     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5681       // Only create vector if there are format attributes.
5682       CheckedVarArgs.resize(Args.size());
5683 
5684       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5685                            CheckedVarArgs);
5686     }
5687   }
5688 
5689   // Refuse POD arguments that weren't caught by the format string
5690   // checks above.
5691   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5692   if (CallType != VariadicDoesNotApply &&
5693       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5694     unsigned NumParams = Proto ? Proto->getNumParams()
5695                        : FDecl && isa<FunctionDecl>(FDecl)
5696                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5697                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5698                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5699                        : 0;
5700 
5701     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5702       // Args[ArgIdx] can be null in malformed code.
5703       if (const Expr *Arg = Args[ArgIdx]) {
5704         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5705           checkVariadicArgument(Arg, CallType);
5706       }
5707     }
5708   }
5709 
5710   if (FDecl || Proto) {
5711     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5712 
5713     // Type safety checking.
5714     if (FDecl) {
5715       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5716         CheckArgumentWithTypeTag(I, Args, Loc);
5717     }
5718   }
5719 
5720   // Check that passed arguments match the alignment of original arguments.
5721   // Try to get the missing prototype from the declaration.
5722   if (!Proto && FDecl) {
5723     const auto *FT = FDecl->getFunctionType();
5724     if (isa_and_nonnull<FunctionProtoType>(FT))
5725       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5726   }
5727   if (Proto) {
5728     // For variadic functions, we may have more args than parameters.
5729     // For some K&R functions, we may have less args than parameters.
5730     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5731     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5732       // Args[ArgIdx] can be null in malformed code.
5733       if (const Expr *Arg = Args[ArgIdx]) {
5734         if (Arg->containsErrors())
5735           continue;
5736 
5737         QualType ParamTy = Proto->getParamType(ArgIdx);
5738         QualType ArgTy = Arg->getType();
5739         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5740                           ArgTy, ParamTy);
5741       }
5742     }
5743   }
5744 
5745   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5746     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5747     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5748     if (!Arg->isValueDependent()) {
5749       Expr::EvalResult Align;
5750       if (Arg->EvaluateAsInt(Align, Context)) {
5751         const llvm::APSInt &I = Align.Val.getInt();
5752         if (!I.isPowerOf2())
5753           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5754               << Arg->getSourceRange();
5755 
5756         if (I > Sema::MaximumAlignment)
5757           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5758               << Arg->getSourceRange() << Sema::MaximumAlignment;
5759       }
5760     }
5761   }
5762 
5763   if (FD)
5764     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5765 }
5766 
5767 /// CheckConstructorCall - Check a constructor call for correctness and safety
5768 /// properties not enforced by the C type system.
5769 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5770                                 ArrayRef<const Expr *> Args,
5771                                 const FunctionProtoType *Proto,
5772                                 SourceLocation Loc) {
5773   VariadicCallType CallType =
5774       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5775 
5776   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5777   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5778                     Context.getPointerType(Ctor->getThisObjectType()));
5779 
5780   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5781             Loc, SourceRange(), CallType);
5782 }
5783 
5784 /// CheckFunctionCall - Check a direct function call for various correctness
5785 /// and safety properties not strictly enforced by the C type system.
5786 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5787                              const FunctionProtoType *Proto) {
5788   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5789                               isa<CXXMethodDecl>(FDecl);
5790   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5791                           IsMemberOperatorCall;
5792   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5793                                                   TheCall->getCallee());
5794   Expr** Args = TheCall->getArgs();
5795   unsigned NumArgs = TheCall->getNumArgs();
5796 
5797   Expr *ImplicitThis = nullptr;
5798   if (IsMemberOperatorCall) {
5799     // If this is a call to a member operator, hide the first argument
5800     // from checkCall.
5801     // FIXME: Our choice of AST representation here is less than ideal.
5802     ImplicitThis = Args[0];
5803     ++Args;
5804     --NumArgs;
5805   } else if (IsMemberFunction)
5806     ImplicitThis =
5807         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5808 
5809   if (ImplicitThis) {
5810     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5811     // used.
5812     QualType ThisType = ImplicitThis->getType();
5813     if (!ThisType->isPointerType()) {
5814       assert(!ThisType->isReferenceType());
5815       ThisType = Context.getPointerType(ThisType);
5816     }
5817 
5818     QualType ThisTypeFromDecl =
5819         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5820 
5821     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5822                       ThisTypeFromDecl);
5823   }
5824 
5825   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5826             IsMemberFunction, TheCall->getRParenLoc(),
5827             TheCall->getCallee()->getSourceRange(), CallType);
5828 
5829   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5830   // None of the checks below are needed for functions that don't have
5831   // simple names (e.g., C++ conversion functions).
5832   if (!FnInfo)
5833     return false;
5834 
5835   // Enforce TCB except for builtin calls, which are always allowed.
5836   if (FDecl->getBuiltinID() == 0)
5837     CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
5838 
5839   CheckAbsoluteValueFunction(TheCall, FDecl);
5840   CheckMaxUnsignedZero(TheCall, FDecl);
5841 
5842   if (getLangOpts().ObjC)
5843     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5844 
5845   unsigned CMId = FDecl->getMemoryFunctionKind();
5846 
5847   // Handle memory setting and copying functions.
5848   switch (CMId) {
5849   case 0:
5850     return false;
5851   case Builtin::BIstrlcpy: // fallthrough
5852   case Builtin::BIstrlcat:
5853     CheckStrlcpycatArguments(TheCall, FnInfo);
5854     break;
5855   case Builtin::BIstrncat:
5856     CheckStrncatArguments(TheCall, FnInfo);
5857     break;
5858   case Builtin::BIfree:
5859     CheckFreeArguments(TheCall);
5860     break;
5861   default:
5862     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5863   }
5864 
5865   return false;
5866 }
5867 
5868 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5869                                ArrayRef<const Expr *> Args) {
5870   VariadicCallType CallType =
5871       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5872 
5873   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5874             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5875             CallType);
5876 
5877   CheckTCBEnforcement(lbrac, Method);
5878 
5879   return false;
5880 }
5881 
5882 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5883                             const FunctionProtoType *Proto) {
5884   QualType Ty;
5885   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5886     Ty = V->getType().getNonReferenceType();
5887   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5888     Ty = F->getType().getNonReferenceType();
5889   else
5890     return false;
5891 
5892   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5893       !Ty->isFunctionProtoType())
5894     return false;
5895 
5896   VariadicCallType CallType;
5897   if (!Proto || !Proto->isVariadic()) {
5898     CallType = VariadicDoesNotApply;
5899   } else if (Ty->isBlockPointerType()) {
5900     CallType = VariadicBlock;
5901   } else { // Ty->isFunctionPointerType()
5902     CallType = VariadicFunction;
5903   }
5904 
5905   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5906             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5907             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5908             TheCall->getCallee()->getSourceRange(), CallType);
5909 
5910   return false;
5911 }
5912 
5913 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5914 /// such as function pointers returned from functions.
5915 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5916   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5917                                                   TheCall->getCallee());
5918   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5919             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5920             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5921             TheCall->getCallee()->getSourceRange(), CallType);
5922 
5923   return false;
5924 }
5925 
5926 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5927   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5928     return false;
5929 
5930   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5931   switch (Op) {
5932   case AtomicExpr::AO__c11_atomic_init:
5933   case AtomicExpr::AO__opencl_atomic_init:
5934     llvm_unreachable("There is no ordering argument for an init");
5935 
5936   case AtomicExpr::AO__c11_atomic_load:
5937   case AtomicExpr::AO__opencl_atomic_load:
5938   case AtomicExpr::AO__hip_atomic_load:
5939   case AtomicExpr::AO__atomic_load_n:
5940   case AtomicExpr::AO__atomic_load:
5941     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5942            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5943 
5944   case AtomicExpr::AO__c11_atomic_store:
5945   case AtomicExpr::AO__opencl_atomic_store:
5946   case AtomicExpr::AO__hip_atomic_store:
5947   case AtomicExpr::AO__atomic_store:
5948   case AtomicExpr::AO__atomic_store_n:
5949     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5950            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5951            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5952 
5953   default:
5954     return true;
5955   }
5956 }
5957 
5958 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5959                                          AtomicExpr::AtomicOp Op) {
5960   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5961   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5962   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5963   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5964                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5965                          Op);
5966 }
5967 
5968 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5969                                  SourceLocation RParenLoc, MultiExprArg Args,
5970                                  AtomicExpr::AtomicOp Op,
5971                                  AtomicArgumentOrder ArgOrder) {
5972   // All the non-OpenCL operations take one of the following forms.
5973   // The OpenCL operations take the __c11 forms with one extra argument for
5974   // synchronization scope.
5975   enum {
5976     // C    __c11_atomic_init(A *, C)
5977     Init,
5978 
5979     // C    __c11_atomic_load(A *, int)
5980     Load,
5981 
5982     // void __atomic_load(A *, CP, int)
5983     LoadCopy,
5984 
5985     // void __atomic_store(A *, CP, int)
5986     Copy,
5987 
5988     // C    __c11_atomic_add(A *, M, int)
5989     Arithmetic,
5990 
5991     // C    __atomic_exchange_n(A *, CP, int)
5992     Xchg,
5993 
5994     // void __atomic_exchange(A *, C *, CP, int)
5995     GNUXchg,
5996 
5997     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5998     C11CmpXchg,
5999 
6000     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
6001     GNUCmpXchg
6002   } Form = Init;
6003 
6004   const unsigned NumForm = GNUCmpXchg + 1;
6005   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
6006   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
6007   // where:
6008   //   C is an appropriate type,
6009   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
6010   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
6011   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
6012   //   the int parameters are for orderings.
6013 
6014   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
6015       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
6016       "need to update code for modified forms");
6017   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
6018                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
6019                         AtomicExpr::AO__atomic_load,
6020                 "need to update code for modified C11 atomics");
6021   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
6022                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
6023   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
6024                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
6025   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
6026                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
6027                IsOpenCL;
6028   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
6029              Op == AtomicExpr::AO__atomic_store_n ||
6030              Op == AtomicExpr::AO__atomic_exchange_n ||
6031              Op == AtomicExpr::AO__atomic_compare_exchange_n;
6032   bool IsAddSub = false;
6033 
6034   switch (Op) {
6035   case AtomicExpr::AO__c11_atomic_init:
6036   case AtomicExpr::AO__opencl_atomic_init:
6037     Form = Init;
6038     break;
6039 
6040   case AtomicExpr::AO__c11_atomic_load:
6041   case AtomicExpr::AO__opencl_atomic_load:
6042   case AtomicExpr::AO__hip_atomic_load:
6043   case AtomicExpr::AO__atomic_load_n:
6044     Form = Load;
6045     break;
6046 
6047   case AtomicExpr::AO__atomic_load:
6048     Form = LoadCopy;
6049     break;
6050 
6051   case AtomicExpr::AO__c11_atomic_store:
6052   case AtomicExpr::AO__opencl_atomic_store:
6053   case AtomicExpr::AO__hip_atomic_store:
6054   case AtomicExpr::AO__atomic_store:
6055   case AtomicExpr::AO__atomic_store_n:
6056     Form = Copy;
6057     break;
6058   case AtomicExpr::AO__hip_atomic_fetch_add:
6059   case AtomicExpr::AO__hip_atomic_fetch_min:
6060   case AtomicExpr::AO__hip_atomic_fetch_max:
6061   case AtomicExpr::AO__c11_atomic_fetch_add:
6062   case AtomicExpr::AO__c11_atomic_fetch_sub:
6063   case AtomicExpr::AO__opencl_atomic_fetch_add:
6064   case AtomicExpr::AO__opencl_atomic_fetch_sub:
6065   case AtomicExpr::AO__atomic_fetch_add:
6066   case AtomicExpr::AO__atomic_fetch_sub:
6067   case AtomicExpr::AO__atomic_add_fetch:
6068   case AtomicExpr::AO__atomic_sub_fetch:
6069     IsAddSub = true;
6070     Form = Arithmetic;
6071     break;
6072   case AtomicExpr::AO__c11_atomic_fetch_and:
6073   case AtomicExpr::AO__c11_atomic_fetch_or:
6074   case AtomicExpr::AO__c11_atomic_fetch_xor:
6075   case AtomicExpr::AO__hip_atomic_fetch_and:
6076   case AtomicExpr::AO__hip_atomic_fetch_or:
6077   case AtomicExpr::AO__hip_atomic_fetch_xor:
6078   case AtomicExpr::AO__c11_atomic_fetch_nand:
6079   case AtomicExpr::AO__opencl_atomic_fetch_and:
6080   case AtomicExpr::AO__opencl_atomic_fetch_or:
6081   case AtomicExpr::AO__opencl_atomic_fetch_xor:
6082   case AtomicExpr::AO__atomic_fetch_and:
6083   case AtomicExpr::AO__atomic_fetch_or:
6084   case AtomicExpr::AO__atomic_fetch_xor:
6085   case AtomicExpr::AO__atomic_fetch_nand:
6086   case AtomicExpr::AO__atomic_and_fetch:
6087   case AtomicExpr::AO__atomic_or_fetch:
6088   case AtomicExpr::AO__atomic_xor_fetch:
6089   case AtomicExpr::AO__atomic_nand_fetch:
6090     Form = Arithmetic;
6091     break;
6092   case AtomicExpr::AO__c11_atomic_fetch_min:
6093   case AtomicExpr::AO__c11_atomic_fetch_max:
6094   case AtomicExpr::AO__opencl_atomic_fetch_min:
6095   case AtomicExpr::AO__opencl_atomic_fetch_max:
6096   case AtomicExpr::AO__atomic_min_fetch:
6097   case AtomicExpr::AO__atomic_max_fetch:
6098   case AtomicExpr::AO__atomic_fetch_min:
6099   case AtomicExpr::AO__atomic_fetch_max:
6100     Form = Arithmetic;
6101     break;
6102 
6103   case AtomicExpr::AO__c11_atomic_exchange:
6104   case AtomicExpr::AO__hip_atomic_exchange:
6105   case AtomicExpr::AO__opencl_atomic_exchange:
6106   case AtomicExpr::AO__atomic_exchange_n:
6107     Form = Xchg;
6108     break;
6109 
6110   case AtomicExpr::AO__atomic_exchange:
6111     Form = GNUXchg;
6112     break;
6113 
6114   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
6115   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
6116   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
6117   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
6118   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
6119   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
6120     Form = C11CmpXchg;
6121     break;
6122 
6123   case AtomicExpr::AO__atomic_compare_exchange:
6124   case AtomicExpr::AO__atomic_compare_exchange_n:
6125     Form = GNUCmpXchg;
6126     break;
6127   }
6128 
6129   unsigned AdjustedNumArgs = NumArgs[Form];
6130   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
6131     ++AdjustedNumArgs;
6132   // Check we have the right number of arguments.
6133   if (Args.size() < AdjustedNumArgs) {
6134     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
6135         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
6136         << ExprRange;
6137     return ExprError();
6138   } else if (Args.size() > AdjustedNumArgs) {
6139     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
6140          diag::err_typecheck_call_too_many_args)
6141         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
6142         << ExprRange;
6143     return ExprError();
6144   }
6145 
6146   // Inspect the first argument of the atomic operation.
6147   Expr *Ptr = Args[0];
6148   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
6149   if (ConvertedPtr.isInvalid())
6150     return ExprError();
6151 
6152   Ptr = ConvertedPtr.get();
6153   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
6154   if (!pointerType) {
6155     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
6156         << Ptr->getType() << Ptr->getSourceRange();
6157     return ExprError();
6158   }
6159 
6160   // For a __c11 builtin, this should be a pointer to an _Atomic type.
6161   QualType AtomTy = pointerType->getPointeeType(); // 'A'
6162   QualType ValType = AtomTy; // 'C'
6163   if (IsC11) {
6164     if (!AtomTy->isAtomicType()) {
6165       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
6166           << Ptr->getType() << Ptr->getSourceRange();
6167       return ExprError();
6168     }
6169     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
6170         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
6171       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
6172           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
6173           << Ptr->getSourceRange();
6174       return ExprError();
6175     }
6176     ValType = AtomTy->castAs<AtomicType>()->getValueType();
6177   } else if (Form != Load && Form != LoadCopy) {
6178     if (ValType.isConstQualified()) {
6179       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
6180           << Ptr->getType() << Ptr->getSourceRange();
6181       return ExprError();
6182     }
6183   }
6184 
6185   // For an arithmetic operation, the implied arithmetic must be well-formed.
6186   if (Form == Arithmetic) {
6187     // GCC does not enforce these rules for GNU atomics, but we do to help catch
6188     // trivial type errors.
6189     auto IsAllowedValueType = [&](QualType ValType) {
6190       if (ValType->isIntegerType())
6191         return true;
6192       if (ValType->isPointerType())
6193         return true;
6194       if (!ValType->isFloatingType())
6195         return false;
6196       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
6197       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
6198           &Context.getTargetInfo().getLongDoubleFormat() ==
6199               &llvm::APFloat::x87DoubleExtended())
6200         return false;
6201       return true;
6202     };
6203     if (IsAddSub && !IsAllowedValueType(ValType)) {
6204       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
6205           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
6206       return ExprError();
6207     }
6208     if (!IsAddSub && !ValType->isIntegerType()) {
6209       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
6210           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
6211       return ExprError();
6212     }
6213     if (IsC11 && ValType->isPointerType() &&
6214         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
6215                             diag::err_incomplete_type)) {
6216       return ExprError();
6217     }
6218   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
6219     // For __atomic_*_n operations, the value type must be a scalar integral or
6220     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
6221     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
6222         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
6223     return ExprError();
6224   }
6225 
6226   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
6227       !AtomTy->isScalarType()) {
6228     // For GNU atomics, require a trivially-copyable type. This is not part of
6229     // the GNU atomics specification but we enforce it for consistency with
6230     // other atomics which generally all require a trivially-copyable type. This
6231     // is because atomics just copy bits.
6232     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
6233         << Ptr->getType() << Ptr->getSourceRange();
6234     return ExprError();
6235   }
6236 
6237   switch (ValType.getObjCLifetime()) {
6238   case Qualifiers::OCL_None:
6239   case Qualifiers::OCL_ExplicitNone:
6240     // okay
6241     break;
6242 
6243   case Qualifiers::OCL_Weak:
6244   case Qualifiers::OCL_Strong:
6245   case Qualifiers::OCL_Autoreleasing:
6246     // FIXME: Can this happen? By this point, ValType should be known
6247     // to be trivially copyable.
6248     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
6249         << ValType << Ptr->getSourceRange();
6250     return ExprError();
6251   }
6252 
6253   // All atomic operations have an overload which takes a pointer to a volatile
6254   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
6255   // into the result or the other operands. Similarly atomic_load takes a
6256   // pointer to a const 'A'.
6257   ValType.removeLocalVolatile();
6258   ValType.removeLocalConst();
6259   QualType ResultType = ValType;
6260   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
6261       Form == Init)
6262     ResultType = Context.VoidTy;
6263   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
6264     ResultType = Context.BoolTy;
6265 
6266   // The type of a parameter passed 'by value'. In the GNU atomics, such
6267   // arguments are actually passed as pointers.
6268   QualType ByValType = ValType; // 'CP'
6269   bool IsPassedByAddress = false;
6270   if (!IsC11 && !IsHIP && !IsN) {
6271     ByValType = Ptr->getType();
6272     IsPassedByAddress = true;
6273   }
6274 
6275   SmallVector<Expr *, 5> APIOrderedArgs;
6276   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
6277     APIOrderedArgs.push_back(Args[0]);
6278     switch (Form) {
6279     case Init:
6280     case Load:
6281       APIOrderedArgs.push_back(Args[1]); // Val1/Order
6282       break;
6283     case LoadCopy:
6284     case Copy:
6285     case Arithmetic:
6286     case Xchg:
6287       APIOrderedArgs.push_back(Args[2]); // Val1
6288       APIOrderedArgs.push_back(Args[1]); // Order
6289       break;
6290     case GNUXchg:
6291       APIOrderedArgs.push_back(Args[2]); // Val1
6292       APIOrderedArgs.push_back(Args[3]); // Val2
6293       APIOrderedArgs.push_back(Args[1]); // Order
6294       break;
6295     case C11CmpXchg:
6296       APIOrderedArgs.push_back(Args[2]); // Val1
6297       APIOrderedArgs.push_back(Args[4]); // Val2
6298       APIOrderedArgs.push_back(Args[1]); // Order
6299       APIOrderedArgs.push_back(Args[3]); // OrderFail
6300       break;
6301     case GNUCmpXchg:
6302       APIOrderedArgs.push_back(Args[2]); // Val1
6303       APIOrderedArgs.push_back(Args[4]); // Val2
6304       APIOrderedArgs.push_back(Args[5]); // Weak
6305       APIOrderedArgs.push_back(Args[1]); // Order
6306       APIOrderedArgs.push_back(Args[3]); // OrderFail
6307       break;
6308     }
6309   } else
6310     APIOrderedArgs.append(Args.begin(), Args.end());
6311 
6312   // The first argument's non-CV pointer type is used to deduce the type of
6313   // subsequent arguments, except for:
6314   //  - weak flag (always converted to bool)
6315   //  - memory order (always converted to int)
6316   //  - scope  (always converted to int)
6317   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
6318     QualType Ty;
6319     if (i < NumVals[Form] + 1) {
6320       switch (i) {
6321       case 0:
6322         // The first argument is always a pointer. It has a fixed type.
6323         // It is always dereferenced, a nullptr is undefined.
6324         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
6325         // Nothing else to do: we already know all we want about this pointer.
6326         continue;
6327       case 1:
6328         // The second argument is the non-atomic operand. For arithmetic, this
6329         // is always passed by value, and for a compare_exchange it is always
6330         // passed by address. For the rest, GNU uses by-address and C11 uses
6331         // by-value.
6332         assert(Form != Load);
6333         if (Form == Arithmetic && ValType->isPointerType())
6334           Ty = Context.getPointerDiffType();
6335         else if (Form == Init || Form == Arithmetic)
6336           Ty = ValType;
6337         else if (Form == Copy || Form == Xchg) {
6338           if (IsPassedByAddress) {
6339             // The value pointer is always dereferenced, a nullptr is undefined.
6340             CheckNonNullArgument(*this, APIOrderedArgs[i],
6341                                  ExprRange.getBegin());
6342           }
6343           Ty = ByValType;
6344         } else {
6345           Expr *ValArg = APIOrderedArgs[i];
6346           // The value pointer is always dereferenced, a nullptr is undefined.
6347           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
6348           LangAS AS = LangAS::Default;
6349           // Keep address space of non-atomic pointer type.
6350           if (const PointerType *PtrTy =
6351                   ValArg->getType()->getAs<PointerType>()) {
6352             AS = PtrTy->getPointeeType().getAddressSpace();
6353           }
6354           Ty = Context.getPointerType(
6355               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
6356         }
6357         break;
6358       case 2:
6359         // The third argument to compare_exchange / GNU exchange is the desired
6360         // value, either by-value (for the C11 and *_n variant) or as a pointer.
6361         if (IsPassedByAddress)
6362           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
6363         Ty = ByValType;
6364         break;
6365       case 3:
6366         // The fourth argument to GNU compare_exchange is a 'weak' flag.
6367         Ty = Context.BoolTy;
6368         break;
6369       }
6370     } else {
6371       // The order(s) and scope are always converted to int.
6372       Ty = Context.IntTy;
6373     }
6374 
6375     InitializedEntity Entity =
6376         InitializedEntity::InitializeParameter(Context, Ty, false);
6377     ExprResult Arg = APIOrderedArgs[i];
6378     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6379     if (Arg.isInvalid())
6380       return true;
6381     APIOrderedArgs[i] = Arg.get();
6382   }
6383 
6384   // Permute the arguments into a 'consistent' order.
6385   SmallVector<Expr*, 5> SubExprs;
6386   SubExprs.push_back(Ptr);
6387   switch (Form) {
6388   case Init:
6389     // Note, AtomicExpr::getVal1() has a special case for this atomic.
6390     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6391     break;
6392   case Load:
6393     SubExprs.push_back(APIOrderedArgs[1]); // Order
6394     break;
6395   case LoadCopy:
6396   case Copy:
6397   case Arithmetic:
6398   case Xchg:
6399     SubExprs.push_back(APIOrderedArgs[2]); // Order
6400     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6401     break;
6402   case GNUXchg:
6403     // Note, AtomicExpr::getVal2() has a special case for this atomic.
6404     SubExprs.push_back(APIOrderedArgs[3]); // Order
6405     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6406     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6407     break;
6408   case C11CmpXchg:
6409     SubExprs.push_back(APIOrderedArgs[3]); // Order
6410     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6411     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
6412     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6413     break;
6414   case GNUCmpXchg:
6415     SubExprs.push_back(APIOrderedArgs[4]); // Order
6416     SubExprs.push_back(APIOrderedArgs[1]); // Val1
6417     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
6418     SubExprs.push_back(APIOrderedArgs[2]); // Val2
6419     SubExprs.push_back(APIOrderedArgs[3]); // Weak
6420     break;
6421   }
6422 
6423   if (SubExprs.size() >= 2 && Form != Init) {
6424     if (Optional<llvm::APSInt> Result =
6425             SubExprs[1]->getIntegerConstantExpr(Context))
6426       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
6427         Diag(SubExprs[1]->getBeginLoc(),
6428              diag::warn_atomic_op_has_invalid_memory_order)
6429             << SubExprs[1]->getSourceRange();
6430   }
6431 
6432   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
6433     auto *Scope = Args[Args.size() - 1];
6434     if (Optional<llvm::APSInt> Result =
6435             Scope->getIntegerConstantExpr(Context)) {
6436       if (!ScopeModel->isValid(Result->getZExtValue()))
6437         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
6438             << Scope->getSourceRange();
6439     }
6440     SubExprs.push_back(Scope);
6441   }
6442 
6443   AtomicExpr *AE = new (Context)
6444       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
6445 
6446   if ((Op == AtomicExpr::AO__c11_atomic_load ||
6447        Op == AtomicExpr::AO__c11_atomic_store ||
6448        Op == AtomicExpr::AO__opencl_atomic_load ||
6449        Op == AtomicExpr::AO__hip_atomic_load ||
6450        Op == AtomicExpr::AO__opencl_atomic_store ||
6451        Op == AtomicExpr::AO__hip_atomic_store) &&
6452       Context.AtomicUsesUnsupportedLibcall(AE))
6453     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
6454         << ((Op == AtomicExpr::AO__c11_atomic_load ||
6455              Op == AtomicExpr::AO__opencl_atomic_load ||
6456              Op == AtomicExpr::AO__hip_atomic_load)
6457                 ? 0
6458                 : 1);
6459 
6460   if (ValType->isBitIntType()) {
6461     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
6462     return ExprError();
6463   }
6464 
6465   return AE;
6466 }
6467 
6468 /// checkBuiltinArgument - Given a call to a builtin function, perform
6469 /// normal type-checking on the given argument, updating the call in
6470 /// place.  This is useful when a builtin function requires custom
6471 /// type-checking for some of its arguments but not necessarily all of
6472 /// them.
6473 ///
6474 /// Returns true on error.
6475 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
6476   FunctionDecl *Fn = E->getDirectCallee();
6477   assert(Fn && "builtin call without direct callee!");
6478 
6479   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
6480   InitializedEntity Entity =
6481     InitializedEntity::InitializeParameter(S.Context, Param);
6482 
6483   ExprResult Arg = E->getArg(ArgIndex);
6484   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
6485   if (Arg.isInvalid())
6486     return true;
6487 
6488   E->setArg(ArgIndex, Arg.get());
6489   return false;
6490 }
6491 
6492 /// We have a call to a function like __sync_fetch_and_add, which is an
6493 /// overloaded function based on the pointer type of its first argument.
6494 /// The main BuildCallExpr routines have already promoted the types of
6495 /// arguments because all of these calls are prototyped as void(...).
6496 ///
6497 /// This function goes through and does final semantic checking for these
6498 /// builtins, as well as generating any warnings.
6499 ExprResult
6500 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
6501   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
6502   Expr *Callee = TheCall->getCallee();
6503   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
6504   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6505 
6506   // Ensure that we have at least one argument to do type inference from.
6507   if (TheCall->getNumArgs() < 1) {
6508     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6509         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
6510     return ExprError();
6511   }
6512 
6513   // Inspect the first argument of the atomic builtin.  This should always be
6514   // a pointer type, whose element is an integral scalar or pointer type.
6515   // Because it is a pointer type, we don't have to worry about any implicit
6516   // casts here.
6517   // FIXME: We don't allow floating point scalars as input.
6518   Expr *FirstArg = TheCall->getArg(0);
6519   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
6520   if (FirstArgResult.isInvalid())
6521     return ExprError();
6522   FirstArg = FirstArgResult.get();
6523   TheCall->setArg(0, FirstArg);
6524 
6525   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
6526   if (!pointerType) {
6527     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
6528         << FirstArg->getType() << FirstArg->getSourceRange();
6529     return ExprError();
6530   }
6531 
6532   QualType ValType = pointerType->getPointeeType();
6533   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6534       !ValType->isBlockPointerType()) {
6535     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
6536         << FirstArg->getType() << FirstArg->getSourceRange();
6537     return ExprError();
6538   }
6539 
6540   if (ValType.isConstQualified()) {
6541     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
6542         << FirstArg->getType() << FirstArg->getSourceRange();
6543     return ExprError();
6544   }
6545 
6546   switch (ValType.getObjCLifetime()) {
6547   case Qualifiers::OCL_None:
6548   case Qualifiers::OCL_ExplicitNone:
6549     // okay
6550     break;
6551 
6552   case Qualifiers::OCL_Weak:
6553   case Qualifiers::OCL_Strong:
6554   case Qualifiers::OCL_Autoreleasing:
6555     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
6556         << ValType << FirstArg->getSourceRange();
6557     return ExprError();
6558   }
6559 
6560   // Strip any qualifiers off ValType.
6561   ValType = ValType.getUnqualifiedType();
6562 
6563   // The majority of builtins return a value, but a few have special return
6564   // types, so allow them to override appropriately below.
6565   QualType ResultType = ValType;
6566 
6567   // We need to figure out which concrete builtin this maps onto.  For example,
6568   // __sync_fetch_and_add with a 2 byte object turns into
6569   // __sync_fetch_and_add_2.
6570 #define BUILTIN_ROW(x) \
6571   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
6572     Builtin::BI##x##_8, Builtin::BI##x##_16 }
6573 
6574   static const unsigned BuiltinIndices[][5] = {
6575     BUILTIN_ROW(__sync_fetch_and_add),
6576     BUILTIN_ROW(__sync_fetch_and_sub),
6577     BUILTIN_ROW(__sync_fetch_and_or),
6578     BUILTIN_ROW(__sync_fetch_and_and),
6579     BUILTIN_ROW(__sync_fetch_and_xor),
6580     BUILTIN_ROW(__sync_fetch_and_nand),
6581 
6582     BUILTIN_ROW(__sync_add_and_fetch),
6583     BUILTIN_ROW(__sync_sub_and_fetch),
6584     BUILTIN_ROW(__sync_and_and_fetch),
6585     BUILTIN_ROW(__sync_or_and_fetch),
6586     BUILTIN_ROW(__sync_xor_and_fetch),
6587     BUILTIN_ROW(__sync_nand_and_fetch),
6588 
6589     BUILTIN_ROW(__sync_val_compare_and_swap),
6590     BUILTIN_ROW(__sync_bool_compare_and_swap),
6591     BUILTIN_ROW(__sync_lock_test_and_set),
6592     BUILTIN_ROW(__sync_lock_release),
6593     BUILTIN_ROW(__sync_swap)
6594   };
6595 #undef BUILTIN_ROW
6596 
6597   // Determine the index of the size.
6598   unsigned SizeIndex;
6599   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6600   case 1: SizeIndex = 0; break;
6601   case 2: SizeIndex = 1; break;
6602   case 4: SizeIndex = 2; break;
6603   case 8: SizeIndex = 3; break;
6604   case 16: SizeIndex = 4; break;
6605   default:
6606     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6607         << FirstArg->getType() << FirstArg->getSourceRange();
6608     return ExprError();
6609   }
6610 
6611   // Each of these builtins has one pointer argument, followed by some number of
6612   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6613   // that we ignore.  Find out which row of BuiltinIndices to read from as well
6614   // as the number of fixed args.
6615   unsigned BuiltinID = FDecl->getBuiltinID();
6616   unsigned BuiltinIndex, NumFixed = 1;
6617   bool WarnAboutSemanticsChange = false;
6618   switch (BuiltinID) {
6619   default: llvm_unreachable("Unknown overloaded atomic builtin!");
6620   case Builtin::BI__sync_fetch_and_add:
6621   case Builtin::BI__sync_fetch_and_add_1:
6622   case Builtin::BI__sync_fetch_and_add_2:
6623   case Builtin::BI__sync_fetch_and_add_4:
6624   case Builtin::BI__sync_fetch_and_add_8:
6625   case Builtin::BI__sync_fetch_and_add_16:
6626     BuiltinIndex = 0;
6627     break;
6628 
6629   case Builtin::BI__sync_fetch_and_sub:
6630   case Builtin::BI__sync_fetch_and_sub_1:
6631   case Builtin::BI__sync_fetch_and_sub_2:
6632   case Builtin::BI__sync_fetch_and_sub_4:
6633   case Builtin::BI__sync_fetch_and_sub_8:
6634   case Builtin::BI__sync_fetch_and_sub_16:
6635     BuiltinIndex = 1;
6636     break;
6637 
6638   case Builtin::BI__sync_fetch_and_or:
6639   case Builtin::BI__sync_fetch_and_or_1:
6640   case Builtin::BI__sync_fetch_and_or_2:
6641   case Builtin::BI__sync_fetch_and_or_4:
6642   case Builtin::BI__sync_fetch_and_or_8:
6643   case Builtin::BI__sync_fetch_and_or_16:
6644     BuiltinIndex = 2;
6645     break;
6646 
6647   case Builtin::BI__sync_fetch_and_and:
6648   case Builtin::BI__sync_fetch_and_and_1:
6649   case Builtin::BI__sync_fetch_and_and_2:
6650   case Builtin::BI__sync_fetch_and_and_4:
6651   case Builtin::BI__sync_fetch_and_and_8:
6652   case Builtin::BI__sync_fetch_and_and_16:
6653     BuiltinIndex = 3;
6654     break;
6655 
6656   case Builtin::BI__sync_fetch_and_xor:
6657   case Builtin::BI__sync_fetch_and_xor_1:
6658   case Builtin::BI__sync_fetch_and_xor_2:
6659   case Builtin::BI__sync_fetch_and_xor_4:
6660   case Builtin::BI__sync_fetch_and_xor_8:
6661   case Builtin::BI__sync_fetch_and_xor_16:
6662     BuiltinIndex = 4;
6663     break;
6664 
6665   case Builtin::BI__sync_fetch_and_nand:
6666   case Builtin::BI__sync_fetch_and_nand_1:
6667   case Builtin::BI__sync_fetch_and_nand_2:
6668   case Builtin::BI__sync_fetch_and_nand_4:
6669   case Builtin::BI__sync_fetch_and_nand_8:
6670   case Builtin::BI__sync_fetch_and_nand_16:
6671     BuiltinIndex = 5;
6672     WarnAboutSemanticsChange = true;
6673     break;
6674 
6675   case Builtin::BI__sync_add_and_fetch:
6676   case Builtin::BI__sync_add_and_fetch_1:
6677   case Builtin::BI__sync_add_and_fetch_2:
6678   case Builtin::BI__sync_add_and_fetch_4:
6679   case Builtin::BI__sync_add_and_fetch_8:
6680   case Builtin::BI__sync_add_and_fetch_16:
6681     BuiltinIndex = 6;
6682     break;
6683 
6684   case Builtin::BI__sync_sub_and_fetch:
6685   case Builtin::BI__sync_sub_and_fetch_1:
6686   case Builtin::BI__sync_sub_and_fetch_2:
6687   case Builtin::BI__sync_sub_and_fetch_4:
6688   case Builtin::BI__sync_sub_and_fetch_8:
6689   case Builtin::BI__sync_sub_and_fetch_16:
6690     BuiltinIndex = 7;
6691     break;
6692 
6693   case Builtin::BI__sync_and_and_fetch:
6694   case Builtin::BI__sync_and_and_fetch_1:
6695   case Builtin::BI__sync_and_and_fetch_2:
6696   case Builtin::BI__sync_and_and_fetch_4:
6697   case Builtin::BI__sync_and_and_fetch_8:
6698   case Builtin::BI__sync_and_and_fetch_16:
6699     BuiltinIndex = 8;
6700     break;
6701 
6702   case Builtin::BI__sync_or_and_fetch:
6703   case Builtin::BI__sync_or_and_fetch_1:
6704   case Builtin::BI__sync_or_and_fetch_2:
6705   case Builtin::BI__sync_or_and_fetch_4:
6706   case Builtin::BI__sync_or_and_fetch_8:
6707   case Builtin::BI__sync_or_and_fetch_16:
6708     BuiltinIndex = 9;
6709     break;
6710 
6711   case Builtin::BI__sync_xor_and_fetch:
6712   case Builtin::BI__sync_xor_and_fetch_1:
6713   case Builtin::BI__sync_xor_and_fetch_2:
6714   case Builtin::BI__sync_xor_and_fetch_4:
6715   case Builtin::BI__sync_xor_and_fetch_8:
6716   case Builtin::BI__sync_xor_and_fetch_16:
6717     BuiltinIndex = 10;
6718     break;
6719 
6720   case Builtin::BI__sync_nand_and_fetch:
6721   case Builtin::BI__sync_nand_and_fetch_1:
6722   case Builtin::BI__sync_nand_and_fetch_2:
6723   case Builtin::BI__sync_nand_and_fetch_4:
6724   case Builtin::BI__sync_nand_and_fetch_8:
6725   case Builtin::BI__sync_nand_and_fetch_16:
6726     BuiltinIndex = 11;
6727     WarnAboutSemanticsChange = true;
6728     break;
6729 
6730   case Builtin::BI__sync_val_compare_and_swap:
6731   case Builtin::BI__sync_val_compare_and_swap_1:
6732   case Builtin::BI__sync_val_compare_and_swap_2:
6733   case Builtin::BI__sync_val_compare_and_swap_4:
6734   case Builtin::BI__sync_val_compare_and_swap_8:
6735   case Builtin::BI__sync_val_compare_and_swap_16:
6736     BuiltinIndex = 12;
6737     NumFixed = 2;
6738     break;
6739 
6740   case Builtin::BI__sync_bool_compare_and_swap:
6741   case Builtin::BI__sync_bool_compare_and_swap_1:
6742   case Builtin::BI__sync_bool_compare_and_swap_2:
6743   case Builtin::BI__sync_bool_compare_and_swap_4:
6744   case Builtin::BI__sync_bool_compare_and_swap_8:
6745   case Builtin::BI__sync_bool_compare_and_swap_16:
6746     BuiltinIndex = 13;
6747     NumFixed = 2;
6748     ResultType = Context.BoolTy;
6749     break;
6750 
6751   case Builtin::BI__sync_lock_test_and_set:
6752   case Builtin::BI__sync_lock_test_and_set_1:
6753   case Builtin::BI__sync_lock_test_and_set_2:
6754   case Builtin::BI__sync_lock_test_and_set_4:
6755   case Builtin::BI__sync_lock_test_and_set_8:
6756   case Builtin::BI__sync_lock_test_and_set_16:
6757     BuiltinIndex = 14;
6758     break;
6759 
6760   case Builtin::BI__sync_lock_release:
6761   case Builtin::BI__sync_lock_release_1:
6762   case Builtin::BI__sync_lock_release_2:
6763   case Builtin::BI__sync_lock_release_4:
6764   case Builtin::BI__sync_lock_release_8:
6765   case Builtin::BI__sync_lock_release_16:
6766     BuiltinIndex = 15;
6767     NumFixed = 0;
6768     ResultType = Context.VoidTy;
6769     break;
6770 
6771   case Builtin::BI__sync_swap:
6772   case Builtin::BI__sync_swap_1:
6773   case Builtin::BI__sync_swap_2:
6774   case Builtin::BI__sync_swap_4:
6775   case Builtin::BI__sync_swap_8:
6776   case Builtin::BI__sync_swap_16:
6777     BuiltinIndex = 16;
6778     break;
6779   }
6780 
6781   // Now that we know how many fixed arguments we expect, first check that we
6782   // have at least that many.
6783   if (TheCall->getNumArgs() < 1+NumFixed) {
6784     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6785         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6786         << Callee->getSourceRange();
6787     return ExprError();
6788   }
6789 
6790   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6791       << Callee->getSourceRange();
6792 
6793   if (WarnAboutSemanticsChange) {
6794     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6795         << Callee->getSourceRange();
6796   }
6797 
6798   // Get the decl for the concrete builtin from this, we can tell what the
6799   // concrete integer type we should convert to is.
6800   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6801   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6802   FunctionDecl *NewBuiltinDecl;
6803   if (NewBuiltinID == BuiltinID)
6804     NewBuiltinDecl = FDecl;
6805   else {
6806     // Perform builtin lookup to avoid redeclaring it.
6807     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6808     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6809     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6810     assert(Res.getFoundDecl());
6811     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6812     if (!NewBuiltinDecl)
6813       return ExprError();
6814   }
6815 
6816   // The first argument --- the pointer --- has a fixed type; we
6817   // deduce the types of the rest of the arguments accordingly.  Walk
6818   // the remaining arguments, converting them to the deduced value type.
6819   for (unsigned i = 0; i != NumFixed; ++i) {
6820     ExprResult Arg = TheCall->getArg(i+1);
6821 
6822     // GCC does an implicit conversion to the pointer or integer ValType.  This
6823     // can fail in some cases (1i -> int**), check for this error case now.
6824     // Initialize the argument.
6825     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6826                                                    ValType, /*consume*/ false);
6827     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6828     if (Arg.isInvalid())
6829       return ExprError();
6830 
6831     // Okay, we have something that *can* be converted to the right type.  Check
6832     // to see if there is a potentially weird extension going on here.  This can
6833     // happen when you do an atomic operation on something like an char* and
6834     // pass in 42.  The 42 gets converted to char.  This is even more strange
6835     // for things like 45.123 -> char, etc.
6836     // FIXME: Do this check.
6837     TheCall->setArg(i+1, Arg.get());
6838   }
6839 
6840   // Create a new DeclRefExpr to refer to the new decl.
6841   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6842       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6843       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6844       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6845 
6846   // Set the callee in the CallExpr.
6847   // FIXME: This loses syntactic information.
6848   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6849   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6850                                               CK_BuiltinFnToFnPtr);
6851   TheCall->setCallee(PromotedCall.get());
6852 
6853   // Change the result type of the call to match the original value type. This
6854   // is arbitrary, but the codegen for these builtins ins design to handle it
6855   // gracefully.
6856   TheCall->setType(ResultType);
6857 
6858   // Prohibit problematic uses of bit-precise integer types with atomic
6859   // builtins. The arguments would have already been converted to the first
6860   // argument's type, so only need to check the first argument.
6861   const auto *BitIntValType = ValType->getAs<BitIntType>();
6862   if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6863     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6864     return ExprError();
6865   }
6866 
6867   return TheCallResult;
6868 }
6869 
6870 /// SemaBuiltinNontemporalOverloaded - We have a call to
6871 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6872 /// overloaded function based on the pointer type of its last argument.
6873 ///
6874 /// This function goes through and does final semantic checking for these
6875 /// builtins.
6876 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6877   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6878   DeclRefExpr *DRE =
6879       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6880   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6881   unsigned BuiltinID = FDecl->getBuiltinID();
6882   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6883           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6884          "Unexpected nontemporal load/store builtin!");
6885   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6886   unsigned numArgs = isStore ? 2 : 1;
6887 
6888   // Ensure that we have the proper number of arguments.
6889   if (checkArgCount(*this, TheCall, numArgs))
6890     return ExprError();
6891 
6892   // Inspect the last argument of the nontemporal builtin.  This should always
6893   // be a pointer type, from which we imply the type of the memory access.
6894   // Because it is a pointer type, we don't have to worry about any implicit
6895   // casts here.
6896   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6897   ExprResult PointerArgResult =
6898       DefaultFunctionArrayLvalueConversion(PointerArg);
6899 
6900   if (PointerArgResult.isInvalid())
6901     return ExprError();
6902   PointerArg = PointerArgResult.get();
6903   TheCall->setArg(numArgs - 1, PointerArg);
6904 
6905   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6906   if (!pointerType) {
6907     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6908         << PointerArg->getType() << PointerArg->getSourceRange();
6909     return ExprError();
6910   }
6911 
6912   QualType ValType = pointerType->getPointeeType();
6913 
6914   // Strip any qualifiers off ValType.
6915   ValType = ValType.getUnqualifiedType();
6916   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6917       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6918       !ValType->isVectorType()) {
6919     Diag(DRE->getBeginLoc(),
6920          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6921         << PointerArg->getType() << PointerArg->getSourceRange();
6922     return ExprError();
6923   }
6924 
6925   if (!isStore) {
6926     TheCall->setType(ValType);
6927     return TheCallResult;
6928   }
6929 
6930   ExprResult ValArg = TheCall->getArg(0);
6931   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6932       Context, ValType, /*consume*/ false);
6933   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6934   if (ValArg.isInvalid())
6935     return ExprError();
6936 
6937   TheCall->setArg(0, ValArg.get());
6938   TheCall->setType(Context.VoidTy);
6939   return TheCallResult;
6940 }
6941 
6942 /// CheckObjCString - Checks that the argument to the builtin
6943 /// CFString constructor is correct
6944 /// Note: It might also make sense to do the UTF-16 conversion here (would
6945 /// simplify the backend).
6946 bool Sema::CheckObjCString(Expr *Arg) {
6947   Arg = Arg->IgnoreParenCasts();
6948   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6949 
6950   if (!Literal || !Literal->isAscii()) {
6951     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6952         << Arg->getSourceRange();
6953     return true;
6954   }
6955 
6956   if (Literal->containsNonAsciiOrNull()) {
6957     StringRef String = Literal->getString();
6958     unsigned NumBytes = String.size();
6959     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6960     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6961     llvm::UTF16 *ToPtr = &ToBuf[0];
6962 
6963     llvm::ConversionResult Result =
6964         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6965                                  ToPtr + NumBytes, llvm::strictConversion);
6966     // Check for conversion failure.
6967     if (Result != llvm::conversionOK)
6968       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6969           << Arg->getSourceRange();
6970   }
6971   return false;
6972 }
6973 
6974 /// CheckObjCString - Checks that the format string argument to the os_log()
6975 /// and os_trace() functions is correct, and converts it to const char *.
6976 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6977   Arg = Arg->IgnoreParenCasts();
6978   auto *Literal = dyn_cast<StringLiteral>(Arg);
6979   if (!Literal) {
6980     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6981       Literal = ObjcLiteral->getString();
6982     }
6983   }
6984 
6985   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6986     return ExprError(
6987         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6988         << Arg->getSourceRange());
6989   }
6990 
6991   ExprResult Result(Literal);
6992   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6993   InitializedEntity Entity =
6994       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6995   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6996   return Result;
6997 }
6998 
6999 /// Check that the user is calling the appropriate va_start builtin for the
7000 /// target and calling convention.
7001 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
7002   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
7003   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
7004   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
7005                     TT.getArch() == llvm::Triple::aarch64_32);
7006   bool IsWindows = TT.isOSWindows();
7007   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
7008   if (IsX64 || IsAArch64) {
7009     CallingConv CC = CC_C;
7010     if (const FunctionDecl *FD = S.getCurFunctionDecl())
7011       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
7012     if (IsMSVAStart) {
7013       // Don't allow this in System V ABI functions.
7014       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
7015         return S.Diag(Fn->getBeginLoc(),
7016                       diag::err_ms_va_start_used_in_sysv_function);
7017     } else {
7018       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
7019       // On x64 Windows, don't allow this in System V ABI functions.
7020       // (Yes, that means there's no corresponding way to support variadic
7021       // System V ABI functions on Windows.)
7022       if ((IsWindows && CC == CC_X86_64SysV) ||
7023           (!IsWindows && CC == CC_Win64))
7024         return S.Diag(Fn->getBeginLoc(),
7025                       diag::err_va_start_used_in_wrong_abi_function)
7026                << !IsWindows;
7027     }
7028     return false;
7029   }
7030 
7031   if (IsMSVAStart)
7032     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
7033   return false;
7034 }
7035 
7036 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
7037                                              ParmVarDecl **LastParam = nullptr) {
7038   // Determine whether the current function, block, or obj-c method is variadic
7039   // and get its parameter list.
7040   bool IsVariadic = false;
7041   ArrayRef<ParmVarDecl *> Params;
7042   DeclContext *Caller = S.CurContext;
7043   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
7044     IsVariadic = Block->isVariadic();
7045     Params = Block->parameters();
7046   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
7047     IsVariadic = FD->isVariadic();
7048     Params = FD->parameters();
7049   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
7050     IsVariadic = MD->isVariadic();
7051     // FIXME: This isn't correct for methods (results in bogus warning).
7052     Params = MD->parameters();
7053   } else if (isa<CapturedDecl>(Caller)) {
7054     // We don't support va_start in a CapturedDecl.
7055     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
7056     return true;
7057   } else {
7058     // This must be some other declcontext that parses exprs.
7059     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
7060     return true;
7061   }
7062 
7063   if (!IsVariadic) {
7064     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
7065     return true;
7066   }
7067 
7068   if (LastParam)
7069     *LastParam = Params.empty() ? nullptr : Params.back();
7070 
7071   return false;
7072 }
7073 
7074 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
7075 /// for validity.  Emit an error and return true on failure; return false
7076 /// on success.
7077 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
7078   Expr *Fn = TheCall->getCallee();
7079 
7080   if (checkVAStartABI(*this, BuiltinID, Fn))
7081     return true;
7082 
7083   if (checkArgCount(*this, TheCall, 2))
7084     return true;
7085 
7086   // Type-check the first argument normally.
7087   if (checkBuiltinArgument(*this, TheCall, 0))
7088     return true;
7089 
7090   // Check that the current function is variadic, and get its last parameter.
7091   ParmVarDecl *LastParam;
7092   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
7093     return true;
7094 
7095   // Verify that the second argument to the builtin is the last argument of the
7096   // current function or method.
7097   bool SecondArgIsLastNamedArgument = false;
7098   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
7099 
7100   // These are valid if SecondArgIsLastNamedArgument is false after the next
7101   // block.
7102   QualType Type;
7103   SourceLocation ParamLoc;
7104   bool IsCRegister = false;
7105 
7106   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
7107     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
7108       SecondArgIsLastNamedArgument = PV == LastParam;
7109 
7110       Type = PV->getType();
7111       ParamLoc = PV->getLocation();
7112       IsCRegister =
7113           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
7114     }
7115   }
7116 
7117   if (!SecondArgIsLastNamedArgument)
7118     Diag(TheCall->getArg(1)->getBeginLoc(),
7119          diag::warn_second_arg_of_va_start_not_last_named_param);
7120   else if (IsCRegister || Type->isReferenceType() ||
7121            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
7122              // Promotable integers are UB, but enumerations need a bit of
7123              // extra checking to see what their promotable type actually is.
7124              if (!Type->isPromotableIntegerType())
7125                return false;
7126              if (!Type->isEnumeralType())
7127                return true;
7128              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
7129              return !(ED &&
7130                       Context.typesAreCompatible(ED->getPromotionType(), Type));
7131            }()) {
7132     unsigned Reason = 0;
7133     if (Type->isReferenceType())  Reason = 1;
7134     else if (IsCRegister)         Reason = 2;
7135     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
7136     Diag(ParamLoc, diag::note_parameter_type) << Type;
7137   }
7138 
7139   TheCall->setType(Context.VoidTy);
7140   return false;
7141 }
7142 
7143 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
7144   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
7145     const LangOptions &LO = getLangOpts();
7146 
7147     if (LO.CPlusPlus)
7148       return Arg->getType()
7149                  .getCanonicalType()
7150                  .getTypePtr()
7151                  ->getPointeeType()
7152                  .withoutLocalFastQualifiers() == Context.CharTy;
7153 
7154     // In C, allow aliasing through `char *`, this is required for AArch64 at
7155     // least.
7156     return true;
7157   };
7158 
7159   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
7160   //                 const char *named_addr);
7161 
7162   Expr *Func = Call->getCallee();
7163 
7164   if (Call->getNumArgs() < 3)
7165     return Diag(Call->getEndLoc(),
7166                 diag::err_typecheck_call_too_few_args_at_least)
7167            << 0 /*function call*/ << 3 << Call->getNumArgs();
7168 
7169   // Type-check the first argument normally.
7170   if (checkBuiltinArgument(*this, Call, 0))
7171     return true;
7172 
7173   // Check that the current function is variadic.
7174   if (checkVAStartIsInVariadicFunction(*this, Func))
7175     return true;
7176 
7177   // __va_start on Windows does not validate the parameter qualifiers
7178 
7179   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
7180   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
7181 
7182   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
7183   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
7184 
7185   const QualType &ConstCharPtrTy =
7186       Context.getPointerType(Context.CharTy.withConst());
7187   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
7188     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7189         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
7190         << 0                                      /* qualifier difference */
7191         << 3                                      /* parameter mismatch */
7192         << 2 << Arg1->getType() << ConstCharPtrTy;
7193 
7194   const QualType SizeTy = Context.getSizeType();
7195   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
7196     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7197         << Arg2->getType() << SizeTy << 1 /* different class */
7198         << 0                              /* qualifier difference */
7199         << 3                              /* parameter mismatch */
7200         << 3 << Arg2->getType() << SizeTy;
7201 
7202   return false;
7203 }
7204 
7205 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
7206 /// friends.  This is declared to take (...), so we have to check everything.
7207 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
7208   if (checkArgCount(*this, TheCall, 2))
7209     return true;
7210 
7211   ExprResult OrigArg0 = TheCall->getArg(0);
7212   ExprResult OrigArg1 = TheCall->getArg(1);
7213 
7214   // Do standard promotions between the two arguments, returning their common
7215   // type.
7216   QualType Res = UsualArithmeticConversions(
7217       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
7218   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
7219     return true;
7220 
7221   // Make sure any conversions are pushed back into the call; this is
7222   // type safe since unordered compare builtins are declared as "_Bool
7223   // foo(...)".
7224   TheCall->setArg(0, OrigArg0.get());
7225   TheCall->setArg(1, OrigArg1.get());
7226 
7227   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
7228     return false;
7229 
7230   // If the common type isn't a real floating type, then the arguments were
7231   // invalid for this operation.
7232   if (Res.isNull() || !Res->isRealFloatingType())
7233     return Diag(OrigArg0.get()->getBeginLoc(),
7234                 diag::err_typecheck_call_invalid_ordered_compare)
7235            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
7236            << SourceRange(OrigArg0.get()->getBeginLoc(),
7237                           OrigArg1.get()->getEndLoc());
7238 
7239   return false;
7240 }
7241 
7242 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
7243 /// __builtin_isnan and friends.  This is declared to take (...), so we have
7244 /// to check everything. We expect the last argument to be a floating point
7245 /// value.
7246 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
7247   if (checkArgCount(*this, TheCall, NumArgs))
7248     return true;
7249 
7250   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
7251   // on all preceding parameters just being int.  Try all of those.
7252   for (unsigned i = 0; i < NumArgs - 1; ++i) {
7253     Expr *Arg = TheCall->getArg(i);
7254 
7255     if (Arg->isTypeDependent())
7256       return false;
7257 
7258     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
7259 
7260     if (Res.isInvalid())
7261       return true;
7262     TheCall->setArg(i, Res.get());
7263   }
7264 
7265   Expr *OrigArg = TheCall->getArg(NumArgs-1);
7266 
7267   if (OrigArg->isTypeDependent())
7268     return false;
7269 
7270   // Usual Unary Conversions will convert half to float, which we want for
7271   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
7272   // type how it is, but do normal L->Rvalue conversions.
7273   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
7274     OrigArg = UsualUnaryConversions(OrigArg).get();
7275   else
7276     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
7277   TheCall->setArg(NumArgs - 1, OrigArg);
7278 
7279   // This operation requires a non-_Complex floating-point number.
7280   if (!OrigArg->getType()->isRealFloatingType())
7281     return Diag(OrigArg->getBeginLoc(),
7282                 diag::err_typecheck_call_invalid_unary_fp)
7283            << OrigArg->getType() << OrigArg->getSourceRange();
7284 
7285   return false;
7286 }
7287 
7288 /// Perform semantic analysis for a call to __builtin_complex.
7289 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
7290   if (checkArgCount(*this, TheCall, 2))
7291     return true;
7292 
7293   bool Dependent = false;
7294   for (unsigned I = 0; I != 2; ++I) {
7295     Expr *Arg = TheCall->getArg(I);
7296     QualType T = Arg->getType();
7297     if (T->isDependentType()) {
7298       Dependent = true;
7299       continue;
7300     }
7301 
7302     // Despite supporting _Complex int, GCC requires a real floating point type
7303     // for the operands of __builtin_complex.
7304     if (!T->isRealFloatingType()) {
7305       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
7306              << Arg->getType() << Arg->getSourceRange();
7307     }
7308 
7309     ExprResult Converted = DefaultLvalueConversion(Arg);
7310     if (Converted.isInvalid())
7311       return true;
7312     TheCall->setArg(I, Converted.get());
7313   }
7314 
7315   if (Dependent) {
7316     TheCall->setType(Context.DependentTy);
7317     return false;
7318   }
7319 
7320   Expr *Real = TheCall->getArg(0);
7321   Expr *Imag = TheCall->getArg(1);
7322   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
7323     return Diag(Real->getBeginLoc(),
7324                 diag::err_typecheck_call_different_arg_types)
7325            << Real->getType() << Imag->getType()
7326            << Real->getSourceRange() << Imag->getSourceRange();
7327   }
7328 
7329   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
7330   // don't allow this builtin to form those types either.
7331   // FIXME: Should we allow these types?
7332   if (Real->getType()->isFloat16Type())
7333     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
7334            << "_Float16";
7335   if (Real->getType()->isHalfType())
7336     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
7337            << "half";
7338 
7339   TheCall->setType(Context.getComplexType(Real->getType()));
7340   return false;
7341 }
7342 
7343 // Customized Sema Checking for VSX builtins that have the following signature:
7344 // vector [...] builtinName(vector [...], vector [...], const int);
7345 // Which takes the same type of vectors (any legal vector type) for the first
7346 // two arguments and takes compile time constant for the third argument.
7347 // Example builtins are :
7348 // vector double vec_xxpermdi(vector double, vector double, int);
7349 // vector short vec_xxsldwi(vector short, vector short, int);
7350 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
7351   unsigned ExpectedNumArgs = 3;
7352   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
7353     return true;
7354 
7355   // Check the third argument is a compile time constant
7356   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
7357     return Diag(TheCall->getBeginLoc(),
7358                 diag::err_vsx_builtin_nonconstant_argument)
7359            << 3 /* argument index */ << TheCall->getDirectCallee()
7360            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
7361                           TheCall->getArg(2)->getEndLoc());
7362 
7363   QualType Arg1Ty = TheCall->getArg(0)->getType();
7364   QualType Arg2Ty = TheCall->getArg(1)->getType();
7365 
7366   // Check the type of argument 1 and argument 2 are vectors.
7367   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
7368   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
7369       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
7370     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
7371            << TheCall->getDirectCallee()
7372            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7373                           TheCall->getArg(1)->getEndLoc());
7374   }
7375 
7376   // Check the first two arguments are the same type.
7377   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
7378     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
7379            << TheCall->getDirectCallee()
7380            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7381                           TheCall->getArg(1)->getEndLoc());
7382   }
7383 
7384   // When default clang type checking is turned off and the customized type
7385   // checking is used, the returning type of the function must be explicitly
7386   // set. Otherwise it is _Bool by default.
7387   TheCall->setType(Arg1Ty);
7388 
7389   return false;
7390 }
7391 
7392 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
7393 // This is declared to take (...), so we have to check everything.
7394 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
7395   if (TheCall->getNumArgs() < 2)
7396     return ExprError(Diag(TheCall->getEndLoc(),
7397                           diag::err_typecheck_call_too_few_args_at_least)
7398                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
7399                      << TheCall->getSourceRange());
7400 
7401   // Determine which of the following types of shufflevector we're checking:
7402   // 1) unary, vector mask: (lhs, mask)
7403   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
7404   QualType resType = TheCall->getArg(0)->getType();
7405   unsigned numElements = 0;
7406 
7407   if (!TheCall->getArg(0)->isTypeDependent() &&
7408       !TheCall->getArg(1)->isTypeDependent()) {
7409     QualType LHSType = TheCall->getArg(0)->getType();
7410     QualType RHSType = TheCall->getArg(1)->getType();
7411 
7412     if (!LHSType->isVectorType() || !RHSType->isVectorType())
7413       return ExprError(
7414           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
7415           << TheCall->getDirectCallee()
7416           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7417                          TheCall->getArg(1)->getEndLoc()));
7418 
7419     numElements = LHSType->castAs<VectorType>()->getNumElements();
7420     unsigned numResElements = TheCall->getNumArgs() - 2;
7421 
7422     // Check to see if we have a call with 2 vector arguments, the unary shuffle
7423     // with mask.  If so, verify that RHS is an integer vector type with the
7424     // same number of elts as lhs.
7425     if (TheCall->getNumArgs() == 2) {
7426       if (!RHSType->hasIntegerRepresentation() ||
7427           RHSType->castAs<VectorType>()->getNumElements() != numElements)
7428         return ExprError(Diag(TheCall->getBeginLoc(),
7429                               diag::err_vec_builtin_incompatible_vector)
7430                          << TheCall->getDirectCallee()
7431                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
7432                                         TheCall->getArg(1)->getEndLoc()));
7433     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
7434       return ExprError(Diag(TheCall->getBeginLoc(),
7435                             diag::err_vec_builtin_incompatible_vector)
7436                        << TheCall->getDirectCallee()
7437                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
7438                                       TheCall->getArg(1)->getEndLoc()));
7439     } else if (numElements != numResElements) {
7440       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
7441       resType = Context.getVectorType(eltType, numResElements,
7442                                       VectorType::GenericVector);
7443     }
7444   }
7445 
7446   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
7447     if (TheCall->getArg(i)->isTypeDependent() ||
7448         TheCall->getArg(i)->isValueDependent())
7449       continue;
7450 
7451     Optional<llvm::APSInt> Result;
7452     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
7453       return ExprError(Diag(TheCall->getBeginLoc(),
7454                             diag::err_shufflevector_nonconstant_argument)
7455                        << TheCall->getArg(i)->getSourceRange());
7456 
7457     // Allow -1 which will be translated to undef in the IR.
7458     if (Result->isSigned() && Result->isAllOnes())
7459       continue;
7460 
7461     if (Result->getActiveBits() > 64 ||
7462         Result->getZExtValue() >= numElements * 2)
7463       return ExprError(Diag(TheCall->getBeginLoc(),
7464                             diag::err_shufflevector_argument_too_large)
7465                        << TheCall->getArg(i)->getSourceRange());
7466   }
7467 
7468   SmallVector<Expr*, 32> exprs;
7469 
7470   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
7471     exprs.push_back(TheCall->getArg(i));
7472     TheCall->setArg(i, nullptr);
7473   }
7474 
7475   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
7476                                          TheCall->getCallee()->getBeginLoc(),
7477                                          TheCall->getRParenLoc());
7478 }
7479 
7480 /// SemaConvertVectorExpr - Handle __builtin_convertvector
7481 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7482                                        SourceLocation BuiltinLoc,
7483                                        SourceLocation RParenLoc) {
7484   ExprValueKind VK = VK_PRValue;
7485   ExprObjectKind OK = OK_Ordinary;
7486   QualType DstTy = TInfo->getType();
7487   QualType SrcTy = E->getType();
7488 
7489   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
7490     return ExprError(Diag(BuiltinLoc,
7491                           diag::err_convertvector_non_vector)
7492                      << E->getSourceRange());
7493   if (!DstTy->isVectorType() && !DstTy->isDependentType())
7494     return ExprError(Diag(BuiltinLoc,
7495                           diag::err_convertvector_non_vector_type));
7496 
7497   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
7498     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
7499     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
7500     if (SrcElts != DstElts)
7501       return ExprError(Diag(BuiltinLoc,
7502                             diag::err_convertvector_incompatible_vector)
7503                        << E->getSourceRange());
7504   }
7505 
7506   return new (Context)
7507       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
7508 }
7509 
7510 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
7511 // This is declared to take (const void*, ...) and can take two
7512 // optional constant int args.
7513 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
7514   unsigned NumArgs = TheCall->getNumArgs();
7515 
7516   if (NumArgs > 3)
7517     return Diag(TheCall->getEndLoc(),
7518                 diag::err_typecheck_call_too_many_args_at_most)
7519            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7520 
7521   // Argument 0 is checked for us and the remaining arguments must be
7522   // constant integers.
7523   for (unsigned i = 1; i != NumArgs; ++i)
7524     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
7525       return true;
7526 
7527   return false;
7528 }
7529 
7530 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
7531 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
7532   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
7533     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
7534            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7535   if (checkArgCount(*this, TheCall, 1))
7536     return true;
7537   Expr *Arg = TheCall->getArg(0);
7538   if (Arg->isInstantiationDependent())
7539     return false;
7540 
7541   QualType ArgTy = Arg->getType();
7542   if (!ArgTy->hasFloatingRepresentation())
7543     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
7544            << ArgTy;
7545   if (Arg->isLValue()) {
7546     ExprResult FirstArg = DefaultLvalueConversion(Arg);
7547     TheCall->setArg(0, FirstArg.get());
7548   }
7549   TheCall->setType(TheCall->getArg(0)->getType());
7550   return false;
7551 }
7552 
7553 /// SemaBuiltinAssume - Handle __assume (MS Extension).
7554 // __assume does not evaluate its arguments, and should warn if its argument
7555 // has side effects.
7556 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
7557   Expr *Arg = TheCall->getArg(0);
7558   if (Arg->isInstantiationDependent()) return false;
7559 
7560   if (Arg->HasSideEffects(Context))
7561     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
7562         << Arg->getSourceRange()
7563         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
7564 
7565   return false;
7566 }
7567 
7568 /// Handle __builtin_alloca_with_align. This is declared
7569 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
7570 /// than 8.
7571 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
7572   // The alignment must be a constant integer.
7573   Expr *Arg = TheCall->getArg(1);
7574 
7575   // We can't check the value of a dependent argument.
7576   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7577     if (const auto *UE =
7578             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
7579       if (UE->getKind() == UETT_AlignOf ||
7580           UE->getKind() == UETT_PreferredAlignOf)
7581         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
7582             << Arg->getSourceRange();
7583 
7584     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
7585 
7586     if (!Result.isPowerOf2())
7587       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7588              << Arg->getSourceRange();
7589 
7590     if (Result < Context.getCharWidth())
7591       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
7592              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
7593 
7594     if (Result > std::numeric_limits<int32_t>::max())
7595       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
7596              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
7597   }
7598 
7599   return false;
7600 }
7601 
7602 /// Handle __builtin_assume_aligned. This is declared
7603 /// as (const void*, size_t, ...) and can take one optional constant int arg.
7604 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
7605   unsigned NumArgs = TheCall->getNumArgs();
7606 
7607   if (NumArgs > 3)
7608     return Diag(TheCall->getEndLoc(),
7609                 diag::err_typecheck_call_too_many_args_at_most)
7610            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
7611 
7612   // The alignment must be a constant integer.
7613   Expr *Arg = TheCall->getArg(1);
7614 
7615   // We can't check the value of a dependent argument.
7616   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
7617     llvm::APSInt Result;
7618     if (SemaBuiltinConstantArg(TheCall, 1, Result))
7619       return true;
7620 
7621     if (!Result.isPowerOf2())
7622       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7623              << Arg->getSourceRange();
7624 
7625     if (Result > Sema::MaximumAlignment)
7626       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7627           << Arg->getSourceRange() << Sema::MaximumAlignment;
7628   }
7629 
7630   if (NumArgs > 2) {
7631     ExprResult Arg(TheCall->getArg(2));
7632     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
7633       Context.getSizeType(), false);
7634     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7635     if (Arg.isInvalid()) return true;
7636     TheCall->setArg(2, Arg.get());
7637   }
7638 
7639   return false;
7640 }
7641 
7642 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7643   unsigned BuiltinID =
7644       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7645   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7646 
7647   unsigned NumArgs = TheCall->getNumArgs();
7648   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7649   if (NumArgs < NumRequiredArgs) {
7650     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7651            << 0 /* function call */ << NumRequiredArgs << NumArgs
7652            << TheCall->getSourceRange();
7653   }
7654   if (NumArgs >= NumRequiredArgs + 0x100) {
7655     return Diag(TheCall->getEndLoc(),
7656                 diag::err_typecheck_call_too_many_args_at_most)
7657            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7658            << TheCall->getSourceRange();
7659   }
7660   unsigned i = 0;
7661 
7662   // For formatting call, check buffer arg.
7663   if (!IsSizeCall) {
7664     ExprResult Arg(TheCall->getArg(i));
7665     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7666         Context, Context.VoidPtrTy, false);
7667     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7668     if (Arg.isInvalid())
7669       return true;
7670     TheCall->setArg(i, Arg.get());
7671     i++;
7672   }
7673 
7674   // Check string literal arg.
7675   unsigned FormatIdx = i;
7676   {
7677     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7678     if (Arg.isInvalid())
7679       return true;
7680     TheCall->setArg(i, Arg.get());
7681     i++;
7682   }
7683 
7684   // Make sure variadic args are scalar.
7685   unsigned FirstDataArg = i;
7686   while (i < NumArgs) {
7687     ExprResult Arg = DefaultVariadicArgumentPromotion(
7688         TheCall->getArg(i), VariadicFunction, nullptr);
7689     if (Arg.isInvalid())
7690       return true;
7691     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7692     if (ArgSize.getQuantity() >= 0x100) {
7693       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7694              << i << (int)ArgSize.getQuantity() << 0xff
7695              << TheCall->getSourceRange();
7696     }
7697     TheCall->setArg(i, Arg.get());
7698     i++;
7699   }
7700 
7701   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7702   // call to avoid duplicate diagnostics.
7703   if (!IsSizeCall) {
7704     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7705     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7706     bool Success = CheckFormatArguments(
7707         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7708         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7709         CheckedVarArgs);
7710     if (!Success)
7711       return true;
7712   }
7713 
7714   if (IsSizeCall) {
7715     TheCall->setType(Context.getSizeType());
7716   } else {
7717     TheCall->setType(Context.VoidPtrTy);
7718   }
7719   return false;
7720 }
7721 
7722 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7723 /// TheCall is a constant expression.
7724 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7725                                   llvm::APSInt &Result) {
7726   Expr *Arg = TheCall->getArg(ArgNum);
7727   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7728   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7729 
7730   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7731 
7732   Optional<llvm::APSInt> R;
7733   if (!(R = Arg->getIntegerConstantExpr(Context)))
7734     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7735            << FDecl->getDeclName() << Arg->getSourceRange();
7736   Result = *R;
7737   return false;
7738 }
7739 
7740 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7741 /// TheCall is a constant expression in the range [Low, High].
7742 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7743                                        int Low, int High, bool RangeIsError) {
7744   if (isConstantEvaluated())
7745     return false;
7746   llvm::APSInt Result;
7747 
7748   // We can't check the value of a dependent argument.
7749   Expr *Arg = TheCall->getArg(ArgNum);
7750   if (Arg->isTypeDependent() || Arg->isValueDependent())
7751     return false;
7752 
7753   // Check constant-ness first.
7754   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7755     return true;
7756 
7757   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7758     if (RangeIsError)
7759       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7760              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7761     else
7762       // Defer the warning until we know if the code will be emitted so that
7763       // dead code can ignore this.
7764       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7765                           PDiag(diag::warn_argument_invalid_range)
7766                               << toString(Result, 10) << Low << High
7767                               << Arg->getSourceRange());
7768   }
7769 
7770   return false;
7771 }
7772 
7773 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7774 /// TheCall is a constant expression is a multiple of Num..
7775 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7776                                           unsigned Num) {
7777   llvm::APSInt Result;
7778 
7779   // We can't check the value of a dependent argument.
7780   Expr *Arg = TheCall->getArg(ArgNum);
7781   if (Arg->isTypeDependent() || Arg->isValueDependent())
7782     return false;
7783 
7784   // Check constant-ness first.
7785   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7786     return true;
7787 
7788   if (Result.getSExtValue() % Num != 0)
7789     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7790            << Num << Arg->getSourceRange();
7791 
7792   return false;
7793 }
7794 
7795 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7796 /// constant expression representing a power of 2.
7797 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7798   llvm::APSInt Result;
7799 
7800   // We can't check the value of a dependent argument.
7801   Expr *Arg = TheCall->getArg(ArgNum);
7802   if (Arg->isTypeDependent() || Arg->isValueDependent())
7803     return false;
7804 
7805   // Check constant-ness first.
7806   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7807     return true;
7808 
7809   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7810   // and only if x is a power of 2.
7811   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7812     return false;
7813 
7814   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7815          << Arg->getSourceRange();
7816 }
7817 
7818 static bool IsShiftedByte(llvm::APSInt Value) {
7819   if (Value.isNegative())
7820     return false;
7821 
7822   // Check if it's a shifted byte, by shifting it down
7823   while (true) {
7824     // If the value fits in the bottom byte, the check passes.
7825     if (Value < 0x100)
7826       return true;
7827 
7828     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7829     // fails.
7830     if ((Value & 0xFF) != 0)
7831       return false;
7832 
7833     // If the bottom 8 bits are all 0, but something above that is nonzero,
7834     // then shifting the value right by 8 bits won't affect whether it's a
7835     // shifted byte or not. So do that, and go round again.
7836     Value >>= 8;
7837   }
7838 }
7839 
7840 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7841 /// a constant expression representing an arbitrary byte value shifted left by
7842 /// a multiple of 8 bits.
7843 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7844                                              unsigned ArgBits) {
7845   llvm::APSInt Result;
7846 
7847   // We can't check the value of a dependent argument.
7848   Expr *Arg = TheCall->getArg(ArgNum);
7849   if (Arg->isTypeDependent() || Arg->isValueDependent())
7850     return false;
7851 
7852   // Check constant-ness first.
7853   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7854     return true;
7855 
7856   // Truncate to the given size.
7857   Result = Result.getLoBits(ArgBits);
7858   Result.setIsUnsigned(true);
7859 
7860   if (IsShiftedByte(Result))
7861     return false;
7862 
7863   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7864          << Arg->getSourceRange();
7865 }
7866 
7867 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7868 /// TheCall is a constant expression representing either a shifted byte value,
7869 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7870 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7871 /// Arm MVE intrinsics.
7872 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7873                                                    int ArgNum,
7874                                                    unsigned ArgBits) {
7875   llvm::APSInt Result;
7876 
7877   // We can't check the value of a dependent argument.
7878   Expr *Arg = TheCall->getArg(ArgNum);
7879   if (Arg->isTypeDependent() || Arg->isValueDependent())
7880     return false;
7881 
7882   // Check constant-ness first.
7883   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7884     return true;
7885 
7886   // Truncate to the given size.
7887   Result = Result.getLoBits(ArgBits);
7888   Result.setIsUnsigned(true);
7889 
7890   // Check to see if it's in either of the required forms.
7891   if (IsShiftedByte(Result) ||
7892       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7893     return false;
7894 
7895   return Diag(TheCall->getBeginLoc(),
7896               diag::err_argument_not_shifted_byte_or_xxff)
7897          << Arg->getSourceRange();
7898 }
7899 
7900 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7901 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7902   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7903     if (checkArgCount(*this, TheCall, 2))
7904       return true;
7905     Expr *Arg0 = TheCall->getArg(0);
7906     Expr *Arg1 = TheCall->getArg(1);
7907 
7908     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7909     if (FirstArg.isInvalid())
7910       return true;
7911     QualType FirstArgType = FirstArg.get()->getType();
7912     if (!FirstArgType->isAnyPointerType())
7913       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7914                << "first" << FirstArgType << Arg0->getSourceRange();
7915     TheCall->setArg(0, FirstArg.get());
7916 
7917     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7918     if (SecArg.isInvalid())
7919       return true;
7920     QualType SecArgType = SecArg.get()->getType();
7921     if (!SecArgType->isIntegerType())
7922       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7923                << "second" << SecArgType << Arg1->getSourceRange();
7924 
7925     // Derive the return type from the pointer argument.
7926     TheCall->setType(FirstArgType);
7927     return false;
7928   }
7929 
7930   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7931     if (checkArgCount(*this, TheCall, 2))
7932       return true;
7933 
7934     Expr *Arg0 = TheCall->getArg(0);
7935     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7936     if (FirstArg.isInvalid())
7937       return true;
7938     QualType FirstArgType = FirstArg.get()->getType();
7939     if (!FirstArgType->isAnyPointerType())
7940       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7941                << "first" << FirstArgType << Arg0->getSourceRange();
7942     TheCall->setArg(0, FirstArg.get());
7943 
7944     // Derive the return type from the pointer argument.
7945     TheCall->setType(FirstArgType);
7946 
7947     // Second arg must be an constant in range [0,15]
7948     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7949   }
7950 
7951   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7952     if (checkArgCount(*this, TheCall, 2))
7953       return true;
7954     Expr *Arg0 = TheCall->getArg(0);
7955     Expr *Arg1 = TheCall->getArg(1);
7956 
7957     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7958     if (FirstArg.isInvalid())
7959       return true;
7960     QualType FirstArgType = FirstArg.get()->getType();
7961     if (!FirstArgType->isAnyPointerType())
7962       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7963                << "first" << FirstArgType << Arg0->getSourceRange();
7964 
7965     QualType SecArgType = Arg1->getType();
7966     if (!SecArgType->isIntegerType())
7967       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7968                << "second" << SecArgType << Arg1->getSourceRange();
7969     TheCall->setType(Context.IntTy);
7970     return false;
7971   }
7972 
7973   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7974       BuiltinID == AArch64::BI__builtin_arm_stg) {
7975     if (checkArgCount(*this, TheCall, 1))
7976       return true;
7977     Expr *Arg0 = TheCall->getArg(0);
7978     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7979     if (FirstArg.isInvalid())
7980       return true;
7981 
7982     QualType FirstArgType = FirstArg.get()->getType();
7983     if (!FirstArgType->isAnyPointerType())
7984       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7985                << "first" << FirstArgType << Arg0->getSourceRange();
7986     TheCall->setArg(0, FirstArg.get());
7987 
7988     // Derive the return type from the pointer argument.
7989     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7990       TheCall->setType(FirstArgType);
7991     return false;
7992   }
7993 
7994   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7995     Expr *ArgA = TheCall->getArg(0);
7996     Expr *ArgB = TheCall->getArg(1);
7997 
7998     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7999     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
8000 
8001     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
8002       return true;
8003 
8004     QualType ArgTypeA = ArgExprA.get()->getType();
8005     QualType ArgTypeB = ArgExprB.get()->getType();
8006 
8007     auto isNull = [&] (Expr *E) -> bool {
8008       return E->isNullPointerConstant(
8009                         Context, Expr::NPC_ValueDependentIsNotNull); };
8010 
8011     // argument should be either a pointer or null
8012     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
8013       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
8014         << "first" << ArgTypeA << ArgA->getSourceRange();
8015 
8016     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
8017       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
8018         << "second" << ArgTypeB << ArgB->getSourceRange();
8019 
8020     // Ensure Pointee types are compatible
8021     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
8022         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
8023       QualType pointeeA = ArgTypeA->getPointeeType();
8024       QualType pointeeB = ArgTypeB->getPointeeType();
8025       if (!Context.typesAreCompatible(
8026              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
8027              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
8028         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
8029           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
8030           << ArgB->getSourceRange();
8031       }
8032     }
8033 
8034     // at least one argument should be pointer type
8035     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
8036       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
8037         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
8038 
8039     if (isNull(ArgA)) // adopt type of the other pointer
8040       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
8041 
8042     if (isNull(ArgB))
8043       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
8044 
8045     TheCall->setArg(0, ArgExprA.get());
8046     TheCall->setArg(1, ArgExprB.get());
8047     TheCall->setType(Context.LongLongTy);
8048     return false;
8049   }
8050   assert(false && "Unhandled ARM MTE intrinsic");
8051   return true;
8052 }
8053 
8054 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
8055 /// TheCall is an ARM/AArch64 special register string literal.
8056 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
8057                                     int ArgNum, unsigned ExpectedFieldNum,
8058                                     bool AllowName) {
8059   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
8060                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
8061                       BuiltinID == ARM::BI__builtin_arm_rsr ||
8062                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
8063                       BuiltinID == ARM::BI__builtin_arm_wsr ||
8064                       BuiltinID == ARM::BI__builtin_arm_wsrp;
8065   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
8066                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
8067                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
8068                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
8069                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
8070                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
8071   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
8072 
8073   // We can't check the value of a dependent argument.
8074   Expr *Arg = TheCall->getArg(ArgNum);
8075   if (Arg->isTypeDependent() || Arg->isValueDependent())
8076     return false;
8077 
8078   // Check if the argument is a string literal.
8079   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
8080     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
8081            << Arg->getSourceRange();
8082 
8083   // Check the type of special register given.
8084   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
8085   SmallVector<StringRef, 6> Fields;
8086   Reg.split(Fields, ":");
8087 
8088   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
8089     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
8090            << Arg->getSourceRange();
8091 
8092   // If the string is the name of a register then we cannot check that it is
8093   // valid here but if the string is of one the forms described in ACLE then we
8094   // can check that the supplied fields are integers and within the valid
8095   // ranges.
8096   if (Fields.size() > 1) {
8097     bool FiveFields = Fields.size() == 5;
8098 
8099     bool ValidString = true;
8100     if (IsARMBuiltin) {
8101       ValidString &= Fields[0].startswith_insensitive("cp") ||
8102                      Fields[0].startswith_insensitive("p");
8103       if (ValidString)
8104         Fields[0] = Fields[0].drop_front(
8105             Fields[0].startswith_insensitive("cp") ? 2 : 1);
8106 
8107       ValidString &= Fields[2].startswith_insensitive("c");
8108       if (ValidString)
8109         Fields[2] = Fields[2].drop_front(1);
8110 
8111       if (FiveFields) {
8112         ValidString &= Fields[3].startswith_insensitive("c");
8113         if (ValidString)
8114           Fields[3] = Fields[3].drop_front(1);
8115       }
8116     }
8117 
8118     SmallVector<int, 5> Ranges;
8119     if (FiveFields)
8120       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
8121     else
8122       Ranges.append({15, 7, 15});
8123 
8124     for (unsigned i=0; i<Fields.size(); ++i) {
8125       int IntField;
8126       ValidString &= !Fields[i].getAsInteger(10, IntField);
8127       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
8128     }
8129 
8130     if (!ValidString)
8131       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
8132              << Arg->getSourceRange();
8133   } else if (IsAArch64Builtin && Fields.size() == 1) {
8134     // If the register name is one of those that appear in the condition below
8135     // and the special register builtin being used is one of the write builtins,
8136     // then we require that the argument provided for writing to the register
8137     // is an integer constant expression. This is because it will be lowered to
8138     // an MSR (immediate) instruction, so we need to know the immediate at
8139     // compile time.
8140     if (TheCall->getNumArgs() != 2)
8141       return false;
8142 
8143     std::string RegLower = Reg.lower();
8144     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
8145         RegLower != "pan" && RegLower != "uao")
8146       return false;
8147 
8148     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
8149   }
8150 
8151   return false;
8152 }
8153 
8154 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
8155 /// Emit an error and return true on failure; return false on success.
8156 /// TypeStr is a string containing the type descriptor of the value returned by
8157 /// the builtin and the descriptors of the expected type of the arguments.
8158 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
8159                                  const char *TypeStr) {
8160 
8161   assert((TypeStr[0] != '\0') &&
8162          "Invalid types in PPC MMA builtin declaration");
8163 
8164   switch (BuiltinID) {
8165   default:
8166     // This function is called in CheckPPCBuiltinFunctionCall where the
8167     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
8168     // we are isolating the pair vector memop builtins that can be used with mma
8169     // off so the default case is every builtin that requires mma and paired
8170     // vector memops.
8171     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
8172                          diag::err_ppc_builtin_only_on_arch, "10") ||
8173         SemaFeatureCheck(*this, TheCall, "mma",
8174                          diag::err_ppc_builtin_only_on_arch, "10"))
8175       return true;
8176     break;
8177   case PPC::BI__builtin_vsx_lxvp:
8178   case PPC::BI__builtin_vsx_stxvp:
8179   case PPC::BI__builtin_vsx_assemble_pair:
8180   case PPC::BI__builtin_vsx_disassemble_pair:
8181     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
8182                          diag::err_ppc_builtin_only_on_arch, "10"))
8183       return true;
8184     break;
8185   }
8186 
8187   unsigned Mask = 0;
8188   unsigned ArgNum = 0;
8189 
8190   // The first type in TypeStr is the type of the value returned by the
8191   // builtin. So we first read that type and change the type of TheCall.
8192   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
8193   TheCall->setType(type);
8194 
8195   while (*TypeStr != '\0') {
8196     Mask = 0;
8197     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
8198     if (ArgNum >= TheCall->getNumArgs()) {
8199       ArgNum++;
8200       break;
8201     }
8202 
8203     Expr *Arg = TheCall->getArg(ArgNum);
8204     QualType PassedType = Arg->getType();
8205     QualType StrippedRVType = PassedType.getCanonicalType();
8206 
8207     // Strip Restrict/Volatile qualifiers.
8208     if (StrippedRVType.isRestrictQualified() ||
8209         StrippedRVType.isVolatileQualified())
8210       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
8211 
8212     // The only case where the argument type and expected type are allowed to
8213     // mismatch is if the argument type is a non-void pointer (or array) and
8214     // expected type is a void pointer.
8215     if (StrippedRVType != ExpectedType)
8216       if (!(ExpectedType->isVoidPointerType() &&
8217             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
8218         return Diag(Arg->getBeginLoc(),
8219                     diag::err_typecheck_convert_incompatible)
8220                << PassedType << ExpectedType << 1 << 0 << 0;
8221 
8222     // If the value of the Mask is not 0, we have a constraint in the size of
8223     // the integer argument so here we ensure the argument is a constant that
8224     // is in the valid range.
8225     if (Mask != 0 &&
8226         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
8227       return true;
8228 
8229     ArgNum++;
8230   }
8231 
8232   // In case we exited early from the previous loop, there are other types to
8233   // read from TypeStr. So we need to read them all to ensure we have the right
8234   // number of arguments in TheCall and if it is not the case, to display a
8235   // better error message.
8236   while (*TypeStr != '\0') {
8237     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
8238     ArgNum++;
8239   }
8240   if (checkArgCount(*this, TheCall, ArgNum))
8241     return true;
8242 
8243   return false;
8244 }
8245 
8246 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
8247 /// This checks that the target supports __builtin_longjmp and
8248 /// that val is a constant 1.
8249 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
8250   if (!Context.getTargetInfo().hasSjLjLowering())
8251     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
8252            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
8253 
8254   Expr *Arg = TheCall->getArg(1);
8255   llvm::APSInt Result;
8256 
8257   // TODO: This is less than ideal. Overload this to take a value.
8258   if (SemaBuiltinConstantArg(TheCall, 1, Result))
8259     return true;
8260 
8261   if (Result != 1)
8262     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
8263            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
8264 
8265   return false;
8266 }
8267 
8268 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
8269 /// This checks that the target supports __builtin_setjmp.
8270 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
8271   if (!Context.getTargetInfo().hasSjLjLowering())
8272     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
8273            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
8274   return false;
8275 }
8276 
8277 namespace {
8278 
8279 class UncoveredArgHandler {
8280   enum { Unknown = -1, AllCovered = -2 };
8281 
8282   signed FirstUncoveredArg = Unknown;
8283   SmallVector<const Expr *, 4> DiagnosticExprs;
8284 
8285 public:
8286   UncoveredArgHandler() = default;
8287 
8288   bool hasUncoveredArg() const {
8289     return (FirstUncoveredArg >= 0);
8290   }
8291 
8292   unsigned getUncoveredArg() const {
8293     assert(hasUncoveredArg() && "no uncovered argument");
8294     return FirstUncoveredArg;
8295   }
8296 
8297   void setAllCovered() {
8298     // A string has been found with all arguments covered, so clear out
8299     // the diagnostics.
8300     DiagnosticExprs.clear();
8301     FirstUncoveredArg = AllCovered;
8302   }
8303 
8304   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
8305     assert(NewFirstUncoveredArg >= 0 && "Outside range");
8306 
8307     // Don't update if a previous string covers all arguments.
8308     if (FirstUncoveredArg == AllCovered)
8309       return;
8310 
8311     // UncoveredArgHandler tracks the highest uncovered argument index
8312     // and with it all the strings that match this index.
8313     if (NewFirstUncoveredArg == FirstUncoveredArg)
8314       DiagnosticExprs.push_back(StrExpr);
8315     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
8316       DiagnosticExprs.clear();
8317       DiagnosticExprs.push_back(StrExpr);
8318       FirstUncoveredArg = NewFirstUncoveredArg;
8319     }
8320   }
8321 
8322   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
8323 };
8324 
8325 enum StringLiteralCheckType {
8326   SLCT_NotALiteral,
8327   SLCT_UncheckedLiteral,
8328   SLCT_CheckedLiteral
8329 };
8330 
8331 } // namespace
8332 
8333 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
8334                                      BinaryOperatorKind BinOpKind,
8335                                      bool AddendIsRight) {
8336   unsigned BitWidth = Offset.getBitWidth();
8337   unsigned AddendBitWidth = Addend.getBitWidth();
8338   // There might be negative interim results.
8339   if (Addend.isUnsigned()) {
8340     Addend = Addend.zext(++AddendBitWidth);
8341     Addend.setIsSigned(true);
8342   }
8343   // Adjust the bit width of the APSInts.
8344   if (AddendBitWidth > BitWidth) {
8345     Offset = Offset.sext(AddendBitWidth);
8346     BitWidth = AddendBitWidth;
8347   } else if (BitWidth > AddendBitWidth) {
8348     Addend = Addend.sext(BitWidth);
8349   }
8350 
8351   bool Ov = false;
8352   llvm::APSInt ResOffset = Offset;
8353   if (BinOpKind == BO_Add)
8354     ResOffset = Offset.sadd_ov(Addend, Ov);
8355   else {
8356     assert(AddendIsRight && BinOpKind == BO_Sub &&
8357            "operator must be add or sub with addend on the right");
8358     ResOffset = Offset.ssub_ov(Addend, Ov);
8359   }
8360 
8361   // We add an offset to a pointer here so we should support an offset as big as
8362   // possible.
8363   if (Ov) {
8364     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
8365            "index (intermediate) result too big");
8366     Offset = Offset.sext(2 * BitWidth);
8367     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
8368     return;
8369   }
8370 
8371   Offset = ResOffset;
8372 }
8373 
8374 namespace {
8375 
8376 // This is a wrapper class around StringLiteral to support offsetted string
8377 // literals as format strings. It takes the offset into account when returning
8378 // the string and its length or the source locations to display notes correctly.
8379 class FormatStringLiteral {
8380   const StringLiteral *FExpr;
8381   int64_t Offset;
8382 
8383  public:
8384   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
8385       : FExpr(fexpr), Offset(Offset) {}
8386 
8387   StringRef getString() const {
8388     return FExpr->getString().drop_front(Offset);
8389   }
8390 
8391   unsigned getByteLength() const {
8392     return FExpr->getByteLength() - getCharByteWidth() * Offset;
8393   }
8394 
8395   unsigned getLength() const { return FExpr->getLength() - Offset; }
8396   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
8397 
8398   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
8399 
8400   QualType getType() const { return FExpr->getType(); }
8401 
8402   bool isAscii() const { return FExpr->isAscii(); }
8403   bool isWide() const { return FExpr->isWide(); }
8404   bool isUTF8() const { return FExpr->isUTF8(); }
8405   bool isUTF16() const { return FExpr->isUTF16(); }
8406   bool isUTF32() const { return FExpr->isUTF32(); }
8407   bool isPascal() const { return FExpr->isPascal(); }
8408 
8409   SourceLocation getLocationOfByte(
8410       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
8411       const TargetInfo &Target, unsigned *StartToken = nullptr,
8412       unsigned *StartTokenByteOffset = nullptr) const {
8413     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
8414                                     StartToken, StartTokenByteOffset);
8415   }
8416 
8417   SourceLocation getBeginLoc() const LLVM_READONLY {
8418     return FExpr->getBeginLoc().getLocWithOffset(Offset);
8419   }
8420 
8421   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
8422 };
8423 
8424 }  // namespace
8425 
8426 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8427                               const Expr *OrigFormatExpr,
8428                               ArrayRef<const Expr *> Args,
8429                               bool HasVAListArg, unsigned format_idx,
8430                               unsigned firstDataArg,
8431                               Sema::FormatStringType Type,
8432                               bool inFunctionCall,
8433                               Sema::VariadicCallType CallType,
8434                               llvm::SmallBitVector &CheckedVarArgs,
8435                               UncoveredArgHandler &UncoveredArg,
8436                               bool IgnoreStringsWithoutSpecifiers);
8437 
8438 // Determine if an expression is a string literal or constant string.
8439 // If this function returns false on the arguments to a function expecting a
8440 // format string, we will usually need to emit a warning.
8441 // True string literals are then checked by CheckFormatString.
8442 static StringLiteralCheckType
8443 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
8444                       bool HasVAListArg, unsigned format_idx,
8445                       unsigned firstDataArg, Sema::FormatStringType Type,
8446                       Sema::VariadicCallType CallType, bool InFunctionCall,
8447                       llvm::SmallBitVector &CheckedVarArgs,
8448                       UncoveredArgHandler &UncoveredArg,
8449                       llvm::APSInt Offset,
8450                       bool IgnoreStringsWithoutSpecifiers = false) {
8451   if (S.isConstantEvaluated())
8452     return SLCT_NotALiteral;
8453  tryAgain:
8454   assert(Offset.isSigned() && "invalid offset");
8455 
8456   if (E->isTypeDependent() || E->isValueDependent())
8457     return SLCT_NotALiteral;
8458 
8459   E = E->IgnoreParenCasts();
8460 
8461   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
8462     // Technically -Wformat-nonliteral does not warn about this case.
8463     // The behavior of printf and friends in this case is implementation
8464     // dependent.  Ideally if the format string cannot be null then
8465     // it should have a 'nonnull' attribute in the function prototype.
8466     return SLCT_UncheckedLiteral;
8467 
8468   switch (E->getStmtClass()) {
8469   case Stmt::BinaryConditionalOperatorClass:
8470   case Stmt::ConditionalOperatorClass: {
8471     // The expression is a literal if both sub-expressions were, and it was
8472     // completely checked only if both sub-expressions were checked.
8473     const AbstractConditionalOperator *C =
8474         cast<AbstractConditionalOperator>(E);
8475 
8476     // Determine whether it is necessary to check both sub-expressions, for
8477     // example, because the condition expression is a constant that can be
8478     // evaluated at compile time.
8479     bool CheckLeft = true, CheckRight = true;
8480 
8481     bool Cond;
8482     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
8483                                                  S.isConstantEvaluated())) {
8484       if (Cond)
8485         CheckRight = false;
8486       else
8487         CheckLeft = false;
8488     }
8489 
8490     // We need to maintain the offsets for the right and the left hand side
8491     // separately to check if every possible indexed expression is a valid
8492     // string literal. They might have different offsets for different string
8493     // literals in the end.
8494     StringLiteralCheckType Left;
8495     if (!CheckLeft)
8496       Left = SLCT_UncheckedLiteral;
8497     else {
8498       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
8499                                    HasVAListArg, format_idx, firstDataArg,
8500                                    Type, CallType, InFunctionCall,
8501                                    CheckedVarArgs, UncoveredArg, Offset,
8502                                    IgnoreStringsWithoutSpecifiers);
8503       if (Left == SLCT_NotALiteral || !CheckRight) {
8504         return Left;
8505       }
8506     }
8507 
8508     StringLiteralCheckType Right = checkFormatStringExpr(
8509         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
8510         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8511         IgnoreStringsWithoutSpecifiers);
8512 
8513     return (CheckLeft && Left < Right) ? Left : Right;
8514   }
8515 
8516   case Stmt::ImplicitCastExprClass:
8517     E = cast<ImplicitCastExpr>(E)->getSubExpr();
8518     goto tryAgain;
8519 
8520   case Stmt::OpaqueValueExprClass:
8521     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
8522       E = src;
8523       goto tryAgain;
8524     }
8525     return SLCT_NotALiteral;
8526 
8527   case Stmt::PredefinedExprClass:
8528     // While __func__, etc., are technically not string literals, they
8529     // cannot contain format specifiers and thus are not a security
8530     // liability.
8531     return SLCT_UncheckedLiteral;
8532 
8533   case Stmt::DeclRefExprClass: {
8534     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8535 
8536     // As an exception, do not flag errors for variables binding to
8537     // const string literals.
8538     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
8539       bool isConstant = false;
8540       QualType T = DR->getType();
8541 
8542       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
8543         isConstant = AT->getElementType().isConstant(S.Context);
8544       } else if (const PointerType *PT = T->getAs<PointerType>()) {
8545         isConstant = T.isConstant(S.Context) &&
8546                      PT->getPointeeType().isConstant(S.Context);
8547       } else if (T->isObjCObjectPointerType()) {
8548         // In ObjC, there is usually no "const ObjectPointer" type,
8549         // so don't check if the pointee type is constant.
8550         isConstant = T.isConstant(S.Context);
8551       }
8552 
8553       if (isConstant) {
8554         if (const Expr *Init = VD->getAnyInitializer()) {
8555           // Look through initializers like const char c[] = { "foo" }
8556           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
8557             if (InitList->isStringLiteralInit())
8558               Init = InitList->getInit(0)->IgnoreParenImpCasts();
8559           }
8560           return checkFormatStringExpr(S, Init, Args,
8561                                        HasVAListArg, format_idx,
8562                                        firstDataArg, Type, CallType,
8563                                        /*InFunctionCall*/ false, CheckedVarArgs,
8564                                        UncoveredArg, Offset);
8565         }
8566       }
8567 
8568       // For vprintf* functions (i.e., HasVAListArg==true), we add a
8569       // special check to see if the format string is a function parameter
8570       // of the function calling the printf function.  If the function
8571       // has an attribute indicating it is a printf-like function, then we
8572       // should suppress warnings concerning non-literals being used in a call
8573       // to a vprintf function.  For example:
8574       //
8575       // void
8576       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
8577       //      va_list ap;
8578       //      va_start(ap, fmt);
8579       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
8580       //      ...
8581       // }
8582       if (HasVAListArg) {
8583         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
8584           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
8585             int PVIndex = PV->getFunctionScopeIndex() + 1;
8586             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
8587               // adjust for implicit parameter
8588               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
8589                 if (MD->isInstance())
8590                   ++PVIndex;
8591               // We also check if the formats are compatible.
8592               // We can't pass a 'scanf' string to a 'printf' function.
8593               if (PVIndex == PVFormat->getFormatIdx() &&
8594                   Type == S.GetFormatStringType(PVFormat))
8595                 return SLCT_UncheckedLiteral;
8596             }
8597           }
8598         }
8599       }
8600     }
8601 
8602     return SLCT_NotALiteral;
8603   }
8604 
8605   case Stmt::CallExprClass:
8606   case Stmt::CXXMemberCallExprClass: {
8607     const CallExpr *CE = cast<CallExpr>(E);
8608     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
8609       bool IsFirst = true;
8610       StringLiteralCheckType CommonResult;
8611       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
8612         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
8613         StringLiteralCheckType Result = checkFormatStringExpr(
8614             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8615             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8616             IgnoreStringsWithoutSpecifiers);
8617         if (IsFirst) {
8618           CommonResult = Result;
8619           IsFirst = false;
8620         }
8621       }
8622       if (!IsFirst)
8623         return CommonResult;
8624 
8625       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8626         unsigned BuiltinID = FD->getBuiltinID();
8627         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
8628             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
8629           const Expr *Arg = CE->getArg(0);
8630           return checkFormatStringExpr(S, Arg, Args,
8631                                        HasVAListArg, format_idx,
8632                                        firstDataArg, Type, CallType,
8633                                        InFunctionCall, CheckedVarArgs,
8634                                        UncoveredArg, Offset,
8635                                        IgnoreStringsWithoutSpecifiers);
8636         }
8637       }
8638     }
8639 
8640     return SLCT_NotALiteral;
8641   }
8642   case Stmt::ObjCMessageExprClass: {
8643     const auto *ME = cast<ObjCMessageExpr>(E);
8644     if (const auto *MD = ME->getMethodDecl()) {
8645       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8646         // As a special case heuristic, if we're using the method -[NSBundle
8647         // localizedStringForKey:value:table:], ignore any key strings that lack
8648         // format specifiers. The idea is that if the key doesn't have any
8649         // format specifiers then its probably just a key to map to the
8650         // localized strings. If it does have format specifiers though, then its
8651         // likely that the text of the key is the format string in the
8652         // programmer's language, and should be checked.
8653         const ObjCInterfaceDecl *IFace;
8654         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8655             IFace->getIdentifier()->isStr("NSBundle") &&
8656             MD->getSelector().isKeywordSelector(
8657                 {"localizedStringForKey", "value", "table"})) {
8658           IgnoreStringsWithoutSpecifiers = true;
8659         }
8660 
8661         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8662         return checkFormatStringExpr(
8663             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8664             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8665             IgnoreStringsWithoutSpecifiers);
8666       }
8667     }
8668 
8669     return SLCT_NotALiteral;
8670   }
8671   case Stmt::ObjCStringLiteralClass:
8672   case Stmt::StringLiteralClass: {
8673     const StringLiteral *StrE = nullptr;
8674 
8675     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8676       StrE = ObjCFExpr->getString();
8677     else
8678       StrE = cast<StringLiteral>(E);
8679 
8680     if (StrE) {
8681       if (Offset.isNegative() || Offset > StrE->getLength()) {
8682         // TODO: It would be better to have an explicit warning for out of
8683         // bounds literals.
8684         return SLCT_NotALiteral;
8685       }
8686       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8687       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8688                         firstDataArg, Type, InFunctionCall, CallType,
8689                         CheckedVarArgs, UncoveredArg,
8690                         IgnoreStringsWithoutSpecifiers);
8691       return SLCT_CheckedLiteral;
8692     }
8693 
8694     return SLCT_NotALiteral;
8695   }
8696   case Stmt::BinaryOperatorClass: {
8697     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8698 
8699     // A string literal + an int offset is still a string literal.
8700     if (BinOp->isAdditiveOp()) {
8701       Expr::EvalResult LResult, RResult;
8702 
8703       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8704           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8705       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8706           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8707 
8708       if (LIsInt != RIsInt) {
8709         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8710 
8711         if (LIsInt) {
8712           if (BinOpKind == BO_Add) {
8713             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8714             E = BinOp->getRHS();
8715             goto tryAgain;
8716           }
8717         } else {
8718           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8719           E = BinOp->getLHS();
8720           goto tryAgain;
8721         }
8722       }
8723     }
8724 
8725     return SLCT_NotALiteral;
8726   }
8727   case Stmt::UnaryOperatorClass: {
8728     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8729     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8730     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8731       Expr::EvalResult IndexResult;
8732       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8733                                        Expr::SE_NoSideEffects,
8734                                        S.isConstantEvaluated())) {
8735         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8736                    /*RHS is int*/ true);
8737         E = ASE->getBase();
8738         goto tryAgain;
8739       }
8740     }
8741 
8742     return SLCT_NotALiteral;
8743   }
8744 
8745   default:
8746     return SLCT_NotALiteral;
8747   }
8748 }
8749 
8750 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8751   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8752       .Case("scanf", FST_Scanf)
8753       .Cases("printf", "printf0", FST_Printf)
8754       .Cases("NSString", "CFString", FST_NSString)
8755       .Case("strftime", FST_Strftime)
8756       .Case("strfmon", FST_Strfmon)
8757       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8758       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8759       .Case("os_trace", FST_OSLog)
8760       .Case("os_log", FST_OSLog)
8761       .Default(FST_Unknown);
8762 }
8763 
8764 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8765 /// functions) for correct use of format strings.
8766 /// Returns true if a format string has been fully checked.
8767 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8768                                 ArrayRef<const Expr *> Args,
8769                                 bool IsCXXMember,
8770                                 VariadicCallType CallType,
8771                                 SourceLocation Loc, SourceRange Range,
8772                                 llvm::SmallBitVector &CheckedVarArgs) {
8773   FormatStringInfo FSI;
8774   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8775     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8776                                 FSI.FirstDataArg, GetFormatStringType(Format),
8777                                 CallType, Loc, Range, CheckedVarArgs);
8778   return false;
8779 }
8780 
8781 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8782                                 bool HasVAListArg, unsigned format_idx,
8783                                 unsigned firstDataArg, FormatStringType Type,
8784                                 VariadicCallType CallType,
8785                                 SourceLocation Loc, SourceRange Range,
8786                                 llvm::SmallBitVector &CheckedVarArgs) {
8787   // CHECK: printf/scanf-like function is called with no format string.
8788   if (format_idx >= Args.size()) {
8789     Diag(Loc, diag::warn_missing_format_string) << Range;
8790     return false;
8791   }
8792 
8793   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8794 
8795   // CHECK: format string is not a string literal.
8796   //
8797   // Dynamically generated format strings are difficult to
8798   // automatically vet at compile time.  Requiring that format strings
8799   // are string literals: (1) permits the checking of format strings by
8800   // the compiler and thereby (2) can practically remove the source of
8801   // many format string exploits.
8802 
8803   // Format string can be either ObjC string (e.g. @"%d") or
8804   // C string (e.g. "%d")
8805   // ObjC string uses the same format specifiers as C string, so we can use
8806   // the same format string checking logic for both ObjC and C strings.
8807   UncoveredArgHandler UncoveredArg;
8808   StringLiteralCheckType CT =
8809       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8810                             format_idx, firstDataArg, Type, CallType,
8811                             /*IsFunctionCall*/ true, CheckedVarArgs,
8812                             UncoveredArg,
8813                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8814 
8815   // Generate a diagnostic where an uncovered argument is detected.
8816   if (UncoveredArg.hasUncoveredArg()) {
8817     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8818     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8819     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8820   }
8821 
8822   if (CT != SLCT_NotALiteral)
8823     // Literal format string found, check done!
8824     return CT == SLCT_CheckedLiteral;
8825 
8826   // Strftime is particular as it always uses a single 'time' argument,
8827   // so it is safe to pass a non-literal string.
8828   if (Type == FST_Strftime)
8829     return false;
8830 
8831   // Do not emit diag when the string param is a macro expansion and the
8832   // format is either NSString or CFString. This is a hack to prevent
8833   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8834   // which are usually used in place of NS and CF string literals.
8835   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8836   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8837     return false;
8838 
8839   // If there are no arguments specified, warn with -Wformat-security, otherwise
8840   // warn only with -Wformat-nonliteral.
8841   if (Args.size() == firstDataArg) {
8842     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8843       << OrigFormatExpr->getSourceRange();
8844     switch (Type) {
8845     default:
8846       break;
8847     case FST_Kprintf:
8848     case FST_FreeBSDKPrintf:
8849     case FST_Printf:
8850       Diag(FormatLoc, diag::note_format_security_fixit)
8851         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8852       break;
8853     case FST_NSString:
8854       Diag(FormatLoc, diag::note_format_security_fixit)
8855         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8856       break;
8857     }
8858   } else {
8859     Diag(FormatLoc, diag::warn_format_nonliteral)
8860       << OrigFormatExpr->getSourceRange();
8861   }
8862   return false;
8863 }
8864 
8865 namespace {
8866 
8867 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8868 protected:
8869   Sema &S;
8870   const FormatStringLiteral *FExpr;
8871   const Expr *OrigFormatExpr;
8872   const Sema::FormatStringType FSType;
8873   const unsigned FirstDataArg;
8874   const unsigned NumDataArgs;
8875   const char *Beg; // Start of format string.
8876   const bool HasVAListArg;
8877   ArrayRef<const Expr *> Args;
8878   unsigned FormatIdx;
8879   llvm::SmallBitVector CoveredArgs;
8880   bool usesPositionalArgs = false;
8881   bool atFirstArg = true;
8882   bool inFunctionCall;
8883   Sema::VariadicCallType CallType;
8884   llvm::SmallBitVector &CheckedVarArgs;
8885   UncoveredArgHandler &UncoveredArg;
8886 
8887 public:
8888   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8889                      const Expr *origFormatExpr,
8890                      const Sema::FormatStringType type, unsigned firstDataArg,
8891                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8892                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8893                      bool inFunctionCall, Sema::VariadicCallType callType,
8894                      llvm::SmallBitVector &CheckedVarArgs,
8895                      UncoveredArgHandler &UncoveredArg)
8896       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8897         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8898         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8899         inFunctionCall(inFunctionCall), CallType(callType),
8900         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8901     CoveredArgs.resize(numDataArgs);
8902     CoveredArgs.reset();
8903   }
8904 
8905   void DoneProcessing();
8906 
8907   void HandleIncompleteSpecifier(const char *startSpecifier,
8908                                  unsigned specifierLen) override;
8909 
8910   void HandleInvalidLengthModifier(
8911                            const analyze_format_string::FormatSpecifier &FS,
8912                            const analyze_format_string::ConversionSpecifier &CS,
8913                            const char *startSpecifier, unsigned specifierLen,
8914                            unsigned DiagID);
8915 
8916   void HandleNonStandardLengthModifier(
8917                     const analyze_format_string::FormatSpecifier &FS,
8918                     const char *startSpecifier, unsigned specifierLen);
8919 
8920   void HandleNonStandardConversionSpecifier(
8921                     const analyze_format_string::ConversionSpecifier &CS,
8922                     const char *startSpecifier, unsigned specifierLen);
8923 
8924   void HandlePosition(const char *startPos, unsigned posLen) override;
8925 
8926   void HandleInvalidPosition(const char *startSpecifier,
8927                              unsigned specifierLen,
8928                              analyze_format_string::PositionContext p) override;
8929 
8930   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8931 
8932   void HandleNullChar(const char *nullCharacter) override;
8933 
8934   template <typename Range>
8935   static void
8936   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8937                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8938                        bool IsStringLocation, Range StringRange,
8939                        ArrayRef<FixItHint> Fixit = None);
8940 
8941 protected:
8942   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8943                                         const char *startSpec,
8944                                         unsigned specifierLen,
8945                                         const char *csStart, unsigned csLen);
8946 
8947   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8948                                          const char *startSpec,
8949                                          unsigned specifierLen);
8950 
8951   SourceRange getFormatStringRange();
8952   CharSourceRange getSpecifierRange(const char *startSpecifier,
8953                                     unsigned specifierLen);
8954   SourceLocation getLocationOfByte(const char *x);
8955 
8956   const Expr *getDataArg(unsigned i) const;
8957 
8958   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8959                     const analyze_format_string::ConversionSpecifier &CS,
8960                     const char *startSpecifier, unsigned specifierLen,
8961                     unsigned argIndex);
8962 
8963   template <typename Range>
8964   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8965                             bool IsStringLocation, Range StringRange,
8966                             ArrayRef<FixItHint> Fixit = None);
8967 };
8968 
8969 } // namespace
8970 
8971 SourceRange CheckFormatHandler::getFormatStringRange() {
8972   return OrigFormatExpr->getSourceRange();
8973 }
8974 
8975 CharSourceRange CheckFormatHandler::
8976 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8977   SourceLocation Start = getLocationOfByte(startSpecifier);
8978   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8979 
8980   // Advance the end SourceLocation by one due to half-open ranges.
8981   End = End.getLocWithOffset(1);
8982 
8983   return CharSourceRange::getCharRange(Start, End);
8984 }
8985 
8986 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8987   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8988                                   S.getLangOpts(), S.Context.getTargetInfo());
8989 }
8990 
8991 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8992                                                    unsigned specifierLen){
8993   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8994                        getLocationOfByte(startSpecifier),
8995                        /*IsStringLocation*/true,
8996                        getSpecifierRange(startSpecifier, specifierLen));
8997 }
8998 
8999 void CheckFormatHandler::HandleInvalidLengthModifier(
9000     const analyze_format_string::FormatSpecifier &FS,
9001     const analyze_format_string::ConversionSpecifier &CS,
9002     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
9003   using namespace analyze_format_string;
9004 
9005   const LengthModifier &LM = FS.getLengthModifier();
9006   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
9007 
9008   // See if we know how to fix this length modifier.
9009   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
9010   if (FixedLM) {
9011     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
9012                          getLocationOfByte(LM.getStart()),
9013                          /*IsStringLocation*/true,
9014                          getSpecifierRange(startSpecifier, specifierLen));
9015 
9016     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
9017       << FixedLM->toString()
9018       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
9019 
9020   } else {
9021     FixItHint Hint;
9022     if (DiagID == diag::warn_format_nonsensical_length)
9023       Hint = FixItHint::CreateRemoval(LMRange);
9024 
9025     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
9026                          getLocationOfByte(LM.getStart()),
9027                          /*IsStringLocation*/true,
9028                          getSpecifierRange(startSpecifier, specifierLen),
9029                          Hint);
9030   }
9031 }
9032 
9033 void CheckFormatHandler::HandleNonStandardLengthModifier(
9034     const analyze_format_string::FormatSpecifier &FS,
9035     const char *startSpecifier, unsigned specifierLen) {
9036   using namespace analyze_format_string;
9037 
9038   const LengthModifier &LM = FS.getLengthModifier();
9039   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
9040 
9041   // See if we know how to fix this length modifier.
9042   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
9043   if (FixedLM) {
9044     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
9045                            << LM.toString() << 0,
9046                          getLocationOfByte(LM.getStart()),
9047                          /*IsStringLocation*/true,
9048                          getSpecifierRange(startSpecifier, specifierLen));
9049 
9050     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
9051       << FixedLM->toString()
9052       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
9053 
9054   } else {
9055     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
9056                            << LM.toString() << 0,
9057                          getLocationOfByte(LM.getStart()),
9058                          /*IsStringLocation*/true,
9059                          getSpecifierRange(startSpecifier, specifierLen));
9060   }
9061 }
9062 
9063 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
9064     const analyze_format_string::ConversionSpecifier &CS,
9065     const char *startSpecifier, unsigned specifierLen) {
9066   using namespace analyze_format_string;
9067 
9068   // See if we know how to fix this conversion specifier.
9069   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
9070   if (FixedCS) {
9071     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
9072                           << CS.toString() << /*conversion specifier*/1,
9073                          getLocationOfByte(CS.getStart()),
9074                          /*IsStringLocation*/true,
9075                          getSpecifierRange(startSpecifier, specifierLen));
9076 
9077     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
9078     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
9079       << FixedCS->toString()
9080       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
9081   } else {
9082     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
9083                           << CS.toString() << /*conversion specifier*/1,
9084                          getLocationOfByte(CS.getStart()),
9085                          /*IsStringLocation*/true,
9086                          getSpecifierRange(startSpecifier, specifierLen));
9087   }
9088 }
9089 
9090 void CheckFormatHandler::HandlePosition(const char *startPos,
9091                                         unsigned posLen) {
9092   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
9093                                getLocationOfByte(startPos),
9094                                /*IsStringLocation*/true,
9095                                getSpecifierRange(startPos, posLen));
9096 }
9097 
9098 void
9099 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
9100                                      analyze_format_string::PositionContext p) {
9101   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
9102                          << (unsigned) p,
9103                        getLocationOfByte(startPos), /*IsStringLocation*/true,
9104                        getSpecifierRange(startPos, posLen));
9105 }
9106 
9107 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
9108                                             unsigned posLen) {
9109   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
9110                                getLocationOfByte(startPos),
9111                                /*IsStringLocation*/true,
9112                                getSpecifierRange(startPos, posLen));
9113 }
9114 
9115 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
9116   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
9117     // The presence of a null character is likely an error.
9118     EmitFormatDiagnostic(
9119       S.PDiag(diag::warn_printf_format_string_contains_null_char),
9120       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
9121       getFormatStringRange());
9122   }
9123 }
9124 
9125 // Note that this may return NULL if there was an error parsing or building
9126 // one of the argument expressions.
9127 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
9128   return Args[FirstDataArg + i];
9129 }
9130 
9131 void CheckFormatHandler::DoneProcessing() {
9132   // Does the number of data arguments exceed the number of
9133   // format conversions in the format string?
9134   if (!HasVAListArg) {
9135       // Find any arguments that weren't covered.
9136     CoveredArgs.flip();
9137     signed notCoveredArg = CoveredArgs.find_first();
9138     if (notCoveredArg >= 0) {
9139       assert((unsigned)notCoveredArg < NumDataArgs);
9140       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
9141     } else {
9142       UncoveredArg.setAllCovered();
9143     }
9144   }
9145 }
9146 
9147 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
9148                                    const Expr *ArgExpr) {
9149   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
9150          "Invalid state");
9151 
9152   if (!ArgExpr)
9153     return;
9154 
9155   SourceLocation Loc = ArgExpr->getBeginLoc();
9156 
9157   if (S.getSourceManager().isInSystemMacro(Loc))
9158     return;
9159 
9160   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
9161   for (auto E : DiagnosticExprs)
9162     PDiag << E->getSourceRange();
9163 
9164   CheckFormatHandler::EmitFormatDiagnostic(
9165                                   S, IsFunctionCall, DiagnosticExprs[0],
9166                                   PDiag, Loc, /*IsStringLocation*/false,
9167                                   DiagnosticExprs[0]->getSourceRange());
9168 }
9169 
9170 bool
9171 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
9172                                                      SourceLocation Loc,
9173                                                      const char *startSpec,
9174                                                      unsigned specifierLen,
9175                                                      const char *csStart,
9176                                                      unsigned csLen) {
9177   bool keepGoing = true;
9178   if (argIndex < NumDataArgs) {
9179     // Consider the argument coverered, even though the specifier doesn't
9180     // make sense.
9181     CoveredArgs.set(argIndex);
9182   }
9183   else {
9184     // If argIndex exceeds the number of data arguments we
9185     // don't issue a warning because that is just a cascade of warnings (and
9186     // they may have intended '%%' anyway). We don't want to continue processing
9187     // the format string after this point, however, as we will like just get
9188     // gibberish when trying to match arguments.
9189     keepGoing = false;
9190   }
9191 
9192   StringRef Specifier(csStart, csLen);
9193 
9194   // If the specifier in non-printable, it could be the first byte of a UTF-8
9195   // sequence. In that case, print the UTF-8 code point. If not, print the byte
9196   // hex value.
9197   std::string CodePointStr;
9198   if (!llvm::sys::locale::isPrint(*csStart)) {
9199     llvm::UTF32 CodePoint;
9200     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
9201     const llvm::UTF8 *E =
9202         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
9203     llvm::ConversionResult Result =
9204         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
9205 
9206     if (Result != llvm::conversionOK) {
9207       unsigned char FirstChar = *csStart;
9208       CodePoint = (llvm::UTF32)FirstChar;
9209     }
9210 
9211     llvm::raw_string_ostream OS(CodePointStr);
9212     if (CodePoint < 256)
9213       OS << "\\x" << llvm::format("%02x", CodePoint);
9214     else if (CodePoint <= 0xFFFF)
9215       OS << "\\u" << llvm::format("%04x", CodePoint);
9216     else
9217       OS << "\\U" << llvm::format("%08x", CodePoint);
9218     OS.flush();
9219     Specifier = CodePointStr;
9220   }
9221 
9222   EmitFormatDiagnostic(
9223       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
9224       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
9225 
9226   return keepGoing;
9227 }
9228 
9229 void
9230 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
9231                                                       const char *startSpec,
9232                                                       unsigned specifierLen) {
9233   EmitFormatDiagnostic(
9234     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
9235     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
9236 }
9237 
9238 bool
9239 CheckFormatHandler::CheckNumArgs(
9240   const analyze_format_string::FormatSpecifier &FS,
9241   const analyze_format_string::ConversionSpecifier &CS,
9242   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
9243 
9244   if (argIndex >= NumDataArgs) {
9245     PartialDiagnostic PDiag = FS.usesPositionalArg()
9246       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
9247            << (argIndex+1) << NumDataArgs)
9248       : S.PDiag(diag::warn_printf_insufficient_data_args);
9249     EmitFormatDiagnostic(
9250       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
9251       getSpecifierRange(startSpecifier, specifierLen));
9252 
9253     // Since more arguments than conversion tokens are given, by extension
9254     // all arguments are covered, so mark this as so.
9255     UncoveredArg.setAllCovered();
9256     return false;
9257   }
9258   return true;
9259 }
9260 
9261 template<typename Range>
9262 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
9263                                               SourceLocation Loc,
9264                                               bool IsStringLocation,
9265                                               Range StringRange,
9266                                               ArrayRef<FixItHint> FixIt) {
9267   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
9268                        Loc, IsStringLocation, StringRange, FixIt);
9269 }
9270 
9271 /// If the format string is not within the function call, emit a note
9272 /// so that the function call and string are in diagnostic messages.
9273 ///
9274 /// \param InFunctionCall if true, the format string is within the function
9275 /// call and only one diagnostic message will be produced.  Otherwise, an
9276 /// extra note will be emitted pointing to location of the format string.
9277 ///
9278 /// \param ArgumentExpr the expression that is passed as the format string
9279 /// argument in the function call.  Used for getting locations when two
9280 /// diagnostics are emitted.
9281 ///
9282 /// \param PDiag the callee should already have provided any strings for the
9283 /// diagnostic message.  This function only adds locations and fixits
9284 /// to diagnostics.
9285 ///
9286 /// \param Loc primary location for diagnostic.  If two diagnostics are
9287 /// required, one will be at Loc and a new SourceLocation will be created for
9288 /// the other one.
9289 ///
9290 /// \param IsStringLocation if true, Loc points to the format string should be
9291 /// used for the note.  Otherwise, Loc points to the argument list and will
9292 /// be used with PDiag.
9293 ///
9294 /// \param StringRange some or all of the string to highlight.  This is
9295 /// templated so it can accept either a CharSourceRange or a SourceRange.
9296 ///
9297 /// \param FixIt optional fix it hint for the format string.
9298 template <typename Range>
9299 void CheckFormatHandler::EmitFormatDiagnostic(
9300     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
9301     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
9302     Range StringRange, ArrayRef<FixItHint> FixIt) {
9303   if (InFunctionCall) {
9304     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
9305     D << StringRange;
9306     D << FixIt;
9307   } else {
9308     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
9309       << ArgumentExpr->getSourceRange();
9310 
9311     const Sema::SemaDiagnosticBuilder &Note =
9312       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
9313              diag::note_format_string_defined);
9314 
9315     Note << StringRange;
9316     Note << FixIt;
9317   }
9318 }
9319 
9320 //===--- CHECK: Printf format string checking ------------------------------===//
9321 
9322 namespace {
9323 
9324 class CheckPrintfHandler : public CheckFormatHandler {
9325 public:
9326   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
9327                      const Expr *origFormatExpr,
9328                      const Sema::FormatStringType type, unsigned firstDataArg,
9329                      unsigned numDataArgs, bool isObjC, const char *beg,
9330                      bool hasVAListArg, ArrayRef<const Expr *> Args,
9331                      unsigned formatIdx, bool inFunctionCall,
9332                      Sema::VariadicCallType CallType,
9333                      llvm::SmallBitVector &CheckedVarArgs,
9334                      UncoveredArgHandler &UncoveredArg)
9335       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9336                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9337                            inFunctionCall, CallType, CheckedVarArgs,
9338                            UncoveredArg) {}
9339 
9340   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
9341 
9342   /// Returns true if '%@' specifiers are allowed in the format string.
9343   bool allowsObjCArg() const {
9344     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
9345            FSType == Sema::FST_OSTrace;
9346   }
9347 
9348   bool HandleInvalidPrintfConversionSpecifier(
9349                                       const analyze_printf::PrintfSpecifier &FS,
9350                                       const char *startSpecifier,
9351                                       unsigned specifierLen) override;
9352 
9353   void handleInvalidMaskType(StringRef MaskType) override;
9354 
9355   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
9356                              const char *startSpecifier, unsigned specifierLen,
9357                              const TargetInfo &Target) override;
9358   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9359                        const char *StartSpecifier,
9360                        unsigned SpecifierLen,
9361                        const Expr *E);
9362 
9363   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
9364                     const char *startSpecifier, unsigned specifierLen);
9365   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
9366                            const analyze_printf::OptionalAmount &Amt,
9367                            unsigned type,
9368                            const char *startSpecifier, unsigned specifierLen);
9369   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9370                   const analyze_printf::OptionalFlag &flag,
9371                   const char *startSpecifier, unsigned specifierLen);
9372   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
9373                          const analyze_printf::OptionalFlag &ignoredFlag,
9374                          const analyze_printf::OptionalFlag &flag,
9375                          const char *startSpecifier, unsigned specifierLen);
9376   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
9377                            const Expr *E);
9378 
9379   void HandleEmptyObjCModifierFlag(const char *startFlag,
9380                                    unsigned flagLen) override;
9381 
9382   void HandleInvalidObjCModifierFlag(const char *startFlag,
9383                                             unsigned flagLen) override;
9384 
9385   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
9386                                            const char *flagsEnd,
9387                                            const char *conversionPosition)
9388                                              override;
9389 };
9390 
9391 } // namespace
9392 
9393 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
9394                                       const analyze_printf::PrintfSpecifier &FS,
9395                                       const char *startSpecifier,
9396                                       unsigned specifierLen) {
9397   const analyze_printf::PrintfConversionSpecifier &CS =
9398     FS.getConversionSpecifier();
9399 
9400   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9401                                           getLocationOfByte(CS.getStart()),
9402                                           startSpecifier, specifierLen,
9403                                           CS.getStart(), CS.getLength());
9404 }
9405 
9406 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
9407   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
9408 }
9409 
9410 bool CheckPrintfHandler::HandleAmount(
9411                                const analyze_format_string::OptionalAmount &Amt,
9412                                unsigned k, const char *startSpecifier,
9413                                unsigned specifierLen) {
9414   if (Amt.hasDataArgument()) {
9415     if (!HasVAListArg) {
9416       unsigned argIndex = Amt.getArgIndex();
9417       if (argIndex >= NumDataArgs) {
9418         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
9419                                << k,
9420                              getLocationOfByte(Amt.getStart()),
9421                              /*IsStringLocation*/true,
9422                              getSpecifierRange(startSpecifier, specifierLen));
9423         // Don't do any more checking.  We will just emit
9424         // spurious errors.
9425         return false;
9426       }
9427 
9428       // Type check the data argument.  It should be an 'int'.
9429       // Although not in conformance with C99, we also allow the argument to be
9430       // an 'unsigned int' as that is a reasonably safe case.  GCC also
9431       // doesn't emit a warning for that case.
9432       CoveredArgs.set(argIndex);
9433       const Expr *Arg = getDataArg(argIndex);
9434       if (!Arg)
9435         return false;
9436 
9437       QualType T = Arg->getType();
9438 
9439       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
9440       assert(AT.isValid());
9441 
9442       if (!AT.matchesType(S.Context, T)) {
9443         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
9444                                << k << AT.getRepresentativeTypeName(S.Context)
9445                                << T << Arg->getSourceRange(),
9446                              getLocationOfByte(Amt.getStart()),
9447                              /*IsStringLocation*/true,
9448                              getSpecifierRange(startSpecifier, specifierLen));
9449         // Don't do any more checking.  We will just emit
9450         // spurious errors.
9451         return false;
9452       }
9453     }
9454   }
9455   return true;
9456 }
9457 
9458 void CheckPrintfHandler::HandleInvalidAmount(
9459                                       const analyze_printf::PrintfSpecifier &FS,
9460                                       const analyze_printf::OptionalAmount &Amt,
9461                                       unsigned type,
9462                                       const char *startSpecifier,
9463                                       unsigned specifierLen) {
9464   const analyze_printf::PrintfConversionSpecifier &CS =
9465     FS.getConversionSpecifier();
9466 
9467   FixItHint fixit =
9468     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
9469       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
9470                                  Amt.getConstantLength()))
9471       : FixItHint();
9472 
9473   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9474                          << type << CS.toString(),
9475                        getLocationOfByte(Amt.getStart()),
9476                        /*IsStringLocation*/true,
9477                        getSpecifierRange(startSpecifier, specifierLen),
9478                        fixit);
9479 }
9480 
9481 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9482                                     const analyze_printf::OptionalFlag &flag,
9483                                     const char *startSpecifier,
9484                                     unsigned specifierLen) {
9485   // Warn about pointless flag with a fixit removal.
9486   const analyze_printf::PrintfConversionSpecifier &CS =
9487     FS.getConversionSpecifier();
9488   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
9489                          << flag.toString() << CS.toString(),
9490                        getLocationOfByte(flag.getPosition()),
9491                        /*IsStringLocation*/true,
9492                        getSpecifierRange(startSpecifier, specifierLen),
9493                        FixItHint::CreateRemoval(
9494                          getSpecifierRange(flag.getPosition(), 1)));
9495 }
9496 
9497 void CheckPrintfHandler::HandleIgnoredFlag(
9498                                 const analyze_printf::PrintfSpecifier &FS,
9499                                 const analyze_printf::OptionalFlag &ignoredFlag,
9500                                 const analyze_printf::OptionalFlag &flag,
9501                                 const char *startSpecifier,
9502                                 unsigned specifierLen) {
9503   // Warn about ignored flag with a fixit removal.
9504   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9505                          << ignoredFlag.toString() << flag.toString(),
9506                        getLocationOfByte(ignoredFlag.getPosition()),
9507                        /*IsStringLocation*/true,
9508                        getSpecifierRange(startSpecifier, specifierLen),
9509                        FixItHint::CreateRemoval(
9510                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
9511 }
9512 
9513 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9514                                                      unsigned flagLen) {
9515   // Warn about an empty flag.
9516   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
9517                        getLocationOfByte(startFlag),
9518                        /*IsStringLocation*/true,
9519                        getSpecifierRange(startFlag, flagLen));
9520 }
9521 
9522 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9523                                                        unsigned flagLen) {
9524   // Warn about an invalid flag.
9525   auto Range = getSpecifierRange(startFlag, flagLen);
9526   StringRef flag(startFlag, flagLen);
9527   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9528                       getLocationOfByte(startFlag),
9529                       /*IsStringLocation*/true,
9530                       Range, FixItHint::CreateRemoval(Range));
9531 }
9532 
9533 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9534     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
9535     // Warn about using '[...]' without a '@' conversion.
9536     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9537     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9538     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9539                          getLocationOfByte(conversionPosition),
9540                          /*IsStringLocation*/true,
9541                          Range, FixItHint::CreateRemoval(Range));
9542 }
9543 
9544 // Determines if the specified is a C++ class or struct containing
9545 // a member with the specified name and kind (e.g. a CXXMethodDecl named
9546 // "c_str()").
9547 template<typename MemberKind>
9548 static llvm::SmallPtrSet<MemberKind*, 1>
9549 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9550   const RecordType *RT = Ty->getAs<RecordType>();
9551   llvm::SmallPtrSet<MemberKind*, 1> Results;
9552 
9553   if (!RT)
9554     return Results;
9555   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
9556   if (!RD || !RD->getDefinition())
9557     return Results;
9558 
9559   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9560                  Sema::LookupMemberName);
9561   R.suppressDiagnostics();
9562 
9563   // We just need to include all members of the right kind turned up by the
9564   // filter, at this point.
9565   if (S.LookupQualifiedName(R, RT->getDecl()))
9566     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9567       NamedDecl *decl = (*I)->getUnderlyingDecl();
9568       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9569         Results.insert(FK);
9570     }
9571   return Results;
9572 }
9573 
9574 /// Check if we could call '.c_str()' on an object.
9575 ///
9576 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9577 /// allow the call, or if it would be ambiguous).
9578 bool Sema::hasCStrMethod(const Expr *E) {
9579   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9580 
9581   MethodSet Results =
9582       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9583   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9584        MI != ME; ++MI)
9585     if ((*MI)->getMinRequiredArguments() == 0)
9586       return true;
9587   return false;
9588 }
9589 
9590 // Check if a (w)string was passed when a (w)char* was needed, and offer a
9591 // better diagnostic if so. AT is assumed to be valid.
9592 // Returns true when a c_str() conversion method is found.
9593 bool CheckPrintfHandler::checkForCStrMembers(
9594     const analyze_printf::ArgType &AT, const Expr *E) {
9595   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9596 
9597   MethodSet Results =
9598       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
9599 
9600   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9601        MI != ME; ++MI) {
9602     const CXXMethodDecl *Method = *MI;
9603     if (Method->getMinRequiredArguments() == 0 &&
9604         AT.matchesType(S.Context, Method->getReturnType())) {
9605       // FIXME: Suggest parens if the expression needs them.
9606       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
9607       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9608           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9609       return true;
9610     }
9611   }
9612 
9613   return false;
9614 }
9615 
9616 bool CheckPrintfHandler::HandlePrintfSpecifier(
9617     const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9618     unsigned specifierLen, const TargetInfo &Target) {
9619   using namespace analyze_format_string;
9620   using namespace analyze_printf;
9621 
9622   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9623 
9624   if (FS.consumesDataArgument()) {
9625     if (atFirstArg) {
9626         atFirstArg = false;
9627         usesPositionalArgs = FS.usesPositionalArg();
9628     }
9629     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9630       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9631                                         startSpecifier, specifierLen);
9632       return false;
9633     }
9634   }
9635 
9636   // First check if the field width, precision, and conversion specifier
9637   // have matching data arguments.
9638   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9639                     startSpecifier, specifierLen)) {
9640     return false;
9641   }
9642 
9643   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9644                     startSpecifier, specifierLen)) {
9645     return false;
9646   }
9647 
9648   if (!CS.consumesDataArgument()) {
9649     // FIXME: Technically specifying a precision or field width here
9650     // makes no sense.  Worth issuing a warning at some point.
9651     return true;
9652   }
9653 
9654   // Consume the argument.
9655   unsigned argIndex = FS.getArgIndex();
9656   if (argIndex < NumDataArgs) {
9657     // The check to see if the argIndex is valid will come later.
9658     // We set the bit here because we may exit early from this
9659     // function if we encounter some other error.
9660     CoveredArgs.set(argIndex);
9661   }
9662 
9663   // FreeBSD kernel extensions.
9664   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9665       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9666     // We need at least two arguments.
9667     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9668       return false;
9669 
9670     // Claim the second argument.
9671     CoveredArgs.set(argIndex + 1);
9672 
9673     // Type check the first argument (int for %b, pointer for %D)
9674     const Expr *Ex = getDataArg(argIndex);
9675     const analyze_printf::ArgType &AT =
9676       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9677         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9678     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9679       EmitFormatDiagnostic(
9680           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9681               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9682               << false << Ex->getSourceRange(),
9683           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9684           getSpecifierRange(startSpecifier, specifierLen));
9685 
9686     // Type check the second argument (char * for both %b and %D)
9687     Ex = getDataArg(argIndex + 1);
9688     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9689     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9690       EmitFormatDiagnostic(
9691           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9692               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9693               << false << Ex->getSourceRange(),
9694           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9695           getSpecifierRange(startSpecifier, specifierLen));
9696 
9697      return true;
9698   }
9699 
9700   // Check for using an Objective-C specific conversion specifier
9701   // in a non-ObjC literal.
9702   if (!allowsObjCArg() && CS.isObjCArg()) {
9703     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9704                                                   specifierLen);
9705   }
9706 
9707   // %P can only be used with os_log.
9708   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9709     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9710                                                   specifierLen);
9711   }
9712 
9713   // %n is not allowed with os_log.
9714   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9715     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9716                          getLocationOfByte(CS.getStart()),
9717                          /*IsStringLocation*/ false,
9718                          getSpecifierRange(startSpecifier, specifierLen));
9719 
9720     return true;
9721   }
9722 
9723   // Only scalars are allowed for os_trace.
9724   if (FSType == Sema::FST_OSTrace &&
9725       (CS.getKind() == ConversionSpecifier::PArg ||
9726        CS.getKind() == ConversionSpecifier::sArg ||
9727        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9728     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9729                                                   specifierLen);
9730   }
9731 
9732   // Check for use of public/private annotation outside of os_log().
9733   if (FSType != Sema::FST_OSLog) {
9734     if (FS.isPublic().isSet()) {
9735       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9736                                << "public",
9737                            getLocationOfByte(FS.isPublic().getPosition()),
9738                            /*IsStringLocation*/ false,
9739                            getSpecifierRange(startSpecifier, specifierLen));
9740     }
9741     if (FS.isPrivate().isSet()) {
9742       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9743                                << "private",
9744                            getLocationOfByte(FS.isPrivate().getPosition()),
9745                            /*IsStringLocation*/ false,
9746                            getSpecifierRange(startSpecifier, specifierLen));
9747     }
9748   }
9749 
9750   const llvm::Triple &Triple = Target.getTriple();
9751   if (CS.getKind() == ConversionSpecifier::nArg &&
9752       (Triple.isAndroid() || Triple.isOSFuchsia())) {
9753     EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9754                          getLocationOfByte(CS.getStart()),
9755                          /*IsStringLocation*/ false,
9756                          getSpecifierRange(startSpecifier, specifierLen));
9757   }
9758 
9759   // Check for invalid use of field width
9760   if (!FS.hasValidFieldWidth()) {
9761     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9762         startSpecifier, specifierLen);
9763   }
9764 
9765   // Check for invalid use of precision
9766   if (!FS.hasValidPrecision()) {
9767     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9768         startSpecifier, specifierLen);
9769   }
9770 
9771   // Precision is mandatory for %P specifier.
9772   if (CS.getKind() == ConversionSpecifier::PArg &&
9773       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9774     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9775                          getLocationOfByte(startSpecifier),
9776                          /*IsStringLocation*/ false,
9777                          getSpecifierRange(startSpecifier, specifierLen));
9778   }
9779 
9780   // Check each flag does not conflict with any other component.
9781   if (!FS.hasValidThousandsGroupingPrefix())
9782     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9783   if (!FS.hasValidLeadingZeros())
9784     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9785   if (!FS.hasValidPlusPrefix())
9786     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9787   if (!FS.hasValidSpacePrefix())
9788     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9789   if (!FS.hasValidAlternativeForm())
9790     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9791   if (!FS.hasValidLeftJustified())
9792     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9793 
9794   // Check that flags are not ignored by another flag
9795   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9796     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9797         startSpecifier, specifierLen);
9798   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9799     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9800             startSpecifier, specifierLen);
9801 
9802   // Check the length modifier is valid with the given conversion specifier.
9803   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9804                                  S.getLangOpts()))
9805     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9806                                 diag::warn_format_nonsensical_length);
9807   else if (!FS.hasStandardLengthModifier())
9808     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9809   else if (!FS.hasStandardLengthConversionCombination())
9810     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9811                                 diag::warn_format_non_standard_conversion_spec);
9812 
9813   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9814     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9815 
9816   // The remaining checks depend on the data arguments.
9817   if (HasVAListArg)
9818     return true;
9819 
9820   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9821     return false;
9822 
9823   const Expr *Arg = getDataArg(argIndex);
9824   if (!Arg)
9825     return true;
9826 
9827   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9828 }
9829 
9830 static bool requiresParensToAddCast(const Expr *E) {
9831   // FIXME: We should have a general way to reason about operator
9832   // precedence and whether parens are actually needed here.
9833   // Take care of a few common cases where they aren't.
9834   const Expr *Inside = E->IgnoreImpCasts();
9835   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9836     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9837 
9838   switch (Inside->getStmtClass()) {
9839   case Stmt::ArraySubscriptExprClass:
9840   case Stmt::CallExprClass:
9841   case Stmt::CharacterLiteralClass:
9842   case Stmt::CXXBoolLiteralExprClass:
9843   case Stmt::DeclRefExprClass:
9844   case Stmt::FloatingLiteralClass:
9845   case Stmt::IntegerLiteralClass:
9846   case Stmt::MemberExprClass:
9847   case Stmt::ObjCArrayLiteralClass:
9848   case Stmt::ObjCBoolLiteralExprClass:
9849   case Stmt::ObjCBoxedExprClass:
9850   case Stmt::ObjCDictionaryLiteralClass:
9851   case Stmt::ObjCEncodeExprClass:
9852   case Stmt::ObjCIvarRefExprClass:
9853   case Stmt::ObjCMessageExprClass:
9854   case Stmt::ObjCPropertyRefExprClass:
9855   case Stmt::ObjCStringLiteralClass:
9856   case Stmt::ObjCSubscriptRefExprClass:
9857   case Stmt::ParenExprClass:
9858   case Stmt::StringLiteralClass:
9859   case Stmt::UnaryOperatorClass:
9860     return false;
9861   default:
9862     return true;
9863   }
9864 }
9865 
9866 static std::pair<QualType, StringRef>
9867 shouldNotPrintDirectly(const ASTContext &Context,
9868                        QualType IntendedTy,
9869                        const Expr *E) {
9870   // Use a 'while' to peel off layers of typedefs.
9871   QualType TyTy = IntendedTy;
9872   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9873     StringRef Name = UserTy->getDecl()->getName();
9874     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9875       .Case("CFIndex", Context.getNSIntegerType())
9876       .Case("NSInteger", Context.getNSIntegerType())
9877       .Case("NSUInteger", Context.getNSUIntegerType())
9878       .Case("SInt32", Context.IntTy)
9879       .Case("UInt32", Context.UnsignedIntTy)
9880       .Default(QualType());
9881 
9882     if (!CastTy.isNull())
9883       return std::make_pair(CastTy, Name);
9884 
9885     TyTy = UserTy->desugar();
9886   }
9887 
9888   // Strip parens if necessary.
9889   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9890     return shouldNotPrintDirectly(Context,
9891                                   PE->getSubExpr()->getType(),
9892                                   PE->getSubExpr());
9893 
9894   // If this is a conditional expression, then its result type is constructed
9895   // via usual arithmetic conversions and thus there might be no necessary
9896   // typedef sugar there.  Recurse to operands to check for NSInteger &
9897   // Co. usage condition.
9898   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9899     QualType TrueTy, FalseTy;
9900     StringRef TrueName, FalseName;
9901 
9902     std::tie(TrueTy, TrueName) =
9903       shouldNotPrintDirectly(Context,
9904                              CO->getTrueExpr()->getType(),
9905                              CO->getTrueExpr());
9906     std::tie(FalseTy, FalseName) =
9907       shouldNotPrintDirectly(Context,
9908                              CO->getFalseExpr()->getType(),
9909                              CO->getFalseExpr());
9910 
9911     if (TrueTy == FalseTy)
9912       return std::make_pair(TrueTy, TrueName);
9913     else if (TrueTy.isNull())
9914       return std::make_pair(FalseTy, FalseName);
9915     else if (FalseTy.isNull())
9916       return std::make_pair(TrueTy, TrueName);
9917   }
9918 
9919   return std::make_pair(QualType(), StringRef());
9920 }
9921 
9922 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9923 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9924 /// type do not count.
9925 static bool
9926 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9927   QualType From = ICE->getSubExpr()->getType();
9928   QualType To = ICE->getType();
9929   // It's an integer promotion if the destination type is the promoted
9930   // source type.
9931   if (ICE->getCastKind() == CK_IntegralCast &&
9932       From->isPromotableIntegerType() &&
9933       S.Context.getPromotedIntegerType(From) == To)
9934     return true;
9935   // Look through vector types, since we do default argument promotion for
9936   // those in OpenCL.
9937   if (const auto *VecTy = From->getAs<ExtVectorType>())
9938     From = VecTy->getElementType();
9939   if (const auto *VecTy = To->getAs<ExtVectorType>())
9940     To = VecTy->getElementType();
9941   // It's a floating promotion if the source type is a lower rank.
9942   return ICE->getCastKind() == CK_FloatingCast &&
9943          S.Context.getFloatingTypeOrder(From, To) < 0;
9944 }
9945 
9946 bool
9947 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9948                                     const char *StartSpecifier,
9949                                     unsigned SpecifierLen,
9950                                     const Expr *E) {
9951   using namespace analyze_format_string;
9952   using namespace analyze_printf;
9953 
9954   // Now type check the data expression that matches the
9955   // format specifier.
9956   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9957   if (!AT.isValid())
9958     return true;
9959 
9960   QualType ExprTy = E->getType();
9961   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9962     ExprTy = TET->getUnderlyingExpr()->getType();
9963   }
9964 
9965   // Diagnose attempts to print a boolean value as a character. Unlike other
9966   // -Wformat diagnostics, this is fine from a type perspective, but it still
9967   // doesn't make sense.
9968   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9969       E->isKnownToHaveBooleanValue()) {
9970     const CharSourceRange &CSR =
9971         getSpecifierRange(StartSpecifier, SpecifierLen);
9972     SmallString<4> FSString;
9973     llvm::raw_svector_ostream os(FSString);
9974     FS.toString(os);
9975     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9976                              << FSString,
9977                          E->getExprLoc(), false, CSR);
9978     return true;
9979   }
9980 
9981   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9982   if (Match == analyze_printf::ArgType::Match)
9983     return true;
9984 
9985   // Look through argument promotions for our error message's reported type.
9986   // This includes the integral and floating promotions, but excludes array
9987   // and function pointer decay (seeing that an argument intended to be a
9988   // string has type 'char [6]' is probably more confusing than 'char *') and
9989   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9990   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9991     if (isArithmeticArgumentPromotion(S, ICE)) {
9992       E = ICE->getSubExpr();
9993       ExprTy = E->getType();
9994 
9995       // Check if we didn't match because of an implicit cast from a 'char'
9996       // or 'short' to an 'int'.  This is done because printf is a varargs
9997       // function.
9998       if (ICE->getType() == S.Context.IntTy ||
9999           ICE->getType() == S.Context.UnsignedIntTy) {
10000         // All further checking is done on the subexpression
10001         const analyze_printf::ArgType::MatchKind ImplicitMatch =
10002             AT.matchesType(S.Context, ExprTy);
10003         if (ImplicitMatch == analyze_printf::ArgType::Match)
10004           return true;
10005         if (ImplicitMatch == ArgType::NoMatchPedantic ||
10006             ImplicitMatch == ArgType::NoMatchTypeConfusion)
10007           Match = ImplicitMatch;
10008       }
10009     }
10010   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
10011     // Special case for 'a', which has type 'int' in C.
10012     // Note, however, that we do /not/ want to treat multibyte constants like
10013     // 'MooV' as characters! This form is deprecated but still exists. In
10014     // addition, don't treat expressions as of type 'char' if one byte length
10015     // modifier is provided.
10016     if (ExprTy == S.Context.IntTy &&
10017         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
10018       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
10019         ExprTy = S.Context.CharTy;
10020   }
10021 
10022   // Look through enums to their underlying type.
10023   bool IsEnum = false;
10024   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
10025     ExprTy = EnumTy->getDecl()->getIntegerType();
10026     IsEnum = true;
10027   }
10028 
10029   // %C in an Objective-C context prints a unichar, not a wchar_t.
10030   // If the argument is an integer of some kind, believe the %C and suggest
10031   // a cast instead of changing the conversion specifier.
10032   QualType IntendedTy = ExprTy;
10033   if (isObjCContext() &&
10034       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
10035     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
10036         !ExprTy->isCharType()) {
10037       // 'unichar' is defined as a typedef of unsigned short, but we should
10038       // prefer using the typedef if it is visible.
10039       IntendedTy = S.Context.UnsignedShortTy;
10040 
10041       // While we are here, check if the value is an IntegerLiteral that happens
10042       // to be within the valid range.
10043       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
10044         const llvm::APInt &V = IL->getValue();
10045         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
10046           return true;
10047       }
10048 
10049       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
10050                           Sema::LookupOrdinaryName);
10051       if (S.LookupName(Result, S.getCurScope())) {
10052         NamedDecl *ND = Result.getFoundDecl();
10053         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
10054           if (TD->getUnderlyingType() == IntendedTy)
10055             IntendedTy = S.Context.getTypedefType(TD);
10056       }
10057     }
10058   }
10059 
10060   // Special-case some of Darwin's platform-independence types by suggesting
10061   // casts to primitive types that are known to be large enough.
10062   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
10063   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
10064     QualType CastTy;
10065     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
10066     if (!CastTy.isNull()) {
10067       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
10068       // (long in ASTContext). Only complain to pedants.
10069       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
10070           (AT.isSizeT() || AT.isPtrdiffT()) &&
10071           AT.matchesType(S.Context, CastTy))
10072         Match = ArgType::NoMatchPedantic;
10073       IntendedTy = CastTy;
10074       ShouldNotPrintDirectly = true;
10075     }
10076   }
10077 
10078   // We may be able to offer a FixItHint if it is a supported type.
10079   PrintfSpecifier fixedFS = FS;
10080   bool Success =
10081       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
10082 
10083   if (Success) {
10084     // Get the fix string from the fixed format specifier
10085     SmallString<16> buf;
10086     llvm::raw_svector_ostream os(buf);
10087     fixedFS.toString(os);
10088 
10089     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
10090 
10091     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
10092       unsigned Diag;
10093       switch (Match) {
10094       case ArgType::Match: llvm_unreachable("expected non-matching");
10095       case ArgType::NoMatchPedantic:
10096         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
10097         break;
10098       case ArgType::NoMatchTypeConfusion:
10099         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
10100         break;
10101       case ArgType::NoMatch:
10102         Diag = diag::warn_format_conversion_argument_type_mismatch;
10103         break;
10104       }
10105 
10106       // In this case, the specifier is wrong and should be changed to match
10107       // the argument.
10108       EmitFormatDiagnostic(S.PDiag(Diag)
10109                                << AT.getRepresentativeTypeName(S.Context)
10110                                << IntendedTy << IsEnum << E->getSourceRange(),
10111                            E->getBeginLoc(),
10112                            /*IsStringLocation*/ false, SpecRange,
10113                            FixItHint::CreateReplacement(SpecRange, os.str()));
10114     } else {
10115       // The canonical type for formatting this value is different from the
10116       // actual type of the expression. (This occurs, for example, with Darwin's
10117       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
10118       // should be printed as 'long' for 64-bit compatibility.)
10119       // Rather than emitting a normal format/argument mismatch, we want to
10120       // add a cast to the recommended type (and correct the format string
10121       // if necessary).
10122       SmallString<16> CastBuf;
10123       llvm::raw_svector_ostream CastFix(CastBuf);
10124       CastFix << "(";
10125       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
10126       CastFix << ")";
10127 
10128       SmallVector<FixItHint,4> Hints;
10129       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
10130         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
10131 
10132       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
10133         // If there's already a cast present, just replace it.
10134         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
10135         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
10136 
10137       } else if (!requiresParensToAddCast(E)) {
10138         // If the expression has high enough precedence,
10139         // just write the C-style cast.
10140         Hints.push_back(
10141             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
10142       } else {
10143         // Otherwise, add parens around the expression as well as the cast.
10144         CastFix << "(";
10145         Hints.push_back(
10146             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
10147 
10148         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
10149         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
10150       }
10151 
10152       if (ShouldNotPrintDirectly) {
10153         // The expression has a type that should not be printed directly.
10154         // We extract the name from the typedef because we don't want to show
10155         // the underlying type in the diagnostic.
10156         StringRef Name;
10157         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
10158           Name = TypedefTy->getDecl()->getName();
10159         else
10160           Name = CastTyName;
10161         unsigned Diag = Match == ArgType::NoMatchPedantic
10162                             ? diag::warn_format_argument_needs_cast_pedantic
10163                             : diag::warn_format_argument_needs_cast;
10164         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
10165                                            << E->getSourceRange(),
10166                              E->getBeginLoc(), /*IsStringLocation=*/false,
10167                              SpecRange, Hints);
10168       } else {
10169         // In this case, the expression could be printed using a different
10170         // specifier, but we've decided that the specifier is probably correct
10171         // and we should cast instead. Just use the normal warning message.
10172         EmitFormatDiagnostic(
10173             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
10174                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
10175                 << E->getSourceRange(),
10176             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
10177       }
10178     }
10179   } else {
10180     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
10181                                                    SpecifierLen);
10182     // Since the warning for passing non-POD types to variadic functions
10183     // was deferred until now, we emit a warning for non-POD
10184     // arguments here.
10185     switch (S.isValidVarArgType(ExprTy)) {
10186     case Sema::VAK_Valid:
10187     case Sema::VAK_ValidInCXX11: {
10188       unsigned Diag;
10189       switch (Match) {
10190       case ArgType::Match: llvm_unreachable("expected non-matching");
10191       case ArgType::NoMatchPedantic:
10192         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
10193         break;
10194       case ArgType::NoMatchTypeConfusion:
10195         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
10196         break;
10197       case ArgType::NoMatch:
10198         Diag = diag::warn_format_conversion_argument_type_mismatch;
10199         break;
10200       }
10201 
10202       EmitFormatDiagnostic(
10203           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
10204                         << IsEnum << CSR << E->getSourceRange(),
10205           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10206       break;
10207     }
10208     case Sema::VAK_Undefined:
10209     case Sema::VAK_MSVCUndefined:
10210       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
10211                                << S.getLangOpts().CPlusPlus11 << ExprTy
10212                                << CallType
10213                                << AT.getRepresentativeTypeName(S.Context) << CSR
10214                                << E->getSourceRange(),
10215                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10216       checkForCStrMembers(AT, E);
10217       break;
10218 
10219     case Sema::VAK_Invalid:
10220       if (ExprTy->isObjCObjectType())
10221         EmitFormatDiagnostic(
10222             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
10223                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
10224                 << AT.getRepresentativeTypeName(S.Context) << CSR
10225                 << E->getSourceRange(),
10226             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10227       else
10228         // FIXME: If this is an initializer list, suggest removing the braces
10229         // or inserting a cast to the target type.
10230         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
10231             << isa<InitListExpr>(E) << ExprTy << CallType
10232             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
10233       break;
10234     }
10235 
10236     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
10237            "format string specifier index out of range");
10238     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
10239   }
10240 
10241   return true;
10242 }
10243 
10244 //===--- CHECK: Scanf format string checking ------------------------------===//
10245 
10246 namespace {
10247 
10248 class CheckScanfHandler : public CheckFormatHandler {
10249 public:
10250   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
10251                     const Expr *origFormatExpr, Sema::FormatStringType type,
10252                     unsigned firstDataArg, unsigned numDataArgs,
10253                     const char *beg, bool hasVAListArg,
10254                     ArrayRef<const Expr *> Args, unsigned formatIdx,
10255                     bool inFunctionCall, Sema::VariadicCallType CallType,
10256                     llvm::SmallBitVector &CheckedVarArgs,
10257                     UncoveredArgHandler &UncoveredArg)
10258       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
10259                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
10260                            inFunctionCall, CallType, CheckedVarArgs,
10261                            UncoveredArg) {}
10262 
10263   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10264                             const char *startSpecifier,
10265                             unsigned specifierLen) override;
10266 
10267   bool HandleInvalidScanfConversionSpecifier(
10268           const analyze_scanf::ScanfSpecifier &FS,
10269           const char *startSpecifier,
10270           unsigned specifierLen) override;
10271 
10272   void HandleIncompleteScanList(const char *start, const char *end) override;
10273 };
10274 
10275 } // namespace
10276 
10277 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
10278                                                  const char *end) {
10279   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
10280                        getLocationOfByte(end), /*IsStringLocation*/true,
10281                        getSpecifierRange(start, end - start));
10282 }
10283 
10284 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
10285                                         const analyze_scanf::ScanfSpecifier &FS,
10286                                         const char *startSpecifier,
10287                                         unsigned specifierLen) {
10288   const analyze_scanf::ScanfConversionSpecifier &CS =
10289     FS.getConversionSpecifier();
10290 
10291   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
10292                                           getLocationOfByte(CS.getStart()),
10293                                           startSpecifier, specifierLen,
10294                                           CS.getStart(), CS.getLength());
10295 }
10296 
10297 bool CheckScanfHandler::HandleScanfSpecifier(
10298                                        const analyze_scanf::ScanfSpecifier &FS,
10299                                        const char *startSpecifier,
10300                                        unsigned specifierLen) {
10301   using namespace analyze_scanf;
10302   using namespace analyze_format_string;
10303 
10304   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
10305 
10306   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
10307   // be used to decide if we are using positional arguments consistently.
10308   if (FS.consumesDataArgument()) {
10309     if (atFirstArg) {
10310       atFirstArg = false;
10311       usesPositionalArgs = FS.usesPositionalArg();
10312     }
10313     else if (usesPositionalArgs != FS.usesPositionalArg()) {
10314       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
10315                                         startSpecifier, specifierLen);
10316       return false;
10317     }
10318   }
10319 
10320   // Check if the field with is non-zero.
10321   const OptionalAmount &Amt = FS.getFieldWidth();
10322   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
10323     if (Amt.getConstantAmount() == 0) {
10324       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
10325                                                    Amt.getConstantLength());
10326       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
10327                            getLocationOfByte(Amt.getStart()),
10328                            /*IsStringLocation*/true, R,
10329                            FixItHint::CreateRemoval(R));
10330     }
10331   }
10332 
10333   if (!FS.consumesDataArgument()) {
10334     // FIXME: Technically specifying a precision or field width here
10335     // makes no sense.  Worth issuing a warning at some point.
10336     return true;
10337   }
10338 
10339   // Consume the argument.
10340   unsigned argIndex = FS.getArgIndex();
10341   if (argIndex < NumDataArgs) {
10342       // The check to see if the argIndex is valid will come later.
10343       // We set the bit here because we may exit early from this
10344       // function if we encounter some other error.
10345     CoveredArgs.set(argIndex);
10346   }
10347 
10348   // Check the length modifier is valid with the given conversion specifier.
10349   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
10350                                  S.getLangOpts()))
10351     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10352                                 diag::warn_format_nonsensical_length);
10353   else if (!FS.hasStandardLengthModifier())
10354     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10355   else if (!FS.hasStandardLengthConversionCombination())
10356     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10357                                 diag::warn_format_non_standard_conversion_spec);
10358 
10359   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
10360     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10361 
10362   // The remaining checks depend on the data arguments.
10363   if (HasVAListArg)
10364     return true;
10365 
10366   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10367     return false;
10368 
10369   // Check that the argument type matches the format specifier.
10370   const Expr *Ex = getDataArg(argIndex);
10371   if (!Ex)
10372     return true;
10373 
10374   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
10375 
10376   if (!AT.isValid()) {
10377     return true;
10378   }
10379 
10380   analyze_format_string::ArgType::MatchKind Match =
10381       AT.matchesType(S.Context, Ex->getType());
10382   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
10383   if (Match == analyze_format_string::ArgType::Match)
10384     return true;
10385 
10386   ScanfSpecifier fixedFS = FS;
10387   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10388                                  S.getLangOpts(), S.Context);
10389 
10390   unsigned Diag =
10391       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10392                : diag::warn_format_conversion_argument_type_mismatch;
10393 
10394   if (Success) {
10395     // Get the fix string from the fixed format specifier.
10396     SmallString<128> buf;
10397     llvm::raw_svector_ostream os(buf);
10398     fixedFS.toString(os);
10399 
10400     EmitFormatDiagnostic(
10401         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
10402                       << Ex->getType() << false << Ex->getSourceRange(),
10403         Ex->getBeginLoc(),
10404         /*IsStringLocation*/ false,
10405         getSpecifierRange(startSpecifier, specifierLen),
10406         FixItHint::CreateReplacement(
10407             getSpecifierRange(startSpecifier, specifierLen), os.str()));
10408   } else {
10409     EmitFormatDiagnostic(S.PDiag(Diag)
10410                              << AT.getRepresentativeTypeName(S.Context)
10411                              << Ex->getType() << false << Ex->getSourceRange(),
10412                          Ex->getBeginLoc(),
10413                          /*IsStringLocation*/ false,
10414                          getSpecifierRange(startSpecifier, specifierLen));
10415   }
10416 
10417   return true;
10418 }
10419 
10420 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
10421                               const Expr *OrigFormatExpr,
10422                               ArrayRef<const Expr *> Args,
10423                               bool HasVAListArg, unsigned format_idx,
10424                               unsigned firstDataArg,
10425                               Sema::FormatStringType Type,
10426                               bool inFunctionCall,
10427                               Sema::VariadicCallType CallType,
10428                               llvm::SmallBitVector &CheckedVarArgs,
10429                               UncoveredArgHandler &UncoveredArg,
10430                               bool IgnoreStringsWithoutSpecifiers) {
10431   // CHECK: is the format string a wide literal?
10432   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10433     CheckFormatHandler::EmitFormatDiagnostic(
10434         S, inFunctionCall, Args[format_idx],
10435         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10436         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10437     return;
10438   }
10439 
10440   // Str - The format string.  NOTE: this is NOT null-terminated!
10441   StringRef StrRef = FExpr->getString();
10442   const char *Str = StrRef.data();
10443   // Account for cases where the string literal is truncated in a declaration.
10444   const ConstantArrayType *T =
10445     S.Context.getAsConstantArrayType(FExpr->getType());
10446   assert(T && "String literal not of constant array type!");
10447   size_t TypeSize = T->getSize().getZExtValue();
10448   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10449   const unsigned numDataArgs = Args.size() - firstDataArg;
10450 
10451   if (IgnoreStringsWithoutSpecifiers &&
10452       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10453           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10454     return;
10455 
10456   // Emit a warning if the string literal is truncated and does not contain an
10457   // embedded null character.
10458   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10459     CheckFormatHandler::EmitFormatDiagnostic(
10460         S, inFunctionCall, Args[format_idx],
10461         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10462         FExpr->getBeginLoc(),
10463         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10464     return;
10465   }
10466 
10467   // CHECK: empty format string?
10468   if (StrLen == 0 && numDataArgs > 0) {
10469     CheckFormatHandler::EmitFormatDiagnostic(
10470         S, inFunctionCall, Args[format_idx],
10471         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10472         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10473     return;
10474   }
10475 
10476   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
10477       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
10478       Type == Sema::FST_OSTrace) {
10479     CheckPrintfHandler H(
10480         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
10481         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
10482         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
10483         CheckedVarArgs, UncoveredArg);
10484 
10485     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
10486                                                   S.getLangOpts(),
10487                                                   S.Context.getTargetInfo(),
10488                                             Type == Sema::FST_FreeBSDKPrintf))
10489       H.DoneProcessing();
10490   } else if (Type == Sema::FST_Scanf) {
10491     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10492                         numDataArgs, Str, HasVAListArg, Args, format_idx,
10493                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
10494 
10495     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
10496                                                  S.getLangOpts(),
10497                                                  S.Context.getTargetInfo()))
10498       H.DoneProcessing();
10499   } // TODO: handle other formats
10500 }
10501 
10502 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10503   // Str - The format string.  NOTE: this is NOT null-terminated!
10504   StringRef StrRef = FExpr->getString();
10505   const char *Str = StrRef.data();
10506   // Account for cases where the string literal is truncated in a declaration.
10507   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10508   assert(T && "String literal not of constant array type!");
10509   size_t TypeSize = T->getSize().getZExtValue();
10510   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10511   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10512                                                          getLangOpts(),
10513                                                          Context.getTargetInfo());
10514 }
10515 
10516 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10517 
10518 // Returns the related absolute value function that is larger, of 0 if one
10519 // does not exist.
10520 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10521   switch (AbsFunction) {
10522   default:
10523     return 0;
10524 
10525   case Builtin::BI__builtin_abs:
10526     return Builtin::BI__builtin_labs;
10527   case Builtin::BI__builtin_labs:
10528     return Builtin::BI__builtin_llabs;
10529   case Builtin::BI__builtin_llabs:
10530     return 0;
10531 
10532   case Builtin::BI__builtin_fabsf:
10533     return Builtin::BI__builtin_fabs;
10534   case Builtin::BI__builtin_fabs:
10535     return Builtin::BI__builtin_fabsl;
10536   case Builtin::BI__builtin_fabsl:
10537     return 0;
10538 
10539   case Builtin::BI__builtin_cabsf:
10540     return Builtin::BI__builtin_cabs;
10541   case Builtin::BI__builtin_cabs:
10542     return Builtin::BI__builtin_cabsl;
10543   case Builtin::BI__builtin_cabsl:
10544     return 0;
10545 
10546   case Builtin::BIabs:
10547     return Builtin::BIlabs;
10548   case Builtin::BIlabs:
10549     return Builtin::BIllabs;
10550   case Builtin::BIllabs:
10551     return 0;
10552 
10553   case Builtin::BIfabsf:
10554     return Builtin::BIfabs;
10555   case Builtin::BIfabs:
10556     return Builtin::BIfabsl;
10557   case Builtin::BIfabsl:
10558     return 0;
10559 
10560   case Builtin::BIcabsf:
10561    return Builtin::BIcabs;
10562   case Builtin::BIcabs:
10563     return Builtin::BIcabsl;
10564   case Builtin::BIcabsl:
10565     return 0;
10566   }
10567 }
10568 
10569 // Returns the argument type of the absolute value function.
10570 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10571                                              unsigned AbsType) {
10572   if (AbsType == 0)
10573     return QualType();
10574 
10575   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10576   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10577   if (Error != ASTContext::GE_None)
10578     return QualType();
10579 
10580   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10581   if (!FT)
10582     return QualType();
10583 
10584   if (FT->getNumParams() != 1)
10585     return QualType();
10586 
10587   return FT->getParamType(0);
10588 }
10589 
10590 // Returns the best absolute value function, or zero, based on type and
10591 // current absolute value function.
10592 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10593                                    unsigned AbsFunctionKind) {
10594   unsigned BestKind = 0;
10595   uint64_t ArgSize = Context.getTypeSize(ArgType);
10596   for (unsigned Kind = AbsFunctionKind; Kind != 0;
10597        Kind = getLargerAbsoluteValueFunction(Kind)) {
10598     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10599     if (Context.getTypeSize(ParamType) >= ArgSize) {
10600       if (BestKind == 0)
10601         BestKind = Kind;
10602       else if (Context.hasSameType(ParamType, ArgType)) {
10603         BestKind = Kind;
10604         break;
10605       }
10606     }
10607   }
10608   return BestKind;
10609 }
10610 
10611 enum AbsoluteValueKind {
10612   AVK_Integer,
10613   AVK_Floating,
10614   AVK_Complex
10615 };
10616 
10617 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10618   if (T->isIntegralOrEnumerationType())
10619     return AVK_Integer;
10620   if (T->isRealFloatingType())
10621     return AVK_Floating;
10622   if (T->isAnyComplexType())
10623     return AVK_Complex;
10624 
10625   llvm_unreachable("Type not integer, floating, or complex");
10626 }
10627 
10628 // Changes the absolute value function to a different type.  Preserves whether
10629 // the function is a builtin.
10630 static unsigned changeAbsFunction(unsigned AbsKind,
10631                                   AbsoluteValueKind ValueKind) {
10632   switch (ValueKind) {
10633   case AVK_Integer:
10634     switch (AbsKind) {
10635     default:
10636       return 0;
10637     case Builtin::BI__builtin_fabsf:
10638     case Builtin::BI__builtin_fabs:
10639     case Builtin::BI__builtin_fabsl:
10640     case Builtin::BI__builtin_cabsf:
10641     case Builtin::BI__builtin_cabs:
10642     case Builtin::BI__builtin_cabsl:
10643       return Builtin::BI__builtin_abs;
10644     case Builtin::BIfabsf:
10645     case Builtin::BIfabs:
10646     case Builtin::BIfabsl:
10647     case Builtin::BIcabsf:
10648     case Builtin::BIcabs:
10649     case Builtin::BIcabsl:
10650       return Builtin::BIabs;
10651     }
10652   case AVK_Floating:
10653     switch (AbsKind) {
10654     default:
10655       return 0;
10656     case Builtin::BI__builtin_abs:
10657     case Builtin::BI__builtin_labs:
10658     case Builtin::BI__builtin_llabs:
10659     case Builtin::BI__builtin_cabsf:
10660     case Builtin::BI__builtin_cabs:
10661     case Builtin::BI__builtin_cabsl:
10662       return Builtin::BI__builtin_fabsf;
10663     case Builtin::BIabs:
10664     case Builtin::BIlabs:
10665     case Builtin::BIllabs:
10666     case Builtin::BIcabsf:
10667     case Builtin::BIcabs:
10668     case Builtin::BIcabsl:
10669       return Builtin::BIfabsf;
10670     }
10671   case AVK_Complex:
10672     switch (AbsKind) {
10673     default:
10674       return 0;
10675     case Builtin::BI__builtin_abs:
10676     case Builtin::BI__builtin_labs:
10677     case Builtin::BI__builtin_llabs:
10678     case Builtin::BI__builtin_fabsf:
10679     case Builtin::BI__builtin_fabs:
10680     case Builtin::BI__builtin_fabsl:
10681       return Builtin::BI__builtin_cabsf;
10682     case Builtin::BIabs:
10683     case Builtin::BIlabs:
10684     case Builtin::BIllabs:
10685     case Builtin::BIfabsf:
10686     case Builtin::BIfabs:
10687     case Builtin::BIfabsl:
10688       return Builtin::BIcabsf;
10689     }
10690   }
10691   llvm_unreachable("Unable to convert function");
10692 }
10693 
10694 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10695   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10696   if (!FnInfo)
10697     return 0;
10698 
10699   switch (FDecl->getBuiltinID()) {
10700   default:
10701     return 0;
10702   case Builtin::BI__builtin_abs:
10703   case Builtin::BI__builtin_fabs:
10704   case Builtin::BI__builtin_fabsf:
10705   case Builtin::BI__builtin_fabsl:
10706   case Builtin::BI__builtin_labs:
10707   case Builtin::BI__builtin_llabs:
10708   case Builtin::BI__builtin_cabs:
10709   case Builtin::BI__builtin_cabsf:
10710   case Builtin::BI__builtin_cabsl:
10711   case Builtin::BIabs:
10712   case Builtin::BIlabs:
10713   case Builtin::BIllabs:
10714   case Builtin::BIfabs:
10715   case Builtin::BIfabsf:
10716   case Builtin::BIfabsl:
10717   case Builtin::BIcabs:
10718   case Builtin::BIcabsf:
10719   case Builtin::BIcabsl:
10720     return FDecl->getBuiltinID();
10721   }
10722   llvm_unreachable("Unknown Builtin type");
10723 }
10724 
10725 // If the replacement is valid, emit a note with replacement function.
10726 // Additionally, suggest including the proper header if not already included.
10727 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10728                             unsigned AbsKind, QualType ArgType) {
10729   bool EmitHeaderHint = true;
10730   const char *HeaderName = nullptr;
10731   const char *FunctionName = nullptr;
10732   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10733     FunctionName = "std::abs";
10734     if (ArgType->isIntegralOrEnumerationType()) {
10735       HeaderName = "cstdlib";
10736     } else if (ArgType->isRealFloatingType()) {
10737       HeaderName = "cmath";
10738     } else {
10739       llvm_unreachable("Invalid Type");
10740     }
10741 
10742     // Lookup all std::abs
10743     if (NamespaceDecl *Std = S.getStdNamespace()) {
10744       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10745       R.suppressDiagnostics();
10746       S.LookupQualifiedName(R, Std);
10747 
10748       for (const auto *I : R) {
10749         const FunctionDecl *FDecl = nullptr;
10750         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10751           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10752         } else {
10753           FDecl = dyn_cast<FunctionDecl>(I);
10754         }
10755         if (!FDecl)
10756           continue;
10757 
10758         // Found std::abs(), check that they are the right ones.
10759         if (FDecl->getNumParams() != 1)
10760           continue;
10761 
10762         // Check that the parameter type can handle the argument.
10763         QualType ParamType = FDecl->getParamDecl(0)->getType();
10764         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10765             S.Context.getTypeSize(ArgType) <=
10766                 S.Context.getTypeSize(ParamType)) {
10767           // Found a function, don't need the header hint.
10768           EmitHeaderHint = false;
10769           break;
10770         }
10771       }
10772     }
10773   } else {
10774     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10775     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10776 
10777     if (HeaderName) {
10778       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10779       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10780       R.suppressDiagnostics();
10781       S.LookupName(R, S.getCurScope());
10782 
10783       if (R.isSingleResult()) {
10784         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10785         if (FD && FD->getBuiltinID() == AbsKind) {
10786           EmitHeaderHint = false;
10787         } else {
10788           return;
10789         }
10790       } else if (!R.empty()) {
10791         return;
10792       }
10793     }
10794   }
10795 
10796   S.Diag(Loc, diag::note_replace_abs_function)
10797       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10798 
10799   if (!HeaderName)
10800     return;
10801 
10802   if (!EmitHeaderHint)
10803     return;
10804 
10805   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10806                                                     << FunctionName;
10807 }
10808 
10809 template <std::size_t StrLen>
10810 static bool IsStdFunction(const FunctionDecl *FDecl,
10811                           const char (&Str)[StrLen]) {
10812   if (!FDecl)
10813     return false;
10814   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10815     return false;
10816   if (!FDecl->isInStdNamespace())
10817     return false;
10818 
10819   return true;
10820 }
10821 
10822 // Warn when using the wrong abs() function.
10823 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10824                                       const FunctionDecl *FDecl) {
10825   if (Call->getNumArgs() != 1)
10826     return;
10827 
10828   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10829   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10830   if (AbsKind == 0 && !IsStdAbs)
10831     return;
10832 
10833   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10834   QualType ParamType = Call->getArg(0)->getType();
10835 
10836   // Unsigned types cannot be negative.  Suggest removing the absolute value
10837   // function call.
10838   if (ArgType->isUnsignedIntegerType()) {
10839     const char *FunctionName =
10840         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10841     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10842     Diag(Call->getExprLoc(), diag::note_remove_abs)
10843         << FunctionName
10844         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10845     return;
10846   }
10847 
10848   // Taking the absolute value of a pointer is very suspicious, they probably
10849   // wanted to index into an array, dereference a pointer, call a function, etc.
10850   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10851     unsigned DiagType = 0;
10852     if (ArgType->isFunctionType())
10853       DiagType = 1;
10854     else if (ArgType->isArrayType())
10855       DiagType = 2;
10856 
10857     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10858     return;
10859   }
10860 
10861   // std::abs has overloads which prevent most of the absolute value problems
10862   // from occurring.
10863   if (IsStdAbs)
10864     return;
10865 
10866   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10867   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10868 
10869   // The argument and parameter are the same kind.  Check if they are the right
10870   // size.
10871   if (ArgValueKind == ParamValueKind) {
10872     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10873       return;
10874 
10875     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10876     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10877         << FDecl << ArgType << ParamType;
10878 
10879     if (NewAbsKind == 0)
10880       return;
10881 
10882     emitReplacement(*this, Call->getExprLoc(),
10883                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10884     return;
10885   }
10886 
10887   // ArgValueKind != ParamValueKind
10888   // The wrong type of absolute value function was used.  Attempt to find the
10889   // proper one.
10890   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10891   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10892   if (NewAbsKind == 0)
10893     return;
10894 
10895   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10896       << FDecl << ParamValueKind << ArgValueKind;
10897 
10898   emitReplacement(*this, Call->getExprLoc(),
10899                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10900 }
10901 
10902 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10903 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10904                                 const FunctionDecl *FDecl) {
10905   if (!Call || !FDecl) return;
10906 
10907   // Ignore template specializations and macros.
10908   if (inTemplateInstantiation()) return;
10909   if (Call->getExprLoc().isMacroID()) return;
10910 
10911   // Only care about the one template argument, two function parameter std::max
10912   if (Call->getNumArgs() != 2) return;
10913   if (!IsStdFunction(FDecl, "max")) return;
10914   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10915   if (!ArgList) return;
10916   if (ArgList->size() != 1) return;
10917 
10918   // Check that template type argument is unsigned integer.
10919   const auto& TA = ArgList->get(0);
10920   if (TA.getKind() != TemplateArgument::Type) return;
10921   QualType ArgType = TA.getAsType();
10922   if (!ArgType->isUnsignedIntegerType()) return;
10923 
10924   // See if either argument is a literal zero.
10925   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10926     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10927     if (!MTE) return false;
10928     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10929     if (!Num) return false;
10930     if (Num->getValue() != 0) return false;
10931     return true;
10932   };
10933 
10934   const Expr *FirstArg = Call->getArg(0);
10935   const Expr *SecondArg = Call->getArg(1);
10936   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10937   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10938 
10939   // Only warn when exactly one argument is zero.
10940   if (IsFirstArgZero == IsSecondArgZero) return;
10941 
10942   SourceRange FirstRange = FirstArg->getSourceRange();
10943   SourceRange SecondRange = SecondArg->getSourceRange();
10944 
10945   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10946 
10947   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10948       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10949 
10950   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10951   SourceRange RemovalRange;
10952   if (IsFirstArgZero) {
10953     RemovalRange = SourceRange(FirstRange.getBegin(),
10954                                SecondRange.getBegin().getLocWithOffset(-1));
10955   } else {
10956     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10957                                SecondRange.getEnd());
10958   }
10959 
10960   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10961         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10962         << FixItHint::CreateRemoval(RemovalRange);
10963 }
10964 
10965 //===--- CHECK: Standard memory functions ---------------------------------===//
10966 
10967 /// Takes the expression passed to the size_t parameter of functions
10968 /// such as memcmp, strncat, etc and warns if it's a comparison.
10969 ///
10970 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10971 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10972                                            IdentifierInfo *FnName,
10973                                            SourceLocation FnLoc,
10974                                            SourceLocation RParenLoc) {
10975   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10976   if (!Size)
10977     return false;
10978 
10979   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10980   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10981     return false;
10982 
10983   SourceRange SizeRange = Size->getSourceRange();
10984   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10985       << SizeRange << FnName;
10986   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10987       << FnName
10988       << FixItHint::CreateInsertion(
10989              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10990       << FixItHint::CreateRemoval(RParenLoc);
10991   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10992       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10993       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10994                                     ")");
10995 
10996   return true;
10997 }
10998 
10999 /// Determine whether the given type is or contains a dynamic class type
11000 /// (e.g., whether it has a vtable).
11001 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
11002                                                      bool &IsContained) {
11003   // Look through array types while ignoring qualifiers.
11004   const Type *Ty = T->getBaseElementTypeUnsafe();
11005   IsContained = false;
11006 
11007   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
11008   RD = RD ? RD->getDefinition() : nullptr;
11009   if (!RD || RD->isInvalidDecl())
11010     return nullptr;
11011 
11012   if (RD->isDynamicClass())
11013     return RD;
11014 
11015   // Check all the fields.  If any bases were dynamic, the class is dynamic.
11016   // It's impossible for a class to transitively contain itself by value, so
11017   // infinite recursion is impossible.
11018   for (auto *FD : RD->fields()) {
11019     bool SubContained;
11020     if (const CXXRecordDecl *ContainedRD =
11021             getContainedDynamicClass(FD->getType(), SubContained)) {
11022       IsContained = true;
11023       return ContainedRD;
11024     }
11025   }
11026 
11027   return nullptr;
11028 }
11029 
11030 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
11031   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
11032     if (Unary->getKind() == UETT_SizeOf)
11033       return Unary;
11034   return nullptr;
11035 }
11036 
11037 /// If E is a sizeof expression, returns its argument expression,
11038 /// otherwise returns NULL.
11039 static const Expr *getSizeOfExprArg(const Expr *E) {
11040   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
11041     if (!SizeOf->isArgumentType())
11042       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
11043   return nullptr;
11044 }
11045 
11046 /// If E is a sizeof expression, returns its argument type.
11047 static QualType getSizeOfArgType(const Expr *E) {
11048   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
11049     return SizeOf->getTypeOfArgument();
11050   return QualType();
11051 }
11052 
11053 namespace {
11054 
11055 struct SearchNonTrivialToInitializeField
11056     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
11057   using Super =
11058       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
11059 
11060   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
11061 
11062   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
11063                      SourceLocation SL) {
11064     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
11065       asDerived().visitArray(PDIK, AT, SL);
11066       return;
11067     }
11068 
11069     Super::visitWithKind(PDIK, FT, SL);
11070   }
11071 
11072   void visitARCStrong(QualType FT, SourceLocation SL) {
11073     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
11074   }
11075   void visitARCWeak(QualType FT, SourceLocation SL) {
11076     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
11077   }
11078   void visitStruct(QualType FT, SourceLocation SL) {
11079     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
11080       visit(FD->getType(), FD->getLocation());
11081   }
11082   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
11083                   const ArrayType *AT, SourceLocation SL) {
11084     visit(getContext().getBaseElementType(AT), SL);
11085   }
11086   void visitTrivial(QualType FT, SourceLocation SL) {}
11087 
11088   static void diag(QualType RT, const Expr *E, Sema &S) {
11089     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
11090   }
11091 
11092   ASTContext &getContext() { return S.getASTContext(); }
11093 
11094   const Expr *E;
11095   Sema &S;
11096 };
11097 
11098 struct SearchNonTrivialToCopyField
11099     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
11100   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
11101 
11102   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
11103 
11104   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
11105                      SourceLocation SL) {
11106     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
11107       asDerived().visitArray(PCK, AT, SL);
11108       return;
11109     }
11110 
11111     Super::visitWithKind(PCK, FT, SL);
11112   }
11113 
11114   void visitARCStrong(QualType FT, SourceLocation SL) {
11115     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
11116   }
11117   void visitARCWeak(QualType FT, SourceLocation SL) {
11118     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
11119   }
11120   void visitStruct(QualType FT, SourceLocation SL) {
11121     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
11122       visit(FD->getType(), FD->getLocation());
11123   }
11124   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
11125                   SourceLocation SL) {
11126     visit(getContext().getBaseElementType(AT), SL);
11127   }
11128   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
11129                 SourceLocation SL) {}
11130   void visitTrivial(QualType FT, SourceLocation SL) {}
11131   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
11132 
11133   static void diag(QualType RT, const Expr *E, Sema &S) {
11134     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
11135   }
11136 
11137   ASTContext &getContext() { return S.getASTContext(); }
11138 
11139   const Expr *E;
11140   Sema &S;
11141 };
11142 
11143 }
11144 
11145 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
11146 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
11147   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
11148 
11149   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
11150     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
11151       return false;
11152 
11153     return doesExprLikelyComputeSize(BO->getLHS()) ||
11154            doesExprLikelyComputeSize(BO->getRHS());
11155   }
11156 
11157   return getAsSizeOfExpr(SizeofExpr) != nullptr;
11158 }
11159 
11160 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
11161 ///
11162 /// \code
11163 ///   #define MACRO 0
11164 ///   foo(MACRO);
11165 ///   foo(0);
11166 /// \endcode
11167 ///
11168 /// This should return true for the first call to foo, but not for the second
11169 /// (regardless of whether foo is a macro or function).
11170 static bool isArgumentExpandedFromMacro(SourceManager &SM,
11171                                         SourceLocation CallLoc,
11172                                         SourceLocation ArgLoc) {
11173   if (!CallLoc.isMacroID())
11174     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
11175 
11176   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
11177          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
11178 }
11179 
11180 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11181 /// last two arguments transposed.
11182 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11183   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11184     return;
11185 
11186   const Expr *SizeArg =
11187     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11188 
11189   auto isLiteralZero = [](const Expr *E) {
11190     return (isa<IntegerLiteral>(E) &&
11191             cast<IntegerLiteral>(E)->getValue() == 0) ||
11192            (isa<CharacterLiteral>(E) &&
11193             cast<CharacterLiteral>(E)->getValue() == 0);
11194   };
11195 
11196   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11197   SourceLocation CallLoc = Call->getRParenLoc();
11198   SourceManager &SM = S.getSourceManager();
11199   if (isLiteralZero(SizeArg) &&
11200       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
11201 
11202     SourceLocation DiagLoc = SizeArg->getExprLoc();
11203 
11204     // Some platforms #define bzero to __builtin_memset. See if this is the
11205     // case, and if so, emit a better diagnostic.
11206     if (BId == Builtin::BIbzero ||
11207         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
11208                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
11209       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
11210       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
11211     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
11212       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
11213       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
11214     }
11215     return;
11216   }
11217 
11218   // If the second argument to a memset is a sizeof expression and the third
11219   // isn't, this is also likely an error. This should catch
11220   // 'memset(buf, sizeof(buf), 0xff)'.
11221   if (BId == Builtin::BImemset &&
11222       doesExprLikelyComputeSize(Call->getArg(1)) &&
11223       !doesExprLikelyComputeSize(Call->getArg(2))) {
11224     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
11225     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
11226     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
11227     return;
11228   }
11229 }
11230 
11231 /// Check for dangerous or invalid arguments to memset().
11232 ///
11233 /// This issues warnings on known problematic, dangerous or unspecified
11234 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
11235 /// function calls.
11236 ///
11237 /// \param Call The call expression to diagnose.
11238 void Sema::CheckMemaccessArguments(const CallExpr *Call,
11239                                    unsigned BId,
11240                                    IdentifierInfo *FnName) {
11241   assert(BId != 0);
11242 
11243   // It is possible to have a non-standard definition of memset.  Validate
11244   // we have enough arguments, and if not, abort further checking.
11245   unsigned ExpectedNumArgs =
11246       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11247   if (Call->getNumArgs() < ExpectedNumArgs)
11248     return;
11249 
11250   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11251                       BId == Builtin::BIstrndup ? 1 : 2);
11252   unsigned LenArg =
11253       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11254   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
11255 
11256   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
11257                                      Call->getBeginLoc(), Call->getRParenLoc()))
11258     return;
11259 
11260   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11261   CheckMemaccessSize(*this, BId, Call);
11262 
11263   // We have special checking when the length is a sizeof expression.
11264   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
11265   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
11266   llvm::FoldingSetNodeID SizeOfArgID;
11267 
11268   // Although widely used, 'bzero' is not a standard function. Be more strict
11269   // with the argument types before allowing diagnostics and only allow the
11270   // form bzero(ptr, sizeof(...)).
11271   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
11272   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11273     return;
11274 
11275   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11276     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
11277     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
11278 
11279     QualType DestTy = Dest->getType();
11280     QualType PointeeTy;
11281     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11282       PointeeTy = DestPtrTy->getPointeeType();
11283 
11284       // Never warn about void type pointers. This can be used to suppress
11285       // false positives.
11286       if (PointeeTy->isVoidType())
11287         continue;
11288 
11289       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11290       // actually comparing the expressions for equality. Because computing the
11291       // expression IDs can be expensive, we only do this if the diagnostic is
11292       // enabled.
11293       if (SizeOfArg &&
11294           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11295                            SizeOfArg->getExprLoc())) {
11296         // We only compute IDs for expressions if the warning is enabled, and
11297         // cache the sizeof arg's ID.
11298         if (SizeOfArgID == llvm::FoldingSetNodeID())
11299           SizeOfArg->Profile(SizeOfArgID, Context, true);
11300         llvm::FoldingSetNodeID DestID;
11301         Dest->Profile(DestID, Context, true);
11302         if (DestID == SizeOfArgID) {
11303           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11304           //       over sizeof(src) as well.
11305           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11306           StringRef ReadableName = FnName->getName();
11307 
11308           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
11309             if (UnaryOp->getOpcode() == UO_AddrOf)
11310               ActionIdx = 1; // If its an address-of operator, just remove it.
11311           if (!PointeeTy->isIncompleteType() &&
11312               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11313             ActionIdx = 2; // If the pointee's size is sizeof(char),
11314                            // suggest an explicit length.
11315 
11316           // If the function is defined as a builtin macro, do not show macro
11317           // expansion.
11318           SourceLocation SL = SizeOfArg->getExprLoc();
11319           SourceRange DSR = Dest->getSourceRange();
11320           SourceRange SSR = SizeOfArg->getSourceRange();
11321           SourceManager &SM = getSourceManager();
11322 
11323           if (SM.isMacroArgExpansion(SL)) {
11324             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11325             SL = SM.getSpellingLoc(SL);
11326             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11327                              SM.getSpellingLoc(DSR.getEnd()));
11328             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11329                              SM.getSpellingLoc(SSR.getEnd()));
11330           }
11331 
11332           DiagRuntimeBehavior(SL, SizeOfArg,
11333                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11334                                 << ReadableName
11335                                 << PointeeTy
11336                                 << DestTy
11337                                 << DSR
11338                                 << SSR);
11339           DiagRuntimeBehavior(SL, SizeOfArg,
11340                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11341                                 << ActionIdx
11342                                 << SSR);
11343 
11344           break;
11345         }
11346       }
11347 
11348       // Also check for cases where the sizeof argument is the exact same
11349       // type as the memory argument, and where it points to a user-defined
11350       // record type.
11351       if (SizeOfArgTy != QualType()) {
11352         if (PointeeTy->isRecordType() &&
11353             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11354           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11355                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
11356                                 << FnName << SizeOfArgTy << ArgIdx
11357                                 << PointeeTy << Dest->getSourceRange()
11358                                 << LenExpr->getSourceRange());
11359           break;
11360         }
11361       }
11362     } else if (DestTy->isArrayType()) {
11363       PointeeTy = DestTy;
11364     }
11365 
11366     if (PointeeTy == QualType())
11367       continue;
11368 
11369     // Always complain about dynamic classes.
11370     bool IsContained;
11371     if (const CXXRecordDecl *ContainedRD =
11372             getContainedDynamicClass(PointeeTy, IsContained)) {
11373 
11374       unsigned OperationType = 0;
11375       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11376       // "overwritten" if we're warning about the destination for any call
11377       // but memcmp; otherwise a verb appropriate to the call.
11378       if (ArgIdx != 0 || IsCmp) {
11379         if (BId == Builtin::BImemcpy)
11380           OperationType = 1;
11381         else if(BId == Builtin::BImemmove)
11382           OperationType = 2;
11383         else if (IsCmp)
11384           OperationType = 3;
11385       }
11386 
11387       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11388                           PDiag(diag::warn_dyn_class_memaccess)
11389                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11390                               << IsContained << ContainedRD << OperationType
11391                               << Call->getCallee()->getSourceRange());
11392     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11393              BId != Builtin::BImemset)
11394       DiagRuntimeBehavior(
11395         Dest->getExprLoc(), Dest,
11396         PDiag(diag::warn_arc_object_memaccess)
11397           << ArgIdx << FnName << PointeeTy
11398           << Call->getCallee()->getSourceRange());
11399     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
11400       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11401           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
11402         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11403                             PDiag(diag::warn_cstruct_memaccess)
11404                                 << ArgIdx << FnName << PointeeTy << 0);
11405         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11406       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11407                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
11408         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11409                             PDiag(diag::warn_cstruct_memaccess)
11410                                 << ArgIdx << FnName << PointeeTy << 1);
11411         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11412       } else {
11413         continue;
11414       }
11415     } else
11416       continue;
11417 
11418     DiagRuntimeBehavior(
11419       Dest->getExprLoc(), Dest,
11420       PDiag(diag::note_bad_memaccess_silence)
11421         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11422     break;
11423   }
11424 }
11425 
11426 // A little helper routine: ignore addition and subtraction of integer literals.
11427 // This intentionally does not ignore all integer constant expressions because
11428 // we don't want to remove sizeof().
11429 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11430   Ex = Ex->IgnoreParenCasts();
11431 
11432   while (true) {
11433     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11434     if (!BO || !BO->isAdditiveOp())
11435       break;
11436 
11437     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11438     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11439 
11440     if (isa<IntegerLiteral>(RHS))
11441       Ex = LHS;
11442     else if (isa<IntegerLiteral>(LHS))
11443       Ex = RHS;
11444     else
11445       break;
11446   }
11447 
11448   return Ex;
11449 }
11450 
11451 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11452                                                       ASTContext &Context) {
11453   // Only handle constant-sized or VLAs, but not flexible members.
11454   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11455     // Only issue the FIXIT for arrays of size > 1.
11456     if (CAT->getSize().getSExtValue() <= 1)
11457       return false;
11458   } else if (!Ty->isVariableArrayType()) {
11459     return false;
11460   }
11461   return true;
11462 }
11463 
11464 // Warn if the user has made the 'size' argument to strlcpy or strlcat
11465 // be the size of the source, instead of the destination.
11466 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11467                                     IdentifierInfo *FnName) {
11468 
11469   // Don't crash if the user has the wrong number of arguments
11470   unsigned NumArgs = Call->getNumArgs();
11471   if ((NumArgs != 3) && (NumArgs != 4))
11472     return;
11473 
11474   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11475   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11476   const Expr *CompareWithSrc = nullptr;
11477 
11478   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11479                                      Call->getBeginLoc(), Call->getRParenLoc()))
11480     return;
11481 
11482   // Look for 'strlcpy(dst, x, sizeof(x))'
11483   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11484     CompareWithSrc = Ex;
11485   else {
11486     // Look for 'strlcpy(dst, x, strlen(x))'
11487     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11488       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11489           SizeCall->getNumArgs() == 1)
11490         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11491     }
11492   }
11493 
11494   if (!CompareWithSrc)
11495     return;
11496 
11497   // Determine if the argument to sizeof/strlen is equal to the source
11498   // argument.  In principle there's all kinds of things you could do
11499   // here, for instance creating an == expression and evaluating it with
11500   // EvaluateAsBooleanCondition, but this uses a more direct technique:
11501   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11502   if (!SrcArgDRE)
11503     return;
11504 
11505   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11506   if (!CompareWithSrcDRE ||
11507       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11508     return;
11509 
11510   const Expr *OriginalSizeArg = Call->getArg(2);
11511   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11512       << OriginalSizeArg->getSourceRange() << FnName;
11513 
11514   // Output a FIXIT hint if the destination is an array (rather than a
11515   // pointer to an array).  This could be enhanced to handle some
11516   // pointers if we know the actual size, like if DstArg is 'array+2'
11517   // we could say 'sizeof(array)-2'.
11518   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11519   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
11520     return;
11521 
11522   SmallString<128> sizeString;
11523   llvm::raw_svector_ostream OS(sizeString);
11524   OS << "sizeof(";
11525   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11526   OS << ")";
11527 
11528   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11529       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11530                                       OS.str());
11531 }
11532 
11533 /// Check if two expressions refer to the same declaration.
11534 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11535   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11536     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11537       return D1->getDecl() == D2->getDecl();
11538   return false;
11539 }
11540 
11541 static const Expr *getStrlenExprArg(const Expr *E) {
11542   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11543     const FunctionDecl *FD = CE->getDirectCallee();
11544     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11545       return nullptr;
11546     return CE->getArg(0)->IgnoreParenCasts();
11547   }
11548   return nullptr;
11549 }
11550 
11551 // Warn on anti-patterns as the 'size' argument to strncat.
11552 // The correct size argument should look like following:
11553 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
11554 void Sema::CheckStrncatArguments(const CallExpr *CE,
11555                                  IdentifierInfo *FnName) {
11556   // Don't crash if the user has the wrong number of arguments.
11557   if (CE->getNumArgs() < 3)
11558     return;
11559   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11560   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11561   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11562 
11563   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11564                                      CE->getRParenLoc()))
11565     return;
11566 
11567   // Identify common expressions, which are wrongly used as the size argument
11568   // to strncat and may lead to buffer overflows.
11569   unsigned PatternType = 0;
11570   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11571     // - sizeof(dst)
11572     if (referToTheSameDecl(SizeOfArg, DstArg))
11573       PatternType = 1;
11574     // - sizeof(src)
11575     else if (referToTheSameDecl(SizeOfArg, SrcArg))
11576       PatternType = 2;
11577   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11578     if (BE->getOpcode() == BO_Sub) {
11579       const Expr *L = BE->getLHS()->IgnoreParenCasts();
11580       const Expr *R = BE->getRHS()->IgnoreParenCasts();
11581       // - sizeof(dst) - strlen(dst)
11582       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11583           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
11584         PatternType = 1;
11585       // - sizeof(src) - (anything)
11586       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11587         PatternType = 2;
11588     }
11589   }
11590 
11591   if (PatternType == 0)
11592     return;
11593 
11594   // Generate the diagnostic.
11595   SourceLocation SL = LenArg->getBeginLoc();
11596   SourceRange SR = LenArg->getSourceRange();
11597   SourceManager &SM = getSourceManager();
11598 
11599   // If the function is defined as a builtin macro, do not show macro expansion.
11600   if (SM.isMacroArgExpansion(SL)) {
11601     SL = SM.getSpellingLoc(SL);
11602     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11603                      SM.getSpellingLoc(SR.getEnd()));
11604   }
11605 
11606   // Check if the destination is an array (rather than a pointer to an array).
11607   QualType DstTy = DstArg->getType();
11608   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11609                                                                     Context);
11610   if (!isKnownSizeArray) {
11611     if (PatternType == 1)
11612       Diag(SL, diag::warn_strncat_wrong_size) << SR;
11613     else
11614       Diag(SL, diag::warn_strncat_src_size) << SR;
11615     return;
11616   }
11617 
11618   if (PatternType == 1)
11619     Diag(SL, diag::warn_strncat_large_size) << SR;
11620   else
11621     Diag(SL, diag::warn_strncat_src_size) << SR;
11622 
11623   SmallString<128> sizeString;
11624   llvm::raw_svector_ostream OS(sizeString);
11625   OS << "sizeof(";
11626   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11627   OS << ") - ";
11628   OS << "strlen(";
11629   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11630   OS << ") - 1";
11631 
11632   Diag(SL, diag::note_strncat_wrong_size)
11633     << FixItHint::CreateReplacement(SR, OS.str());
11634 }
11635 
11636 namespace {
11637 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11638                                 const UnaryOperator *UnaryExpr, const Decl *D) {
11639   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
11640     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11641         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11642     return;
11643   }
11644 }
11645 
11646 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11647                                  const UnaryOperator *UnaryExpr) {
11648   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11649     const Decl *D = Lvalue->getDecl();
11650     if (isa<DeclaratorDecl>(D))
11651       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11652         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11653   }
11654 
11655   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11656     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11657                                       Lvalue->getMemberDecl());
11658 }
11659 
11660 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11661                             const UnaryOperator *UnaryExpr) {
11662   const auto *Lambda = dyn_cast<LambdaExpr>(
11663       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11664   if (!Lambda)
11665     return;
11666 
11667   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11668       << CalleeName << 2 /*object: lambda expression*/;
11669 }
11670 
11671 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11672                                   const DeclRefExpr *Lvalue) {
11673   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11674   if (Var == nullptr)
11675     return;
11676 
11677   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11678       << CalleeName << 0 /*object: */ << Var;
11679 }
11680 
11681 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11682                             const CastExpr *Cast) {
11683   SmallString<128> SizeString;
11684   llvm::raw_svector_ostream OS(SizeString);
11685 
11686   clang::CastKind Kind = Cast->getCastKind();
11687   if (Kind == clang::CK_BitCast &&
11688       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11689     return;
11690   if (Kind == clang::CK_IntegralToPointer &&
11691       !isa<IntegerLiteral>(
11692           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11693     return;
11694 
11695   switch (Cast->getCastKind()) {
11696   case clang::CK_BitCast:
11697   case clang::CK_IntegralToPointer:
11698   case clang::CK_FunctionToPointerDecay:
11699     OS << '\'';
11700     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11701     OS << '\'';
11702     break;
11703   default:
11704     return;
11705   }
11706 
11707   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11708       << CalleeName << 0 /*object: */ << OS.str();
11709 }
11710 } // namespace
11711 
11712 /// Alerts the user that they are attempting to free a non-malloc'd object.
11713 void Sema::CheckFreeArguments(const CallExpr *E) {
11714   const std::string CalleeName =
11715       cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11716 
11717   { // Prefer something that doesn't involve a cast to make things simpler.
11718     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11719     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11720       switch (UnaryExpr->getOpcode()) {
11721       case UnaryOperator::Opcode::UO_AddrOf:
11722         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11723       case UnaryOperator::Opcode::UO_Plus:
11724         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11725       default:
11726         break;
11727       }
11728 
11729     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11730       if (Lvalue->getType()->isArrayType())
11731         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11732 
11733     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11734       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11735           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11736       return;
11737     }
11738 
11739     if (isa<BlockExpr>(Arg)) {
11740       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11741           << CalleeName << 1 /*object: block*/;
11742       return;
11743     }
11744   }
11745   // Maybe the cast was important, check after the other cases.
11746   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11747     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11748 }
11749 
11750 void
11751 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11752                          SourceLocation ReturnLoc,
11753                          bool isObjCMethod,
11754                          const AttrVec *Attrs,
11755                          const FunctionDecl *FD) {
11756   // Check if the return value is null but should not be.
11757   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11758        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11759       CheckNonNullExpr(*this, RetValExp))
11760     Diag(ReturnLoc, diag::warn_null_ret)
11761       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11762 
11763   // C++11 [basic.stc.dynamic.allocation]p4:
11764   //   If an allocation function declared with a non-throwing
11765   //   exception-specification fails to allocate storage, it shall return
11766   //   a null pointer. Any other allocation function that fails to allocate
11767   //   storage shall indicate failure only by throwing an exception [...]
11768   if (FD) {
11769     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11770     if (Op == OO_New || Op == OO_Array_New) {
11771       const FunctionProtoType *Proto
11772         = FD->getType()->castAs<FunctionProtoType>();
11773       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11774           CheckNonNullExpr(*this, RetValExp))
11775         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11776           << FD << getLangOpts().CPlusPlus11;
11777     }
11778   }
11779 
11780   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11781   // here prevent the user from using a PPC MMA type as trailing return type.
11782   if (Context.getTargetInfo().getTriple().isPPC64())
11783     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11784 }
11785 
11786 /// Check for comparisons of floating-point values using == and !=. Issue a
11787 /// warning if the comparison is not likely to do what the programmer intended.
11788 void Sema::CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
11789                                 BinaryOperatorKind Opcode) {
11790   // Match and capture subexpressions such as "(float) X == 0.1".
11791   FloatingLiteral *FPLiteral;
11792   CastExpr *FPCast;
11793   auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {
11794     FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11795     FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11796     return FPLiteral && FPCast;
11797   };
11798 
11799   if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11800     auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11801     auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11802     if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11803         TargetTy->isFloatingPoint()) {
11804       bool Lossy;
11805       llvm::APFloat TargetC = FPLiteral->getValue();
11806       TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11807                       llvm::APFloat::rmNearestTiesToEven, &Lossy);
11808       if (Lossy) {
11809         // If the literal cannot be represented in the source type, then a
11810         // check for == is always false and check for != is always true.
11811         Diag(Loc, diag::warn_float_compare_literal)
11812             << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11813             << LHS->getSourceRange() << RHS->getSourceRange();
11814         return;
11815       }
11816     }
11817   }
11818 
11819   // Match a more general floating-point equality comparison (-Wfloat-equal).
11820   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11821   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11822 
11823   // Special case: check for x == x (which is OK).
11824   // Do not emit warnings for such cases.
11825   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11826     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11827       if (DRL->getDecl() == DRR->getDecl())
11828         return;
11829 
11830   // Special case: check for comparisons against literals that can be exactly
11831   //  represented by APFloat.  In such cases, do not emit a warning.  This
11832   //  is a heuristic: often comparison against such literals are used to
11833   //  detect if a value in a variable has not changed.  This clearly can
11834   //  lead to false negatives.
11835   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11836     if (FLL->isExact())
11837       return;
11838   } else
11839     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11840       if (FLR->isExact())
11841         return;
11842 
11843   // Check for comparisons with builtin types.
11844   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11845     if (CL->getBuiltinCallee())
11846       return;
11847 
11848   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11849     if (CR->getBuiltinCallee())
11850       return;
11851 
11852   // Emit the diagnostic.
11853   Diag(Loc, diag::warn_floatingpoint_eq)
11854     << LHS->getSourceRange() << RHS->getSourceRange();
11855 }
11856 
11857 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11858 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11859 
11860 namespace {
11861 
11862 /// Structure recording the 'active' range of an integer-valued
11863 /// expression.
11864 struct IntRange {
11865   /// The number of bits active in the int. Note that this includes exactly one
11866   /// sign bit if !NonNegative.
11867   unsigned Width;
11868 
11869   /// True if the int is known not to have negative values. If so, all leading
11870   /// bits before Width are known zero, otherwise they are known to be the
11871   /// same as the MSB within Width.
11872   bool NonNegative;
11873 
11874   IntRange(unsigned Width, bool NonNegative)
11875       : Width(Width), NonNegative(NonNegative) {}
11876 
11877   /// Number of bits excluding the sign bit.
11878   unsigned valueBits() const {
11879     return NonNegative ? Width : Width - 1;
11880   }
11881 
11882   /// Returns the range of the bool type.
11883   static IntRange forBoolType() {
11884     return IntRange(1, true);
11885   }
11886 
11887   /// Returns the range of an opaque value of the given integral type.
11888   static IntRange forValueOfType(ASTContext &C, QualType T) {
11889     return forValueOfCanonicalType(C,
11890                           T->getCanonicalTypeInternal().getTypePtr());
11891   }
11892 
11893   /// Returns the range of an opaque value of a canonical integral type.
11894   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11895     assert(T->isCanonicalUnqualified());
11896 
11897     if (const VectorType *VT = dyn_cast<VectorType>(T))
11898       T = VT->getElementType().getTypePtr();
11899     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11900       T = CT->getElementType().getTypePtr();
11901     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11902       T = AT->getValueType().getTypePtr();
11903 
11904     if (!C.getLangOpts().CPlusPlus) {
11905       // For enum types in C code, use the underlying datatype.
11906       if (const EnumType *ET = dyn_cast<EnumType>(T))
11907         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11908     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11909       // For enum types in C++, use the known bit width of the enumerators.
11910       EnumDecl *Enum = ET->getDecl();
11911       // In C++11, enums can have a fixed underlying type. Use this type to
11912       // compute the range.
11913       if (Enum->isFixed()) {
11914         return IntRange(C.getIntWidth(QualType(T, 0)),
11915                         !ET->isSignedIntegerOrEnumerationType());
11916       }
11917 
11918       unsigned NumPositive = Enum->getNumPositiveBits();
11919       unsigned NumNegative = Enum->getNumNegativeBits();
11920 
11921       if (NumNegative == 0)
11922         return IntRange(NumPositive, true/*NonNegative*/);
11923       else
11924         return IntRange(std::max(NumPositive + 1, NumNegative),
11925                         false/*NonNegative*/);
11926     }
11927 
11928     if (const auto *EIT = dyn_cast<BitIntType>(T))
11929       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11930 
11931     const BuiltinType *BT = cast<BuiltinType>(T);
11932     assert(BT->isInteger());
11933 
11934     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11935   }
11936 
11937   /// Returns the "target" range of a canonical integral type, i.e.
11938   /// the range of values expressible in the type.
11939   ///
11940   /// This matches forValueOfCanonicalType except that enums have the
11941   /// full range of their type, not the range of their enumerators.
11942   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11943     assert(T->isCanonicalUnqualified());
11944 
11945     if (const VectorType *VT = dyn_cast<VectorType>(T))
11946       T = VT->getElementType().getTypePtr();
11947     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11948       T = CT->getElementType().getTypePtr();
11949     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11950       T = AT->getValueType().getTypePtr();
11951     if (const EnumType *ET = dyn_cast<EnumType>(T))
11952       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11953 
11954     if (const auto *EIT = dyn_cast<BitIntType>(T))
11955       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11956 
11957     const BuiltinType *BT = cast<BuiltinType>(T);
11958     assert(BT->isInteger());
11959 
11960     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11961   }
11962 
11963   /// Returns the supremum of two ranges: i.e. their conservative merge.
11964   static IntRange join(IntRange L, IntRange R) {
11965     bool Unsigned = L.NonNegative && R.NonNegative;
11966     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11967                     L.NonNegative && R.NonNegative);
11968   }
11969 
11970   /// Return the range of a bitwise-AND of the two ranges.
11971   static IntRange bit_and(IntRange L, IntRange R) {
11972     unsigned Bits = std::max(L.Width, R.Width);
11973     bool NonNegative = false;
11974     if (L.NonNegative) {
11975       Bits = std::min(Bits, L.Width);
11976       NonNegative = true;
11977     }
11978     if (R.NonNegative) {
11979       Bits = std::min(Bits, R.Width);
11980       NonNegative = true;
11981     }
11982     return IntRange(Bits, NonNegative);
11983   }
11984 
11985   /// Return the range of a sum of the two ranges.
11986   static IntRange sum(IntRange L, IntRange R) {
11987     bool Unsigned = L.NonNegative && R.NonNegative;
11988     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11989                     Unsigned);
11990   }
11991 
11992   /// Return the range of a difference of the two ranges.
11993   static IntRange difference(IntRange L, IntRange R) {
11994     // We need a 1-bit-wider range if:
11995     //   1) LHS can be negative: least value can be reduced.
11996     //   2) RHS can be negative: greatest value can be increased.
11997     bool CanWiden = !L.NonNegative || !R.NonNegative;
11998     bool Unsigned = L.NonNegative && R.Width == 0;
11999     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
12000                         !Unsigned,
12001                     Unsigned);
12002   }
12003 
12004   /// Return the range of a product of the two ranges.
12005   static IntRange product(IntRange L, IntRange R) {
12006     // If both LHS and RHS can be negative, we can form
12007     //   -2^L * -2^R = 2^(L + R)
12008     // which requires L + R + 1 value bits to represent.
12009     bool CanWiden = !L.NonNegative && !R.NonNegative;
12010     bool Unsigned = L.NonNegative && R.NonNegative;
12011     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
12012                     Unsigned);
12013   }
12014 
12015   /// Return the range of a remainder operation between the two ranges.
12016   static IntRange rem(IntRange L, IntRange R) {
12017     // The result of a remainder can't be larger than the result of
12018     // either side. The sign of the result is the sign of the LHS.
12019     bool Unsigned = L.NonNegative;
12020     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
12021                     Unsigned);
12022   }
12023 };
12024 
12025 } // namespace
12026 
12027 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
12028                               unsigned MaxWidth) {
12029   if (value.isSigned() && value.isNegative())
12030     return IntRange(value.getMinSignedBits(), false);
12031 
12032   if (value.getBitWidth() > MaxWidth)
12033     value = value.trunc(MaxWidth);
12034 
12035   // isNonNegative() just checks the sign bit without considering
12036   // signedness.
12037   return IntRange(value.getActiveBits(), true);
12038 }
12039 
12040 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
12041                               unsigned MaxWidth) {
12042   if (result.isInt())
12043     return GetValueRange(C, result.getInt(), MaxWidth);
12044 
12045   if (result.isVector()) {
12046     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
12047     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
12048       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
12049       R = IntRange::join(R, El);
12050     }
12051     return R;
12052   }
12053 
12054   if (result.isComplexInt()) {
12055     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
12056     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
12057     return IntRange::join(R, I);
12058   }
12059 
12060   // This can happen with lossless casts to intptr_t of "based" lvalues.
12061   // Assume it might use arbitrary bits.
12062   // FIXME: The only reason we need to pass the type in here is to get
12063   // the sign right on this one case.  It would be nice if APValue
12064   // preserved this.
12065   assert(result.isLValue() || result.isAddrLabelDiff());
12066   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
12067 }
12068 
12069 static QualType GetExprType(const Expr *E) {
12070   QualType Ty = E->getType();
12071   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
12072     Ty = AtomicRHS->getValueType();
12073   return Ty;
12074 }
12075 
12076 /// Pseudo-evaluate the given integer expression, estimating the
12077 /// range of values it might take.
12078 ///
12079 /// \param MaxWidth The width to which the value will be truncated.
12080 /// \param Approximate If \c true, return a likely range for the result: in
12081 ///        particular, assume that arithmetic on narrower types doesn't leave
12082 ///        those types. If \c false, return a range including all possible
12083 ///        result values.
12084 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
12085                              bool InConstantContext, bool Approximate) {
12086   E = E->IgnoreParens();
12087 
12088   // Try a full evaluation first.
12089   Expr::EvalResult result;
12090   if (E->EvaluateAsRValue(result, C, InConstantContext))
12091     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
12092 
12093   // I think we only want to look through implicit casts here; if the
12094   // user has an explicit widening cast, we should treat the value as
12095   // being of the new, wider type.
12096   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
12097     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
12098       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
12099                           Approximate);
12100 
12101     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
12102 
12103     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
12104                          CE->getCastKind() == CK_BooleanToSignedIntegral;
12105 
12106     // Assume that non-integer casts can span the full range of the type.
12107     if (!isIntegerCast)
12108       return OutputTypeRange;
12109 
12110     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
12111                                      std::min(MaxWidth, OutputTypeRange.Width),
12112                                      InConstantContext, Approximate);
12113 
12114     // Bail out if the subexpr's range is as wide as the cast type.
12115     if (SubRange.Width >= OutputTypeRange.Width)
12116       return OutputTypeRange;
12117 
12118     // Otherwise, we take the smaller width, and we're non-negative if
12119     // either the output type or the subexpr is.
12120     return IntRange(SubRange.Width,
12121                     SubRange.NonNegative || OutputTypeRange.NonNegative);
12122   }
12123 
12124   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12125     // If we can fold the condition, just take that operand.
12126     bool CondResult;
12127     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
12128       return GetExprRange(C,
12129                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
12130                           MaxWidth, InConstantContext, Approximate);
12131 
12132     // Otherwise, conservatively merge.
12133     // GetExprRange requires an integer expression, but a throw expression
12134     // results in a void type.
12135     Expr *E = CO->getTrueExpr();
12136     IntRange L = E->getType()->isVoidType()
12137                      ? IntRange{0, true}
12138                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
12139     E = CO->getFalseExpr();
12140     IntRange R = E->getType()->isVoidType()
12141                      ? IntRange{0, true}
12142                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
12143     return IntRange::join(L, R);
12144   }
12145 
12146   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12147     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12148 
12149     switch (BO->getOpcode()) {
12150     case BO_Cmp:
12151       llvm_unreachable("builtin <=> should have class type");
12152 
12153     // Boolean-valued operations are single-bit and positive.
12154     case BO_LAnd:
12155     case BO_LOr:
12156     case BO_LT:
12157     case BO_GT:
12158     case BO_LE:
12159     case BO_GE:
12160     case BO_EQ:
12161     case BO_NE:
12162       return IntRange::forBoolType();
12163 
12164     // The type of the assignments is the type of the LHS, so the RHS
12165     // is not necessarily the same type.
12166     case BO_MulAssign:
12167     case BO_DivAssign:
12168     case BO_RemAssign:
12169     case BO_AddAssign:
12170     case BO_SubAssign:
12171     case BO_XorAssign:
12172     case BO_OrAssign:
12173       // TODO: bitfields?
12174       return IntRange::forValueOfType(C, GetExprType(E));
12175 
12176     // Simple assignments just pass through the RHS, which will have
12177     // been coerced to the LHS type.
12178     case BO_Assign:
12179       // TODO: bitfields?
12180       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12181                           Approximate);
12182 
12183     // Operations with opaque sources are black-listed.
12184     case BO_PtrMemD:
12185     case BO_PtrMemI:
12186       return IntRange::forValueOfType(C, GetExprType(E));
12187 
12188     // Bitwise-and uses the *infinum* of the two source ranges.
12189     case BO_And:
12190     case BO_AndAssign:
12191       Combine = IntRange::bit_and;
12192       break;
12193 
12194     // Left shift gets black-listed based on a judgement call.
12195     case BO_Shl:
12196       // ...except that we want to treat '1 << (blah)' as logically
12197       // positive.  It's an important idiom.
12198       if (IntegerLiteral *I
12199             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
12200         if (I->getValue() == 1) {
12201           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
12202           return IntRange(R.Width, /*NonNegative*/ true);
12203         }
12204       }
12205       LLVM_FALLTHROUGH;
12206 
12207     case BO_ShlAssign:
12208       return IntRange::forValueOfType(C, GetExprType(E));
12209 
12210     // Right shift by a constant can narrow its left argument.
12211     case BO_Shr:
12212     case BO_ShrAssign: {
12213       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
12214                                 Approximate);
12215 
12216       // If the shift amount is a positive constant, drop the width by
12217       // that much.
12218       if (Optional<llvm::APSInt> shift =
12219               BO->getRHS()->getIntegerConstantExpr(C)) {
12220         if (shift->isNonNegative()) {
12221           unsigned zext = shift->getZExtValue();
12222           if (zext >= L.Width)
12223             L.Width = (L.NonNegative ? 0 : 1);
12224           else
12225             L.Width -= zext;
12226         }
12227       }
12228 
12229       return L;
12230     }
12231 
12232     // Comma acts as its right operand.
12233     case BO_Comma:
12234       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12235                           Approximate);
12236 
12237     case BO_Add:
12238       if (!Approximate)
12239         Combine = IntRange::sum;
12240       break;
12241 
12242     case BO_Sub:
12243       if (BO->getLHS()->getType()->isPointerType())
12244         return IntRange::forValueOfType(C, GetExprType(E));
12245       if (!Approximate)
12246         Combine = IntRange::difference;
12247       break;
12248 
12249     case BO_Mul:
12250       if (!Approximate)
12251         Combine = IntRange::product;
12252       break;
12253 
12254     // The width of a division result is mostly determined by the size
12255     // of the LHS.
12256     case BO_Div: {
12257       // Don't 'pre-truncate' the operands.
12258       unsigned opWidth = C.getIntWidth(GetExprType(E));
12259       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
12260                                 Approximate);
12261 
12262       // If the divisor is constant, use that.
12263       if (Optional<llvm::APSInt> divisor =
12264               BO->getRHS()->getIntegerConstantExpr(C)) {
12265         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12266         if (log2 >= L.Width)
12267           L.Width = (L.NonNegative ? 0 : 1);
12268         else
12269           L.Width = std::min(L.Width - log2, MaxWidth);
12270         return L;
12271       }
12272 
12273       // Otherwise, just use the LHS's width.
12274       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12275       // could be -1.
12276       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
12277                                 Approximate);
12278       return IntRange(L.Width, L.NonNegative && R.NonNegative);
12279     }
12280 
12281     case BO_Rem:
12282       Combine = IntRange::rem;
12283       break;
12284 
12285     // The default behavior is okay for these.
12286     case BO_Xor:
12287     case BO_Or:
12288       break;
12289     }
12290 
12291     // Combine the two ranges, but limit the result to the type in which we
12292     // performed the computation.
12293     QualType T = GetExprType(E);
12294     unsigned opWidth = C.getIntWidth(T);
12295     IntRange L =
12296         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
12297     IntRange R =
12298         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
12299     IntRange C = Combine(L, R);
12300     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12301     C.Width = std::min(C.Width, MaxWidth);
12302     return C;
12303   }
12304 
12305   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12306     switch (UO->getOpcode()) {
12307     // Boolean-valued operations are white-listed.
12308     case UO_LNot:
12309       return IntRange::forBoolType();
12310 
12311     // Operations with opaque sources are black-listed.
12312     case UO_Deref:
12313     case UO_AddrOf: // should be impossible
12314       return IntRange::forValueOfType(C, GetExprType(E));
12315 
12316     default:
12317       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12318                           Approximate);
12319     }
12320   }
12321 
12322   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12323     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
12324                         Approximate);
12325 
12326   if (const auto *BitField = E->getSourceBitField())
12327     return IntRange(BitField->getBitWidthValue(C),
12328                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
12329 
12330   return IntRange::forValueOfType(C, GetExprType(E));
12331 }
12332 
12333 static IntRange GetExprRange(ASTContext &C, const Expr *E,
12334                              bool InConstantContext, bool Approximate) {
12335   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12336                       Approximate);
12337 }
12338 
12339 /// Checks whether the given value, which currently has the given
12340 /// source semantics, has the same value when coerced through the
12341 /// target semantics.
12342 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12343                                  const llvm::fltSemantics &Src,
12344                                  const llvm::fltSemantics &Tgt) {
12345   llvm::APFloat truncated = value;
12346 
12347   bool ignored;
12348   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12349   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12350 
12351   return truncated.bitwiseIsEqual(value);
12352 }
12353 
12354 /// Checks whether the given value, which currently has the given
12355 /// source semantics, has the same value when coerced through the
12356 /// target semantics.
12357 ///
12358 /// The value might be a vector of floats (or a complex number).
12359 static bool IsSameFloatAfterCast(const APValue &value,
12360                                  const llvm::fltSemantics &Src,
12361                                  const llvm::fltSemantics &Tgt) {
12362   if (value.isFloat())
12363     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12364 
12365   if (value.isVector()) {
12366     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12367       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12368         return false;
12369     return true;
12370   }
12371 
12372   assert(value.isComplexFloat());
12373   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12374           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12375 }
12376 
12377 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12378                                        bool IsListInit = false);
12379 
12380 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
12381   // Suppress cases where we are comparing against an enum constant.
12382   if (const DeclRefExpr *DR =
12383       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12384     if (isa<EnumConstantDecl>(DR->getDecl()))
12385       return true;
12386 
12387   // Suppress cases where the value is expanded from a macro, unless that macro
12388   // is how a language represents a boolean literal. This is the case in both C
12389   // and Objective-C.
12390   SourceLocation BeginLoc = E->getBeginLoc();
12391   if (BeginLoc.isMacroID()) {
12392     StringRef MacroName = Lexer::getImmediateMacroName(
12393         BeginLoc, S.getSourceManager(), S.getLangOpts());
12394     return MacroName != "YES" && MacroName != "NO" &&
12395            MacroName != "true" && MacroName != "false";
12396   }
12397 
12398   return false;
12399 }
12400 
12401 static bool isKnownToHaveUnsignedValue(Expr *E) {
12402   return E->getType()->isIntegerType() &&
12403          (!E->getType()->isSignedIntegerType() ||
12404           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12405 }
12406 
12407 namespace {
12408 /// The promoted range of values of a type. In general this has the
12409 /// following structure:
12410 ///
12411 ///     |-----------| . . . |-----------|
12412 ///     ^           ^       ^           ^
12413 ///    Min       HoleMin  HoleMax      Max
12414 ///
12415 /// ... where there is only a hole if a signed type is promoted to unsigned
12416 /// (in which case Min and Max are the smallest and largest representable
12417 /// values).
12418 struct PromotedRange {
12419   // Min, or HoleMax if there is a hole.
12420   llvm::APSInt PromotedMin;
12421   // Max, or HoleMin if there is a hole.
12422   llvm::APSInt PromotedMax;
12423 
12424   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12425     if (R.Width == 0)
12426       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12427     else if (R.Width >= BitWidth && !Unsigned) {
12428       // Promotion made the type *narrower*. This happens when promoting
12429       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12430       // Treat all values of 'signed int' as being in range for now.
12431       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12432       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12433     } else {
12434       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12435                         .extOrTrunc(BitWidth);
12436       PromotedMin.setIsUnsigned(Unsigned);
12437 
12438       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12439                         .extOrTrunc(BitWidth);
12440       PromotedMax.setIsUnsigned(Unsigned);
12441     }
12442   }
12443 
12444   // Determine whether this range is contiguous (has no hole).
12445   bool isContiguous() const { return PromotedMin <= PromotedMax; }
12446 
12447   // Where a constant value is within the range.
12448   enum ComparisonResult {
12449     LT = 0x1,
12450     LE = 0x2,
12451     GT = 0x4,
12452     GE = 0x8,
12453     EQ = 0x10,
12454     NE = 0x20,
12455     InRangeFlag = 0x40,
12456 
12457     Less = LE | LT | NE,
12458     Min = LE | InRangeFlag,
12459     InRange = InRangeFlag,
12460     Max = GE | InRangeFlag,
12461     Greater = GE | GT | NE,
12462 
12463     OnlyValue = LE | GE | EQ | InRangeFlag,
12464     InHole = NE
12465   };
12466 
12467   ComparisonResult compare(const llvm::APSInt &Value) const {
12468     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12469            Value.isUnsigned() == PromotedMin.isUnsigned());
12470     if (!isContiguous()) {
12471       assert(Value.isUnsigned() && "discontiguous range for signed compare");
12472       if (Value.isMinValue()) return Min;
12473       if (Value.isMaxValue()) return Max;
12474       if (Value >= PromotedMin) return InRange;
12475       if (Value <= PromotedMax) return InRange;
12476       return InHole;
12477     }
12478 
12479     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12480     case -1: return Less;
12481     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12482     case 1:
12483       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12484       case -1: return InRange;
12485       case 0: return Max;
12486       case 1: return Greater;
12487       }
12488     }
12489 
12490     llvm_unreachable("impossible compare result");
12491   }
12492 
12493   static llvm::Optional<StringRef>
12494   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12495     if (Op == BO_Cmp) {
12496       ComparisonResult LTFlag = LT, GTFlag = GT;
12497       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12498 
12499       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12500       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12501       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12502       return llvm::None;
12503     }
12504 
12505     ComparisonResult TrueFlag, FalseFlag;
12506     if (Op == BO_EQ) {
12507       TrueFlag = EQ;
12508       FalseFlag = NE;
12509     } else if (Op == BO_NE) {
12510       TrueFlag = NE;
12511       FalseFlag = EQ;
12512     } else {
12513       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12514         TrueFlag = LT;
12515         FalseFlag = GE;
12516       } else {
12517         TrueFlag = GT;
12518         FalseFlag = LE;
12519       }
12520       if (Op == BO_GE || Op == BO_LE)
12521         std::swap(TrueFlag, FalseFlag);
12522     }
12523     if (R & TrueFlag)
12524       return StringRef("true");
12525     if (R & FalseFlag)
12526       return StringRef("false");
12527     return llvm::None;
12528   }
12529 };
12530 }
12531 
12532 static bool HasEnumType(Expr *E) {
12533   // Strip off implicit integral promotions.
12534   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12535     if (ICE->getCastKind() != CK_IntegralCast &&
12536         ICE->getCastKind() != CK_NoOp)
12537       break;
12538     E = ICE->getSubExpr();
12539   }
12540 
12541   return E->getType()->isEnumeralType();
12542 }
12543 
12544 static int classifyConstantValue(Expr *Constant) {
12545   // The values of this enumeration are used in the diagnostics
12546   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12547   enum ConstantValueKind {
12548     Miscellaneous = 0,
12549     LiteralTrue,
12550     LiteralFalse
12551   };
12552   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12553     return BL->getValue() ? ConstantValueKind::LiteralTrue
12554                           : ConstantValueKind::LiteralFalse;
12555   return ConstantValueKind::Miscellaneous;
12556 }
12557 
12558 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12559                                         Expr *Constant, Expr *Other,
12560                                         const llvm::APSInt &Value,
12561                                         bool RhsConstant) {
12562   if (S.inTemplateInstantiation())
12563     return false;
12564 
12565   Expr *OriginalOther = Other;
12566 
12567   Constant = Constant->IgnoreParenImpCasts();
12568   Other = Other->IgnoreParenImpCasts();
12569 
12570   // Suppress warnings on tautological comparisons between values of the same
12571   // enumeration type. There are only two ways we could warn on this:
12572   //  - If the constant is outside the range of representable values of
12573   //    the enumeration. In such a case, we should warn about the cast
12574   //    to enumeration type, not about the comparison.
12575   //  - If the constant is the maximum / minimum in-range value. For an
12576   //    enumeratin type, such comparisons can be meaningful and useful.
12577   if (Constant->getType()->isEnumeralType() &&
12578       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12579     return false;
12580 
12581   IntRange OtherValueRange = GetExprRange(
12582       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
12583 
12584   QualType OtherT = Other->getType();
12585   if (const auto *AT = OtherT->getAs<AtomicType>())
12586     OtherT = AT->getValueType();
12587   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12588 
12589   // Special case for ObjC BOOL on targets where its a typedef for a signed char
12590   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12591   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12592                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
12593                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12594 
12595   // Whether we're treating Other as being a bool because of the form of
12596   // expression despite it having another type (typically 'int' in C).
12597   bool OtherIsBooleanDespiteType =
12598       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12599   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12600     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
12601 
12602   // Check if all values in the range of possible values of this expression
12603   // lead to the same comparison outcome.
12604   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
12605                                         Value.isUnsigned());
12606   auto Cmp = OtherPromotedValueRange.compare(Value);
12607   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12608   if (!Result)
12609     return false;
12610 
12611   // Also consider the range determined by the type alone. This allows us to
12612   // classify the warning under the proper diagnostic group.
12613   bool TautologicalTypeCompare = false;
12614   {
12615     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12616                                          Value.isUnsigned());
12617     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12618     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12619                                                        RhsConstant)) {
12620       TautologicalTypeCompare = true;
12621       Cmp = TypeCmp;
12622       Result = TypeResult;
12623     }
12624   }
12625 
12626   // Don't warn if the non-constant operand actually always evaluates to the
12627   // same value.
12628   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
12629     return false;
12630 
12631   // Suppress the diagnostic for an in-range comparison if the constant comes
12632   // from a macro or enumerator. We don't want to diagnose
12633   //
12634   //   some_long_value <= INT_MAX
12635   //
12636   // when sizeof(int) == sizeof(long).
12637   bool InRange = Cmp & PromotedRange::InRangeFlag;
12638   if (InRange && IsEnumConstOrFromMacro(S, Constant))
12639     return false;
12640 
12641   // A comparison of an unsigned bit-field against 0 is really a type problem,
12642   // even though at the type level the bit-field might promote to 'signed int'.
12643   if (Other->refersToBitField() && InRange && Value == 0 &&
12644       Other->getType()->isUnsignedIntegerOrEnumerationType())
12645     TautologicalTypeCompare = true;
12646 
12647   // If this is a comparison to an enum constant, include that
12648   // constant in the diagnostic.
12649   const EnumConstantDecl *ED = nullptr;
12650   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
12651     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12652 
12653   // Should be enough for uint128 (39 decimal digits)
12654   SmallString<64> PrettySourceValue;
12655   llvm::raw_svector_ostream OS(PrettySourceValue);
12656   if (ED) {
12657     OS << '\'' << *ED << "' (" << Value << ")";
12658   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12659                Constant->IgnoreParenImpCasts())) {
12660     OS << (BL->getValue() ? "YES" : "NO");
12661   } else {
12662     OS << Value;
12663   }
12664 
12665   if (!TautologicalTypeCompare) {
12666     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12667         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
12668         << E->getOpcodeStr() << OS.str() << *Result
12669         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12670     return true;
12671   }
12672 
12673   if (IsObjCSignedCharBool) {
12674     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12675                           S.PDiag(diag::warn_tautological_compare_objc_bool)
12676                               << OS.str() << *Result);
12677     return true;
12678   }
12679 
12680   // FIXME: We use a somewhat different formatting for the in-range cases and
12681   // cases involving boolean values for historical reasons. We should pick a
12682   // consistent way of presenting these diagnostics.
12683   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12684 
12685     S.DiagRuntimeBehavior(
12686         E->getOperatorLoc(), E,
12687         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12688                          : diag::warn_tautological_bool_compare)
12689             << OS.str() << classifyConstantValue(Constant) << OtherT
12690             << OtherIsBooleanDespiteType << *Result
12691             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12692   } else {
12693     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12694     unsigned Diag =
12695         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12696             ? (HasEnumType(OriginalOther)
12697                    ? diag::warn_unsigned_enum_always_true_comparison
12698                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12699                               : diag::warn_unsigned_always_true_comparison)
12700             : diag::warn_tautological_constant_compare;
12701 
12702     S.Diag(E->getOperatorLoc(), Diag)
12703         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12704         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12705   }
12706 
12707   return true;
12708 }
12709 
12710 /// Analyze the operands of the given comparison.  Implements the
12711 /// fallback case from AnalyzeComparison.
12712 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12713   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12714   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12715 }
12716 
12717 /// Implements -Wsign-compare.
12718 ///
12719 /// \param E the binary operator to check for warnings
12720 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12721   // The type the comparison is being performed in.
12722   QualType T = E->getLHS()->getType();
12723 
12724   // Only analyze comparison operators where both sides have been converted to
12725   // the same type.
12726   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12727     return AnalyzeImpConvsInComparison(S, E);
12728 
12729   // Don't analyze value-dependent comparisons directly.
12730   if (E->isValueDependent())
12731     return AnalyzeImpConvsInComparison(S, E);
12732 
12733   Expr *LHS = E->getLHS();
12734   Expr *RHS = E->getRHS();
12735 
12736   if (T->isIntegralType(S.Context)) {
12737     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12738     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12739 
12740     // We don't care about expressions whose result is a constant.
12741     if (RHSValue && LHSValue)
12742       return AnalyzeImpConvsInComparison(S, E);
12743 
12744     // We only care about expressions where just one side is literal
12745     if ((bool)RHSValue ^ (bool)LHSValue) {
12746       // Is the constant on the RHS or LHS?
12747       const bool RhsConstant = (bool)RHSValue;
12748       Expr *Const = RhsConstant ? RHS : LHS;
12749       Expr *Other = RhsConstant ? LHS : RHS;
12750       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12751 
12752       // Check whether an integer constant comparison results in a value
12753       // of 'true' or 'false'.
12754       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12755         return AnalyzeImpConvsInComparison(S, E);
12756     }
12757   }
12758 
12759   if (!T->hasUnsignedIntegerRepresentation()) {
12760     // We don't do anything special if this isn't an unsigned integral
12761     // comparison:  we're only interested in integral comparisons, and
12762     // signed comparisons only happen in cases we don't care to warn about.
12763     return AnalyzeImpConvsInComparison(S, E);
12764   }
12765 
12766   LHS = LHS->IgnoreParenImpCasts();
12767   RHS = RHS->IgnoreParenImpCasts();
12768 
12769   if (!S.getLangOpts().CPlusPlus) {
12770     // Avoid warning about comparison of integers with different signs when
12771     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12772     // the type of `E`.
12773     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12774       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12775     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12776       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12777   }
12778 
12779   // Check to see if one of the (unmodified) operands is of different
12780   // signedness.
12781   Expr *signedOperand, *unsignedOperand;
12782   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12783     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12784            "unsigned comparison between two signed integer expressions?");
12785     signedOperand = LHS;
12786     unsignedOperand = RHS;
12787   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12788     signedOperand = RHS;
12789     unsignedOperand = LHS;
12790   } else {
12791     return AnalyzeImpConvsInComparison(S, E);
12792   }
12793 
12794   // Otherwise, calculate the effective range of the signed operand.
12795   IntRange signedRange = GetExprRange(
12796       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12797 
12798   // Go ahead and analyze implicit conversions in the operands.  Note
12799   // that we skip the implicit conversions on both sides.
12800   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12801   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12802 
12803   // If the signed range is non-negative, -Wsign-compare won't fire.
12804   if (signedRange.NonNegative)
12805     return;
12806 
12807   // For (in)equality comparisons, if the unsigned operand is a
12808   // constant which cannot collide with a overflowed signed operand,
12809   // then reinterpreting the signed operand as unsigned will not
12810   // change the result of the comparison.
12811   if (E->isEqualityOp()) {
12812     unsigned comparisonWidth = S.Context.getIntWidth(T);
12813     IntRange unsignedRange =
12814         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12815                      /*Approximate*/ true);
12816 
12817     // We should never be unable to prove that the unsigned operand is
12818     // non-negative.
12819     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12820 
12821     if (unsignedRange.Width < comparisonWidth)
12822       return;
12823   }
12824 
12825   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12826                         S.PDiag(diag::warn_mixed_sign_comparison)
12827                             << LHS->getType() << RHS->getType()
12828                             << LHS->getSourceRange() << RHS->getSourceRange());
12829 }
12830 
12831 /// Analyzes an attempt to assign the given value to a bitfield.
12832 ///
12833 /// Returns true if there was something fishy about the attempt.
12834 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12835                                       SourceLocation InitLoc) {
12836   assert(Bitfield->isBitField());
12837   if (Bitfield->isInvalidDecl())
12838     return false;
12839 
12840   // White-list bool bitfields.
12841   QualType BitfieldType = Bitfield->getType();
12842   if (BitfieldType->isBooleanType())
12843      return false;
12844 
12845   if (BitfieldType->isEnumeralType()) {
12846     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12847     // If the underlying enum type was not explicitly specified as an unsigned
12848     // type and the enum contain only positive values, MSVC++ will cause an
12849     // inconsistency by storing this as a signed type.
12850     if (S.getLangOpts().CPlusPlus11 &&
12851         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12852         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12853         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12854       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12855           << BitfieldEnumDecl;
12856     }
12857   }
12858 
12859   if (Bitfield->getType()->isBooleanType())
12860     return false;
12861 
12862   // Ignore value- or type-dependent expressions.
12863   if (Bitfield->getBitWidth()->isValueDependent() ||
12864       Bitfield->getBitWidth()->isTypeDependent() ||
12865       Init->isValueDependent() ||
12866       Init->isTypeDependent())
12867     return false;
12868 
12869   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12870   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12871 
12872   Expr::EvalResult Result;
12873   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12874                                    Expr::SE_AllowSideEffects)) {
12875     // The RHS is not constant.  If the RHS has an enum type, make sure the
12876     // bitfield is wide enough to hold all the values of the enum without
12877     // truncation.
12878     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12879       EnumDecl *ED = EnumTy->getDecl();
12880       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12881 
12882       // Enum types are implicitly signed on Windows, so check if there are any
12883       // negative enumerators to see if the enum was intended to be signed or
12884       // not.
12885       bool SignedEnum = ED->getNumNegativeBits() > 0;
12886 
12887       // Check for surprising sign changes when assigning enum values to a
12888       // bitfield of different signedness.  If the bitfield is signed and we
12889       // have exactly the right number of bits to store this unsigned enum,
12890       // suggest changing the enum to an unsigned type. This typically happens
12891       // on Windows where unfixed enums always use an underlying type of 'int'.
12892       unsigned DiagID = 0;
12893       if (SignedEnum && !SignedBitfield) {
12894         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12895       } else if (SignedBitfield && !SignedEnum &&
12896                  ED->getNumPositiveBits() == FieldWidth) {
12897         DiagID = diag::warn_signed_bitfield_enum_conversion;
12898       }
12899 
12900       if (DiagID) {
12901         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12902         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12903         SourceRange TypeRange =
12904             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12905         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12906             << SignedEnum << TypeRange;
12907       }
12908 
12909       // Compute the required bitwidth. If the enum has negative values, we need
12910       // one more bit than the normal number of positive bits to represent the
12911       // sign bit.
12912       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12913                                                   ED->getNumNegativeBits())
12914                                        : ED->getNumPositiveBits();
12915 
12916       // Check the bitwidth.
12917       if (BitsNeeded > FieldWidth) {
12918         Expr *WidthExpr = Bitfield->getBitWidth();
12919         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12920             << Bitfield << ED;
12921         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12922             << BitsNeeded << ED << WidthExpr->getSourceRange();
12923       }
12924     }
12925 
12926     return false;
12927   }
12928 
12929   llvm::APSInt Value = Result.Val.getInt();
12930 
12931   unsigned OriginalWidth = Value.getBitWidth();
12932 
12933   if (!Value.isSigned() || Value.isNegative())
12934     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12935       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12936         OriginalWidth = Value.getMinSignedBits();
12937 
12938   if (OriginalWidth <= FieldWidth)
12939     return false;
12940 
12941   // Compute the value which the bitfield will contain.
12942   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12943   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12944 
12945   // Check whether the stored value is equal to the original value.
12946   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12947   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12948     return false;
12949 
12950   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12951   // therefore don't strictly fit into a signed bitfield of width 1.
12952   if (FieldWidth == 1 && Value == 1)
12953     return false;
12954 
12955   std::string PrettyValue = toString(Value, 10);
12956   std::string PrettyTrunc = toString(TruncatedValue, 10);
12957 
12958   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12959     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12960     << Init->getSourceRange();
12961 
12962   return true;
12963 }
12964 
12965 /// Analyze the given simple or compound assignment for warning-worthy
12966 /// operations.
12967 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12968   // Just recurse on the LHS.
12969   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12970 
12971   // We want to recurse on the RHS as normal unless we're assigning to
12972   // a bitfield.
12973   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12974     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12975                                   E->getOperatorLoc())) {
12976       // Recurse, ignoring any implicit conversions on the RHS.
12977       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12978                                         E->getOperatorLoc());
12979     }
12980   }
12981 
12982   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12983 
12984   // Diagnose implicitly sequentially-consistent atomic assignment.
12985   if (E->getLHS()->getType()->isAtomicType())
12986     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12987 }
12988 
12989 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12990 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12991                             SourceLocation CContext, unsigned diag,
12992                             bool pruneControlFlow = false) {
12993   if (pruneControlFlow) {
12994     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12995                           S.PDiag(diag)
12996                               << SourceType << T << E->getSourceRange()
12997                               << SourceRange(CContext));
12998     return;
12999   }
13000   S.Diag(E->getExprLoc(), diag)
13001     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
13002 }
13003 
13004 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
13005 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
13006                             SourceLocation CContext,
13007                             unsigned diag, bool pruneControlFlow = false) {
13008   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
13009 }
13010 
13011 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
13012   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
13013       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
13014 }
13015 
13016 static void adornObjCBoolConversionDiagWithTernaryFixit(
13017     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
13018   Expr *Ignored = SourceExpr->IgnoreImplicit();
13019   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
13020     Ignored = OVE->getSourceExpr();
13021   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
13022                      isa<BinaryOperator>(Ignored) ||
13023                      isa<CXXOperatorCallExpr>(Ignored);
13024   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
13025   if (NeedsParens)
13026     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
13027             << FixItHint::CreateInsertion(EndLoc, ")");
13028   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
13029 }
13030 
13031 /// Diagnose an implicit cast from a floating point value to an integer value.
13032 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
13033                                     SourceLocation CContext) {
13034   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
13035   const bool PruneWarnings = S.inTemplateInstantiation();
13036 
13037   Expr *InnerE = E->IgnoreParenImpCasts();
13038   // We also want to warn on, e.g., "int i = -1.234"
13039   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
13040     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13041       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13042 
13043   const bool IsLiteral =
13044       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
13045 
13046   llvm::APFloat Value(0.0);
13047   bool IsConstant =
13048     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
13049   if (!IsConstant) {
13050     if (isObjCSignedCharBool(S, T)) {
13051       return adornObjCBoolConversionDiagWithTernaryFixit(
13052           S, E,
13053           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
13054               << E->getType());
13055     }
13056 
13057     return DiagnoseImpCast(S, E, T, CContext,
13058                            diag::warn_impcast_float_integer, PruneWarnings);
13059   }
13060 
13061   bool isExact = false;
13062 
13063   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13064                             T->hasUnsignedIntegerRepresentation());
13065   llvm::APFloat::opStatus Result = Value.convertToInteger(
13066       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
13067 
13068   // FIXME: Force the precision of the source value down so we don't print
13069   // digits which are usually useless (we don't really care here if we
13070   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
13071   // would automatically print the shortest representation, but it's a bit
13072   // tricky to implement.
13073   SmallString<16> PrettySourceValue;
13074   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13075   precision = (precision * 59 + 195) / 196;
13076   Value.toString(PrettySourceValue, precision);
13077 
13078   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
13079     return adornObjCBoolConversionDiagWithTernaryFixit(
13080         S, E,
13081         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
13082             << PrettySourceValue);
13083   }
13084 
13085   if (Result == llvm::APFloat::opOK && isExact) {
13086     if (IsLiteral) return;
13087     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
13088                            PruneWarnings);
13089   }
13090 
13091   // Conversion of a floating-point value to a non-bool integer where the
13092   // integral part cannot be represented by the integer type is undefined.
13093   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13094     return DiagnoseImpCast(
13095         S, E, T, CContext,
13096         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13097                   : diag::warn_impcast_float_to_integer_out_of_range,
13098         PruneWarnings);
13099 
13100   unsigned DiagID = 0;
13101   if (IsLiteral) {
13102     // Warn on floating point literal to integer.
13103     DiagID = diag::warn_impcast_literal_float_to_integer;
13104   } else if (IntegerValue == 0) {
13105     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
13106       return DiagnoseImpCast(S, E, T, CContext,
13107                              diag::warn_impcast_float_integer, PruneWarnings);
13108     }
13109     // Warn on non-zero to zero conversion.
13110     DiagID = diag::warn_impcast_float_to_integer_zero;
13111   } else {
13112     if (IntegerValue.isUnsigned()) {
13113       if (!IntegerValue.isMaxValue()) {
13114         return DiagnoseImpCast(S, E, T, CContext,
13115                                diag::warn_impcast_float_integer, PruneWarnings);
13116       }
13117     } else {  // IntegerValue.isSigned()
13118       if (!IntegerValue.isMaxSignedValue() &&
13119           !IntegerValue.isMinSignedValue()) {
13120         return DiagnoseImpCast(S, E, T, CContext,
13121                                diag::warn_impcast_float_integer, PruneWarnings);
13122       }
13123     }
13124     // Warn on evaluatable floating point expression to integer conversion.
13125     DiagID = diag::warn_impcast_float_to_integer;
13126   }
13127 
13128   SmallString<16> PrettyTargetValue;
13129   if (IsBool)
13130     PrettyTargetValue = Value.isZero() ? "false" : "true";
13131   else
13132     IntegerValue.toString(PrettyTargetValue);
13133 
13134   if (PruneWarnings) {
13135     S.DiagRuntimeBehavior(E->getExprLoc(), E,
13136                           S.PDiag(DiagID)
13137                               << E->getType() << T.getUnqualifiedType()
13138                               << PrettySourceValue << PrettyTargetValue
13139                               << E->getSourceRange() << SourceRange(CContext));
13140   } else {
13141     S.Diag(E->getExprLoc(), DiagID)
13142         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13143         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13144   }
13145 }
13146 
13147 /// Analyze the given compound assignment for the possible losing of
13148 /// floating-point precision.
13149 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
13150   assert(isa<CompoundAssignOperator>(E) &&
13151          "Must be compound assignment operation");
13152   // Recurse on the LHS and RHS in here
13153   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
13154   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
13155 
13156   if (E->getLHS()->getType()->isAtomicType())
13157     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
13158 
13159   // Now check the outermost expression
13160   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13161   const auto *RBT = cast<CompoundAssignOperator>(E)
13162                         ->getComputationResultType()
13163                         ->getAs<BuiltinType>();
13164 
13165   // The below checks assume source is floating point.
13166   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13167 
13168   // If source is floating point but target is an integer.
13169   if (ResultBT->isInteger())
13170     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
13171                            E->getExprLoc(), diag::warn_impcast_float_integer);
13172 
13173   if (!ResultBT->isFloatingPoint())
13174     return;
13175 
13176   // If both source and target are floating points, warn about losing precision.
13177   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13178       QualType(ResultBT, 0), QualType(RBT, 0));
13179   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
13180     // warn about dropping FP rank.
13181     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
13182                     diag::warn_impcast_float_result_precision);
13183 }
13184 
13185 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13186                                       IntRange Range) {
13187   if (!Range.Width) return "0";
13188 
13189   llvm::APSInt ValueInRange = Value;
13190   ValueInRange.setIsSigned(!Range.NonNegative);
13191   ValueInRange = ValueInRange.trunc(Range.Width);
13192   return toString(ValueInRange, 10);
13193 }
13194 
13195 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
13196   if (!isa<ImplicitCastExpr>(Ex))
13197     return false;
13198 
13199   Expr *InnerE = Ex->IgnoreParenImpCasts();
13200   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
13201   const Type *Source =
13202     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
13203   if (Target->isDependentType())
13204     return false;
13205 
13206   const BuiltinType *FloatCandidateBT =
13207     dyn_cast<BuiltinType>(ToBool ? Source : Target);
13208   const Type *BoolCandidateType = ToBool ? Target : Source;
13209 
13210   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
13211           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13212 }
13213 
13214 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
13215                                              SourceLocation CC) {
13216   unsigned NumArgs = TheCall->getNumArgs();
13217   for (unsigned i = 0; i < NumArgs; ++i) {
13218     Expr *CurrA = TheCall->getArg(i);
13219     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
13220       continue;
13221 
13222     bool IsSwapped = ((i > 0) &&
13223         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
13224     IsSwapped |= ((i < (NumArgs - 1)) &&
13225         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
13226     if (IsSwapped) {
13227       // Warn on this floating-point to bool conversion.
13228       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
13229                       CurrA->getType(), CC,
13230                       diag::warn_impcast_floating_point_to_bool);
13231     }
13232   }
13233 }
13234 
13235 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
13236                                    SourceLocation CC) {
13237   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
13238                         E->getExprLoc()))
13239     return;
13240 
13241   // Don't warn on functions which have return type nullptr_t.
13242   if (isa<CallExpr>(E))
13243     return;
13244 
13245   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13246   const Expr::NullPointerConstantKind NullKind =
13247       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
13248   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
13249     return;
13250 
13251   // Return if target type is a safe conversion.
13252   if (T->isAnyPointerType() || T->isBlockPointerType() ||
13253       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13254     return;
13255 
13256   SourceLocation Loc = E->getSourceRange().getBegin();
13257 
13258   // Venture through the macro stacks to get to the source of macro arguments.
13259   // The new location is a better location than the complete location that was
13260   // passed in.
13261   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13262   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
13263 
13264   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
13265   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
13266     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13267         Loc, S.SourceMgr, S.getLangOpts());
13268     if (MacroName == "NULL")
13269       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
13270   }
13271 
13272   // Only warn if the null and context location are in the same macro expansion.
13273   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13274     return;
13275 
13276   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13277       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
13278       << FixItHint::CreateReplacement(Loc,
13279                                       S.getFixItZeroLiteralForType(T, Loc));
13280 }
13281 
13282 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
13283                                   ObjCArrayLiteral *ArrayLiteral);
13284 
13285 static void
13286 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
13287                            ObjCDictionaryLiteral *DictionaryLiteral);
13288 
13289 /// Check a single element within a collection literal against the
13290 /// target element type.
13291 static void checkObjCCollectionLiteralElement(Sema &S,
13292                                               QualType TargetElementType,
13293                                               Expr *Element,
13294                                               unsigned ElementKind) {
13295   // Skip a bitcast to 'id' or qualified 'id'.
13296   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
13297     if (ICE->getCastKind() == CK_BitCast &&
13298         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
13299       Element = ICE->getSubExpr();
13300   }
13301 
13302   QualType ElementType = Element->getType();
13303   ExprResult ElementResult(Element);
13304   if (ElementType->getAs<ObjCObjectPointerType>() &&
13305       S.CheckSingleAssignmentConstraints(TargetElementType,
13306                                          ElementResult,
13307                                          false, false)
13308         != Sema::Compatible) {
13309     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
13310         << ElementType << ElementKind << TargetElementType
13311         << Element->getSourceRange();
13312   }
13313 
13314   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
13315     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
13316   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
13317     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
13318 }
13319 
13320 /// Check an Objective-C array literal being converted to the given
13321 /// target type.
13322 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
13323                                   ObjCArrayLiteral *ArrayLiteral) {
13324   if (!S.NSArrayDecl)
13325     return;
13326 
13327   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
13328   if (!TargetObjCPtr)
13329     return;
13330 
13331   if (TargetObjCPtr->isUnspecialized() ||
13332       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
13333         != S.NSArrayDecl->getCanonicalDecl())
13334     return;
13335 
13336   auto TypeArgs = TargetObjCPtr->getTypeArgs();
13337   if (TypeArgs.size() != 1)
13338     return;
13339 
13340   QualType TargetElementType = TypeArgs[0];
13341   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
13342     checkObjCCollectionLiteralElement(S, TargetElementType,
13343                                       ArrayLiteral->getElement(I),
13344                                       0);
13345   }
13346 }
13347 
13348 /// Check an Objective-C dictionary literal being converted to the given
13349 /// target type.
13350 static void
13351 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
13352                            ObjCDictionaryLiteral *DictionaryLiteral) {
13353   if (!S.NSDictionaryDecl)
13354     return;
13355 
13356   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
13357   if (!TargetObjCPtr)
13358     return;
13359 
13360   if (TargetObjCPtr->isUnspecialized() ||
13361       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
13362         != S.NSDictionaryDecl->getCanonicalDecl())
13363     return;
13364 
13365   auto TypeArgs = TargetObjCPtr->getTypeArgs();
13366   if (TypeArgs.size() != 2)
13367     return;
13368 
13369   QualType TargetKeyType = TypeArgs[0];
13370   QualType TargetObjectType = TypeArgs[1];
13371   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
13372     auto Element = DictionaryLiteral->getKeyValueElement(I);
13373     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
13374     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
13375   }
13376 }
13377 
13378 // Helper function to filter out cases for constant width constant conversion.
13379 // Don't warn on char array initialization or for non-decimal values.
13380 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
13381                                           SourceLocation CC) {
13382   // If initializing from a constant, and the constant starts with '0',
13383   // then it is a binary, octal, or hexadecimal.  Allow these constants
13384   // to fill all the bits, even if there is a sign change.
13385   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13386     const char FirstLiteralCharacter =
13387         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13388     if (FirstLiteralCharacter == '0')
13389       return false;
13390   }
13391 
13392   // If the CC location points to a '{', and the type is char, then assume
13393   // assume it is an array initialization.
13394   if (CC.isValid() && T->isCharType()) {
13395     const char FirstContextCharacter =
13396         S.getSourceManager().getCharacterData(CC)[0];
13397     if (FirstContextCharacter == '{')
13398       return false;
13399   }
13400 
13401   return true;
13402 }
13403 
13404 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13405   const auto *IL = dyn_cast<IntegerLiteral>(E);
13406   if (!IL) {
13407     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13408       if (UO->getOpcode() == UO_Minus)
13409         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13410     }
13411   }
13412 
13413   return IL;
13414 }
13415 
13416 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13417   E = E->IgnoreParenImpCasts();
13418   SourceLocation ExprLoc = E->getExprLoc();
13419 
13420   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13421     BinaryOperator::Opcode Opc = BO->getOpcode();
13422     Expr::EvalResult Result;
13423     // Do not diagnose unsigned shifts.
13424     if (Opc == BO_Shl) {
13425       const auto *LHS = getIntegerLiteral(BO->getLHS());
13426       const auto *RHS = getIntegerLiteral(BO->getRHS());
13427       if (LHS && LHS->getValue() == 0)
13428         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13429       else if (!E->isValueDependent() && LHS && RHS &&
13430                RHS->getValue().isNonNegative() &&
13431                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
13432         S.Diag(ExprLoc, diag::warn_left_shift_always)
13433             << (Result.Val.getInt() != 0);
13434       else if (E->getType()->isSignedIntegerType())
13435         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
13436     }
13437   }
13438 
13439   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13440     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13441     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13442     if (!LHS || !RHS)
13443       return;
13444     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13445         (RHS->getValue() == 0 || RHS->getValue() == 1))
13446       // Do not diagnose common idioms.
13447       return;
13448     if (LHS->getValue() != 0 && RHS->getValue() != 0)
13449       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13450   }
13451 }
13452 
13453 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
13454                                     SourceLocation CC,
13455                                     bool *ICContext = nullptr,
13456                                     bool IsListInit = false) {
13457   if (E->isTypeDependent() || E->isValueDependent()) return;
13458 
13459   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
13460   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
13461   if (Source == Target) return;
13462   if (Target->isDependentType()) return;
13463 
13464   // If the conversion context location is invalid don't complain. We also
13465   // don't want to emit a warning if the issue occurs from the expansion of
13466   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13467   // delay this check as long as possible. Once we detect we are in that
13468   // scenario, we just return.
13469   if (CC.isInvalid())
13470     return;
13471 
13472   if (Source->isAtomicType())
13473     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13474 
13475   // Diagnose implicit casts to bool.
13476   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13477     if (isa<StringLiteral>(E))
13478       // Warn on string literal to bool.  Checks for string literals in logical
13479       // and expressions, for instance, assert(0 && "error here"), are
13480       // prevented by a check in AnalyzeImplicitConversions().
13481       return DiagnoseImpCast(S, E, T, CC,
13482                              diag::warn_impcast_string_literal_to_bool);
13483     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
13484         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
13485       // This covers the literal expressions that evaluate to Objective-C
13486       // objects.
13487       return DiagnoseImpCast(S, E, T, CC,
13488                              diag::warn_impcast_objective_c_literal_to_bool);
13489     }
13490     if (Source->isPointerType() || Source->canDecayToPointerType()) {
13491       // Warn on pointer to bool conversion that is always true.
13492       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
13493                                      SourceRange(CC));
13494     }
13495   }
13496 
13497   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13498   // is a typedef for signed char (macOS), then that constant value has to be 1
13499   // or 0.
13500   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
13501     Expr::EvalResult Result;
13502     if (E->EvaluateAsInt(Result, S.getASTContext(),
13503                          Expr::SE_AllowSideEffects)) {
13504       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13505         adornObjCBoolConversionDiagWithTernaryFixit(
13506             S, E,
13507             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13508                 << toString(Result.Val.getInt(), 10));
13509       }
13510       return;
13511     }
13512   }
13513 
13514   // Check implicit casts from Objective-C collection literals to specialized
13515   // collection types, e.g., NSArray<NSString *> *.
13516   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13517     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
13518   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13519     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
13520 
13521   // Strip vector types.
13522   if (isa<VectorType>(Source)) {
13523     if (Target->isVLSTBuiltinType() &&
13524         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
13525                                          QualType(Source, 0)) ||
13526          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
13527                                             QualType(Source, 0))))
13528       return;
13529 
13530     if (!isa<VectorType>(Target)) {
13531       if (S.SourceMgr.isInSystemMacro(CC))
13532         return;
13533       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
13534     }
13535 
13536     // If the vector cast is cast between two vectors of the same size, it is
13537     // a bitcast, not a conversion.
13538     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
13539       return;
13540 
13541     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13542     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13543   }
13544   if (auto VecTy = dyn_cast<VectorType>(Target))
13545     Target = VecTy->getElementType().getTypePtr();
13546 
13547   // Strip complex types.
13548   if (isa<ComplexType>(Source)) {
13549     if (!isa<ComplexType>(Target)) {
13550       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13551         return;
13552 
13553       return DiagnoseImpCast(S, E, T, CC,
13554                              S.getLangOpts().CPlusPlus
13555                                  ? diag::err_impcast_complex_scalar
13556                                  : diag::warn_impcast_complex_scalar);
13557     }
13558 
13559     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13560     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13561   }
13562 
13563   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13564   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13565 
13566   // If the source is floating point...
13567   if (SourceBT && SourceBT->isFloatingPoint()) {
13568     // ...and the target is floating point...
13569     if (TargetBT && TargetBT->isFloatingPoint()) {
13570       // ...then warn if we're dropping FP rank.
13571 
13572       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13573           QualType(SourceBT, 0), QualType(TargetBT, 0));
13574       if (Order > 0) {
13575         // Don't warn about float constants that are precisely
13576         // representable in the target type.
13577         Expr::EvalResult result;
13578         if (E->EvaluateAsRValue(result, S.Context)) {
13579           // Value might be a float, a float vector, or a float complex.
13580           if (IsSameFloatAfterCast(result.Val,
13581                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13582                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13583             return;
13584         }
13585 
13586         if (S.SourceMgr.isInSystemMacro(CC))
13587           return;
13588 
13589         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
13590       }
13591       // ... or possibly if we're increasing rank, too
13592       else if (Order < 0) {
13593         if (S.SourceMgr.isInSystemMacro(CC))
13594           return;
13595 
13596         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
13597       }
13598       return;
13599     }
13600 
13601     // If the target is integral, always warn.
13602     if (TargetBT && TargetBT->isInteger()) {
13603       if (S.SourceMgr.isInSystemMacro(CC))
13604         return;
13605 
13606       DiagnoseFloatingImpCast(S, E, T, CC);
13607     }
13608 
13609     // Detect the case where a call result is converted from floating-point to
13610     // to bool, and the final argument to the call is converted from bool, to
13611     // discover this typo:
13612     //
13613     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
13614     //
13615     // FIXME: This is an incredibly special case; is there some more general
13616     // way to detect this class of misplaced-parentheses bug?
13617     if (Target->isBooleanType() && isa<CallExpr>(E)) {
13618       // Check last argument of function call to see if it is an
13619       // implicit cast from a type matching the type the result
13620       // is being cast to.
13621       CallExpr *CEx = cast<CallExpr>(E);
13622       if (unsigned NumArgs = CEx->getNumArgs()) {
13623         Expr *LastA = CEx->getArg(NumArgs - 1);
13624         Expr *InnerE = LastA->IgnoreParenImpCasts();
13625         if (isa<ImplicitCastExpr>(LastA) &&
13626             InnerE->getType()->isBooleanType()) {
13627           // Warn on this floating-point to bool conversion
13628           DiagnoseImpCast(S, E, T, CC,
13629                           diag::warn_impcast_floating_point_to_bool);
13630         }
13631       }
13632     }
13633     return;
13634   }
13635 
13636   // Valid casts involving fixed point types should be accounted for here.
13637   if (Source->isFixedPointType()) {
13638     if (Target->isUnsaturatedFixedPointType()) {
13639       Expr::EvalResult Result;
13640       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
13641                                   S.isConstantEvaluated())) {
13642         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13643         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
13644         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
13645         if (Value > MaxVal || Value < MinVal) {
13646           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13647                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13648                                     << Value.toString() << T
13649                                     << E->getSourceRange()
13650                                     << clang::SourceRange(CC));
13651           return;
13652         }
13653       }
13654     } else if (Target->isIntegerType()) {
13655       Expr::EvalResult Result;
13656       if (!S.isConstantEvaluated() &&
13657           E->EvaluateAsFixedPoint(Result, S.Context,
13658                                   Expr::SE_AllowSideEffects)) {
13659         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13660 
13661         bool Overflowed;
13662         llvm::APSInt IntResult = FXResult.convertToInt(
13663             S.Context.getIntWidth(T),
13664             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
13665 
13666         if (Overflowed) {
13667           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13668                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13669                                     << FXResult.toString() << T
13670                                     << E->getSourceRange()
13671                                     << clang::SourceRange(CC));
13672           return;
13673         }
13674       }
13675     }
13676   } else if (Target->isUnsaturatedFixedPointType()) {
13677     if (Source->isIntegerType()) {
13678       Expr::EvalResult Result;
13679       if (!S.isConstantEvaluated() &&
13680           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13681         llvm::APSInt Value = Result.Val.getInt();
13682 
13683         bool Overflowed;
13684         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13685             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13686 
13687         if (Overflowed) {
13688           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13689                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13690                                     << toString(Value, /*Radix=*/10) << T
13691                                     << E->getSourceRange()
13692                                     << clang::SourceRange(CC));
13693           return;
13694         }
13695       }
13696     }
13697   }
13698 
13699   // If we are casting an integer type to a floating point type without
13700   // initialization-list syntax, we might lose accuracy if the floating
13701   // point type has a narrower significand than the integer type.
13702   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13703       TargetBT->isFloatingType() && !IsListInit) {
13704     // Determine the number of precision bits in the source integer type.
13705     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13706                                         /*Approximate*/ true);
13707     unsigned int SourcePrecision = SourceRange.Width;
13708 
13709     // Determine the number of precision bits in the
13710     // target floating point type.
13711     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13712         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13713 
13714     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13715         SourcePrecision > TargetPrecision) {
13716 
13717       if (Optional<llvm::APSInt> SourceInt =
13718               E->getIntegerConstantExpr(S.Context)) {
13719         // If the source integer is a constant, convert it to the target
13720         // floating point type. Issue a warning if the value changes
13721         // during the whole conversion.
13722         llvm::APFloat TargetFloatValue(
13723             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13724         llvm::APFloat::opStatus ConversionStatus =
13725             TargetFloatValue.convertFromAPInt(
13726                 *SourceInt, SourceBT->isSignedInteger(),
13727                 llvm::APFloat::rmNearestTiesToEven);
13728 
13729         if (ConversionStatus != llvm::APFloat::opOK) {
13730           SmallString<32> PrettySourceValue;
13731           SourceInt->toString(PrettySourceValue, 10);
13732           SmallString<32> PrettyTargetValue;
13733           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13734 
13735           S.DiagRuntimeBehavior(
13736               E->getExprLoc(), E,
13737               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13738                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13739                   << E->getSourceRange() << clang::SourceRange(CC));
13740         }
13741       } else {
13742         // Otherwise, the implicit conversion may lose precision.
13743         DiagnoseImpCast(S, E, T, CC,
13744                         diag::warn_impcast_integer_float_precision);
13745       }
13746     }
13747   }
13748 
13749   DiagnoseNullConversion(S, E, T, CC);
13750 
13751   S.DiscardMisalignedMemberAddress(Target, E);
13752 
13753   if (Target->isBooleanType())
13754     DiagnoseIntInBoolContext(S, E);
13755 
13756   if (!Source->isIntegerType() || !Target->isIntegerType())
13757     return;
13758 
13759   // TODO: remove this early return once the false positives for constant->bool
13760   // in templates, macros, etc, are reduced or removed.
13761   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13762     return;
13763 
13764   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13765       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13766     return adornObjCBoolConversionDiagWithTernaryFixit(
13767         S, E,
13768         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13769             << E->getType());
13770   }
13771 
13772   IntRange SourceTypeRange =
13773       IntRange::forTargetOfCanonicalType(S.Context, Source);
13774   IntRange LikelySourceRange =
13775       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13776   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13777 
13778   if (LikelySourceRange.Width > TargetRange.Width) {
13779     // If the source is a constant, use a default-on diagnostic.
13780     // TODO: this should happen for bitfield stores, too.
13781     Expr::EvalResult Result;
13782     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13783                          S.isConstantEvaluated())) {
13784       llvm::APSInt Value(32);
13785       Value = Result.Val.getInt();
13786 
13787       if (S.SourceMgr.isInSystemMacro(CC))
13788         return;
13789 
13790       std::string PrettySourceValue = toString(Value, 10);
13791       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13792 
13793       S.DiagRuntimeBehavior(
13794           E->getExprLoc(), E,
13795           S.PDiag(diag::warn_impcast_integer_precision_constant)
13796               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13797               << E->getSourceRange() << SourceRange(CC));
13798       return;
13799     }
13800 
13801     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13802     if (S.SourceMgr.isInSystemMacro(CC))
13803       return;
13804 
13805     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13806       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13807                              /* pruneControlFlow */ true);
13808     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13809   }
13810 
13811   if (TargetRange.Width > SourceTypeRange.Width) {
13812     if (auto *UO = dyn_cast<UnaryOperator>(E))
13813       if (UO->getOpcode() == UO_Minus)
13814         if (Source->isUnsignedIntegerType()) {
13815           if (Target->isUnsignedIntegerType())
13816             return DiagnoseImpCast(S, E, T, CC,
13817                                    diag::warn_impcast_high_order_zero_bits);
13818           if (Target->isSignedIntegerType())
13819             return DiagnoseImpCast(S, E, T, CC,
13820                                    diag::warn_impcast_nonnegative_result);
13821         }
13822   }
13823 
13824   if (TargetRange.Width == LikelySourceRange.Width &&
13825       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13826       Source->isSignedIntegerType()) {
13827     // Warn when doing a signed to signed conversion, warn if the positive
13828     // source value is exactly the width of the target type, which will
13829     // cause a negative value to be stored.
13830 
13831     Expr::EvalResult Result;
13832     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13833         !S.SourceMgr.isInSystemMacro(CC)) {
13834       llvm::APSInt Value = Result.Val.getInt();
13835       if (isSameWidthConstantConversion(S, E, T, CC)) {
13836         std::string PrettySourceValue = toString(Value, 10);
13837         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13838 
13839         S.DiagRuntimeBehavior(
13840             E->getExprLoc(), E,
13841             S.PDiag(diag::warn_impcast_integer_precision_constant)
13842                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13843                 << E->getSourceRange() << SourceRange(CC));
13844         return;
13845       }
13846     }
13847 
13848     // Fall through for non-constants to give a sign conversion warning.
13849   }
13850 
13851   if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13852       ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13853        (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13854         LikelySourceRange.Width == TargetRange.Width))) {
13855     if (S.SourceMgr.isInSystemMacro(CC))
13856       return;
13857 
13858     unsigned DiagID = diag::warn_impcast_integer_sign;
13859 
13860     // Traditionally, gcc has warned about this under -Wsign-compare.
13861     // We also want to warn about it in -Wconversion.
13862     // So if -Wconversion is off, use a completely identical diagnostic
13863     // in the sign-compare group.
13864     // The conditional-checking code will
13865     if (ICContext) {
13866       DiagID = diag::warn_impcast_integer_sign_conditional;
13867       *ICContext = true;
13868     }
13869 
13870     return DiagnoseImpCast(S, E, T, CC, DiagID);
13871   }
13872 
13873   // Diagnose conversions between different enumeration types.
13874   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13875   // type, to give us better diagnostics.
13876   QualType SourceType = E->getType();
13877   if (!S.getLangOpts().CPlusPlus) {
13878     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13879       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13880         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13881         SourceType = S.Context.getTypeDeclType(Enum);
13882         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13883       }
13884   }
13885 
13886   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13887     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13888       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13889           TargetEnum->getDecl()->hasNameForLinkage() &&
13890           SourceEnum != TargetEnum) {
13891         if (S.SourceMgr.isInSystemMacro(CC))
13892           return;
13893 
13894         return DiagnoseImpCast(S, E, SourceType, T, CC,
13895                                diag::warn_impcast_different_enum_types);
13896       }
13897 }
13898 
13899 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13900                                      SourceLocation CC, QualType T);
13901 
13902 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13903                                     SourceLocation CC, bool &ICContext) {
13904   E = E->IgnoreParenImpCasts();
13905 
13906   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13907     return CheckConditionalOperator(S, CO, CC, T);
13908 
13909   AnalyzeImplicitConversions(S, E, CC);
13910   if (E->getType() != T)
13911     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13912 }
13913 
13914 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13915                                      SourceLocation CC, QualType T) {
13916   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13917 
13918   Expr *TrueExpr = E->getTrueExpr();
13919   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13920     TrueExpr = BCO->getCommon();
13921 
13922   bool Suspicious = false;
13923   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13924   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13925 
13926   if (T->isBooleanType())
13927     DiagnoseIntInBoolContext(S, E);
13928 
13929   // If -Wconversion would have warned about either of the candidates
13930   // for a signedness conversion to the context type...
13931   if (!Suspicious) return;
13932 
13933   // ...but it's currently ignored...
13934   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13935     return;
13936 
13937   // ...then check whether it would have warned about either of the
13938   // candidates for a signedness conversion to the condition type.
13939   if (E->getType() == T) return;
13940 
13941   Suspicious = false;
13942   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13943                           E->getType(), CC, &Suspicious);
13944   if (!Suspicious)
13945     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13946                             E->getType(), CC, &Suspicious);
13947 }
13948 
13949 /// Check conversion of given expression to boolean.
13950 /// Input argument E is a logical expression.
13951 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13952   if (S.getLangOpts().Bool)
13953     return;
13954   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13955     return;
13956   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13957 }
13958 
13959 namespace {
13960 struct AnalyzeImplicitConversionsWorkItem {
13961   Expr *E;
13962   SourceLocation CC;
13963   bool IsListInit;
13964 };
13965 }
13966 
13967 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13968 /// that should be visited are added to WorkList.
13969 static void AnalyzeImplicitConversions(
13970     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13971     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13972   Expr *OrigE = Item.E;
13973   SourceLocation CC = Item.CC;
13974 
13975   QualType T = OrigE->getType();
13976   Expr *E = OrigE->IgnoreParenImpCasts();
13977 
13978   // Propagate whether we are in a C++ list initialization expression.
13979   // If so, we do not issue warnings for implicit int-float conversion
13980   // precision loss, because C++11 narrowing already handles it.
13981   bool IsListInit = Item.IsListInit ||
13982                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13983 
13984   if (E->isTypeDependent() || E->isValueDependent())
13985     return;
13986 
13987   Expr *SourceExpr = E;
13988   // Examine, but don't traverse into the source expression of an
13989   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13990   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13991   // evaluate it in the context of checking the specific conversion to T though.
13992   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13993     if (auto *Src = OVE->getSourceExpr())
13994       SourceExpr = Src;
13995 
13996   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13997     if (UO->getOpcode() == UO_Not &&
13998         UO->getSubExpr()->isKnownToHaveBooleanValue())
13999       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
14000           << OrigE->getSourceRange() << T->isBooleanType()
14001           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
14002 
14003   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
14004     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14005         BO->getLHS()->isKnownToHaveBooleanValue() &&
14006         BO->getRHS()->isKnownToHaveBooleanValue() &&
14007         BO->getLHS()->HasSideEffects(S.Context) &&
14008         BO->getRHS()->HasSideEffects(S.Context)) {
14009       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
14010           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
14011           << FixItHint::CreateReplacement(
14012                  BO->getOperatorLoc(),
14013                  (BO->getOpcode() == BO_And ? "&&" : "||"));
14014       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
14015     }
14016 
14017   // For conditional operators, we analyze the arguments as if they
14018   // were being fed directly into the output.
14019   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
14020     CheckConditionalOperator(S, CO, CC, T);
14021     return;
14022   }
14023 
14024   // Check implicit argument conversions for function calls.
14025   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
14026     CheckImplicitArgumentConversions(S, Call, CC);
14027 
14028   // Go ahead and check any implicit conversions we might have skipped.
14029   // The non-canonical typecheck is just an optimization;
14030   // CheckImplicitConversion will filter out dead implicit conversions.
14031   if (SourceExpr->getType() != T)
14032     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
14033 
14034   // Now continue drilling into this expression.
14035 
14036   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
14037     // The bound subexpressions in a PseudoObjectExpr are not reachable
14038     // as transitive children.
14039     // FIXME: Use a more uniform representation for this.
14040     for (auto *SE : POE->semantics())
14041       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
14042         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
14043   }
14044 
14045   // Skip past explicit casts.
14046   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
14047     E = CE->getSubExpr()->IgnoreParenImpCasts();
14048     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14049       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
14050     WorkList.push_back({E, CC, IsListInit});
14051     return;
14052   }
14053 
14054   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14055     // Do a somewhat different check with comparison operators.
14056     if (BO->isComparisonOp())
14057       return AnalyzeComparison(S, BO);
14058 
14059     // And with simple assignments.
14060     if (BO->getOpcode() == BO_Assign)
14061       return AnalyzeAssignment(S, BO);
14062     // And with compound assignments.
14063     if (BO->isAssignmentOp())
14064       return AnalyzeCompoundAssignment(S, BO);
14065   }
14066 
14067   // These break the otherwise-useful invariant below.  Fortunately,
14068   // we don't really need to recurse into them, because any internal
14069   // expressions should have been analyzed already when they were
14070   // built into statements.
14071   if (isa<StmtExpr>(E)) return;
14072 
14073   // Don't descend into unevaluated contexts.
14074   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
14075 
14076   // Now just recurse over the expression's children.
14077   CC = E->getExprLoc();
14078   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
14079   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14080   for (Stmt *SubStmt : E->children()) {
14081     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
14082     if (!ChildExpr)
14083       continue;
14084 
14085     if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
14086       if (ChildExpr == CSE->getOperand())
14087         // Do not recurse over a CoroutineSuspendExpr's operand.
14088         // The operand is also a subexpression of getCommonExpr(), and
14089         // recursing into it directly would produce duplicate diagnostics.
14090         continue;
14091 
14092     if (IsLogicalAndOperator &&
14093         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
14094       // Ignore checking string literals that are in logical and operators.
14095       // This is a common pattern for asserts.
14096       continue;
14097     WorkList.push_back({ChildExpr, CC, IsListInit});
14098   }
14099 
14100   if (BO && BO->isLogicalOp()) {
14101     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14102     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14103       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14104 
14105     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14106     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14107       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14108   }
14109 
14110   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
14111     if (U->getOpcode() == UO_LNot) {
14112       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
14113     } else if (U->getOpcode() != UO_AddrOf) {
14114       if (U->getSubExpr()->getType()->isAtomicType())
14115         S.Diag(U->getSubExpr()->getBeginLoc(),
14116                diag::warn_atomic_implicit_seq_cst);
14117     }
14118   }
14119 }
14120 
14121 /// AnalyzeImplicitConversions - Find and report any interesting
14122 /// implicit conversions in the given expression.  There are a couple
14123 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
14124 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
14125                                        bool IsListInit/*= false*/) {
14126   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
14127   WorkList.push_back({OrigE, CC, IsListInit});
14128   while (!WorkList.empty())
14129     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
14130 }
14131 
14132 /// Diagnose integer type and any valid implicit conversion to it.
14133 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
14134   // Taking into account implicit conversions,
14135   // allow any integer.
14136   if (!E->getType()->isIntegerType()) {
14137     S.Diag(E->getBeginLoc(),
14138            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
14139     return true;
14140   }
14141   // Potentially emit standard warnings for implicit conversions if enabled
14142   // using -Wconversion.
14143   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
14144   return false;
14145 }
14146 
14147 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14148 // Returns true when emitting a warning about taking the address of a reference.
14149 static bool CheckForReference(Sema &SemaRef, const Expr *E,
14150                               const PartialDiagnostic &PD) {
14151   E = E->IgnoreParenImpCasts();
14152 
14153   const FunctionDecl *FD = nullptr;
14154 
14155   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14156     if (!DRE->getDecl()->getType()->isReferenceType())
14157       return false;
14158   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14159     if (!M->getMemberDecl()->getType()->isReferenceType())
14160       return false;
14161   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
14162     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
14163       return false;
14164     FD = Call->getDirectCallee();
14165   } else {
14166     return false;
14167   }
14168 
14169   SemaRef.Diag(E->getExprLoc(), PD);
14170 
14171   // If possible, point to location of function.
14172   if (FD) {
14173     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
14174   }
14175 
14176   return true;
14177 }
14178 
14179 // Returns true if the SourceLocation is expanded from any macro body.
14180 // Returns false if the SourceLocation is invalid, is from not in a macro
14181 // expansion, or is from expanded from a top-level macro argument.
14182 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14183   if (Loc.isInvalid())
14184     return false;
14185 
14186   while (Loc.isMacroID()) {
14187     if (SM.isMacroBodyExpansion(Loc))
14188       return true;
14189     Loc = SM.getImmediateMacroCallerLoc(Loc);
14190   }
14191 
14192   return false;
14193 }
14194 
14195 /// Diagnose pointers that are always non-null.
14196 /// \param E the expression containing the pointer
14197 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
14198 /// compared to a null pointer
14199 /// \param IsEqual True when the comparison is equal to a null pointer
14200 /// \param Range Extra SourceRange to highlight in the diagnostic
14201 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
14202                                         Expr::NullPointerConstantKind NullKind,
14203                                         bool IsEqual, SourceRange Range) {
14204   if (!E)
14205     return;
14206 
14207   // Don't warn inside macros.
14208   if (E->getExprLoc().isMacroID()) {
14209     const SourceManager &SM = getSourceManager();
14210     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14211         IsInAnyMacroBody(SM, Range.getBegin()))
14212       return;
14213   }
14214   E = E->IgnoreImpCasts();
14215 
14216   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14217 
14218   if (isa<CXXThisExpr>(E)) {
14219     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14220                                 : diag::warn_this_bool_conversion;
14221     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14222     return;
14223   }
14224 
14225   bool IsAddressOf = false;
14226 
14227   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14228     if (UO->getOpcode() != UO_AddrOf)
14229       return;
14230     IsAddressOf = true;
14231     E = UO->getSubExpr();
14232   }
14233 
14234   if (IsAddressOf) {
14235     unsigned DiagID = IsCompare
14236                           ? diag::warn_address_of_reference_null_compare
14237                           : diag::warn_address_of_reference_bool_conversion;
14238     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14239                                          << IsEqual;
14240     if (CheckForReference(*this, E, PD)) {
14241       return;
14242     }
14243   }
14244 
14245   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14246     bool IsParam = isa<NonNullAttr>(NonnullAttr);
14247     std::string Str;
14248     llvm::raw_string_ostream S(Str);
14249     E->printPretty(S, nullptr, getPrintingPolicy());
14250     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14251                                 : diag::warn_cast_nonnull_to_bool;
14252     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14253       << E->getSourceRange() << Range << IsEqual;
14254     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14255   };
14256 
14257   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14258   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14259     if (auto *Callee = Call->getDirectCallee()) {
14260       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14261         ComplainAboutNonnullParamOrCall(A);
14262         return;
14263       }
14264     }
14265   }
14266 
14267   // Expect to find a single Decl.  Skip anything more complicated.
14268   ValueDecl *D = nullptr;
14269   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14270     D = R->getDecl();
14271   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14272     D = M->getMemberDecl();
14273   }
14274 
14275   // Weak Decls can be null.
14276   if (!D || D->isWeak())
14277     return;
14278 
14279   // Check for parameter decl with nonnull attribute
14280   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14281     if (getCurFunction() &&
14282         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14283       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14284         ComplainAboutNonnullParamOrCall(A);
14285         return;
14286       }
14287 
14288       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14289         // Skip function template not specialized yet.
14290         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
14291           return;
14292         auto ParamIter = llvm::find(FD->parameters(), PV);
14293         assert(ParamIter != FD->param_end());
14294         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14295 
14296         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14297           if (!NonNull->args_size()) {
14298               ComplainAboutNonnullParamOrCall(NonNull);
14299               return;
14300           }
14301 
14302           for (const ParamIdx &ArgNo : NonNull->args()) {
14303             if (ArgNo.getASTIndex() == ParamNo) {
14304               ComplainAboutNonnullParamOrCall(NonNull);
14305               return;
14306             }
14307           }
14308         }
14309       }
14310     }
14311   }
14312 
14313   QualType T = D->getType();
14314   const bool IsArray = T->isArrayType();
14315   const bool IsFunction = T->isFunctionType();
14316 
14317   // Address of function is used to silence the function warning.
14318   if (IsAddressOf && IsFunction) {
14319     return;
14320   }
14321 
14322   // Found nothing.
14323   if (!IsAddressOf && !IsFunction && !IsArray)
14324     return;
14325 
14326   // Pretty print the expression for the diagnostic.
14327   std::string Str;
14328   llvm::raw_string_ostream S(Str);
14329   E->printPretty(S, nullptr, getPrintingPolicy());
14330 
14331   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14332                               : diag::warn_impcast_pointer_to_bool;
14333   enum {
14334     AddressOf,
14335     FunctionPointer,
14336     ArrayPointer
14337   } DiagType;
14338   if (IsAddressOf)
14339     DiagType = AddressOf;
14340   else if (IsFunction)
14341     DiagType = FunctionPointer;
14342   else if (IsArray)
14343     DiagType = ArrayPointer;
14344   else
14345     llvm_unreachable("Could not determine diagnostic.");
14346   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14347                                 << Range << IsEqual;
14348 
14349   if (!IsFunction)
14350     return;
14351 
14352   // Suggest '&' to silence the function warning.
14353   Diag(E->getExprLoc(), diag::note_function_warning_silence)
14354       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
14355 
14356   // Check to see if '()' fixit should be emitted.
14357   QualType ReturnType;
14358   UnresolvedSet<4> NonTemplateOverloads;
14359   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14360   if (ReturnType.isNull())
14361     return;
14362 
14363   if (IsCompare) {
14364     // There are two cases here.  If there is null constant, the only suggest
14365     // for a pointer return type.  If the null is 0, then suggest if the return
14366     // type is a pointer or an integer type.
14367     if (!ReturnType->isPointerType()) {
14368       if (NullKind == Expr::NPCK_ZeroExpression ||
14369           NullKind == Expr::NPCK_ZeroLiteral) {
14370         if (!ReturnType->isIntegerType())
14371           return;
14372       } else {
14373         return;
14374       }
14375     }
14376   } else { // !IsCompare
14377     // For function to bool, only suggest if the function pointer has bool
14378     // return type.
14379     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14380       return;
14381   }
14382   Diag(E->getExprLoc(), diag::note_function_to_function_call)
14383       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
14384 }
14385 
14386 /// Diagnoses "dangerous" implicit conversions within the given
14387 /// expression (which is a full expression).  Implements -Wconversion
14388 /// and -Wsign-compare.
14389 ///
14390 /// \param CC the "context" location of the implicit conversion, i.e.
14391 ///   the most location of the syntactic entity requiring the implicit
14392 ///   conversion
14393 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14394   // Don't diagnose in unevaluated contexts.
14395   if (isUnevaluatedContext())
14396     return;
14397 
14398   // Don't diagnose for value- or type-dependent expressions.
14399   if (E->isTypeDependent() || E->isValueDependent())
14400     return;
14401 
14402   // Check for array bounds violations in cases where the check isn't triggered
14403   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14404   // ArraySubscriptExpr is on the RHS of a variable initialization.
14405   CheckArrayAccess(E);
14406 
14407   // This is not the right CC for (e.g.) a variable initialization.
14408   AnalyzeImplicitConversions(*this, E, CC);
14409 }
14410 
14411 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
14412 /// Input argument E is a logical expression.
14413 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14414   ::CheckBoolLikeConversion(*this, E, CC);
14415 }
14416 
14417 /// Diagnose when expression is an integer constant expression and its evaluation
14418 /// results in integer overflow
14419 void Sema::CheckForIntOverflow (Expr *E) {
14420   // Use a work list to deal with nested struct initializers.
14421   SmallVector<Expr *, 2> Exprs(1, E);
14422 
14423   do {
14424     Expr *OriginalE = Exprs.pop_back_val();
14425     Expr *E = OriginalE->IgnoreParenCasts();
14426 
14427     if (isa<BinaryOperator>(E)) {
14428       E->EvaluateForOverflow(Context);
14429       continue;
14430     }
14431 
14432     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
14433       Exprs.append(InitList->inits().begin(), InitList->inits().end());
14434     else if (isa<ObjCBoxedExpr>(OriginalE))
14435       E->EvaluateForOverflow(Context);
14436     else if (auto Call = dyn_cast<CallExpr>(E))
14437       Exprs.append(Call->arg_begin(), Call->arg_end());
14438     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
14439       Exprs.append(Message->arg_begin(), Message->arg_end());
14440   } while (!Exprs.empty());
14441 }
14442 
14443 namespace {
14444 
14445 /// Visitor for expressions which looks for unsequenced operations on the
14446 /// same object.
14447 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14448   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14449 
14450   /// A tree of sequenced regions within an expression. Two regions are
14451   /// unsequenced if one is an ancestor or a descendent of the other. When we
14452   /// finish processing an expression with sequencing, such as a comma
14453   /// expression, we fold its tree nodes into its parent, since they are
14454   /// unsequenced with respect to nodes we will visit later.
14455   class SequenceTree {
14456     struct Value {
14457       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14458       unsigned Parent : 31;
14459       unsigned Merged : 1;
14460     };
14461     SmallVector<Value, 8> Values;
14462 
14463   public:
14464     /// A region within an expression which may be sequenced with respect
14465     /// to some other region.
14466     class Seq {
14467       friend class SequenceTree;
14468 
14469       unsigned Index;
14470 
14471       explicit Seq(unsigned N) : Index(N) {}
14472 
14473     public:
14474       Seq() : Index(0) {}
14475     };
14476 
14477     SequenceTree() { Values.push_back(Value(0)); }
14478     Seq root() const { return Seq(0); }
14479 
14480     /// Create a new sequence of operations, which is an unsequenced
14481     /// subset of \p Parent. This sequence of operations is sequenced with
14482     /// respect to other children of \p Parent.
14483     Seq allocate(Seq Parent) {
14484       Values.push_back(Value(Parent.Index));
14485       return Seq(Values.size() - 1);
14486     }
14487 
14488     /// Merge a sequence of operations into its parent.
14489     void merge(Seq S) {
14490       Values[S.Index].Merged = true;
14491     }
14492 
14493     /// Determine whether two operations are unsequenced. This operation
14494     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14495     /// should have been merged into its parent as appropriate.
14496     bool isUnsequenced(Seq Cur, Seq Old) {
14497       unsigned C = representative(Cur.Index);
14498       unsigned Target = representative(Old.Index);
14499       while (C >= Target) {
14500         if (C == Target)
14501           return true;
14502         C = Values[C].Parent;
14503       }
14504       return false;
14505     }
14506 
14507   private:
14508     /// Pick a representative for a sequence.
14509     unsigned representative(unsigned K) {
14510       if (Values[K].Merged)
14511         // Perform path compression as we go.
14512         return Values[K].Parent = representative(Values[K].Parent);
14513       return K;
14514     }
14515   };
14516 
14517   /// An object for which we can track unsequenced uses.
14518   using Object = const NamedDecl *;
14519 
14520   /// Different flavors of object usage which we track. We only track the
14521   /// least-sequenced usage of each kind.
14522   enum UsageKind {
14523     /// A read of an object. Multiple unsequenced reads are OK.
14524     UK_Use,
14525 
14526     /// A modification of an object which is sequenced before the value
14527     /// computation of the expression, such as ++n in C++.
14528     UK_ModAsValue,
14529 
14530     /// A modification of an object which is not sequenced before the value
14531     /// computation of the expression, such as n++.
14532     UK_ModAsSideEffect,
14533 
14534     UK_Count = UK_ModAsSideEffect + 1
14535   };
14536 
14537   /// Bundle together a sequencing region and the expression corresponding
14538   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14539   struct Usage {
14540     const Expr *UsageExpr;
14541     SequenceTree::Seq Seq;
14542 
14543     Usage() : UsageExpr(nullptr) {}
14544   };
14545 
14546   struct UsageInfo {
14547     Usage Uses[UK_Count];
14548 
14549     /// Have we issued a diagnostic for this object already?
14550     bool Diagnosed;
14551 
14552     UsageInfo() : Diagnosed(false) {}
14553   };
14554   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14555 
14556   Sema &SemaRef;
14557 
14558   /// Sequenced regions within the expression.
14559   SequenceTree Tree;
14560 
14561   /// Declaration modifications and references which we have seen.
14562   UsageInfoMap UsageMap;
14563 
14564   /// The region we are currently within.
14565   SequenceTree::Seq Region;
14566 
14567   /// Filled in with declarations which were modified as a side-effect
14568   /// (that is, post-increment operations).
14569   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14570 
14571   /// Expressions to check later. We defer checking these to reduce
14572   /// stack usage.
14573   SmallVectorImpl<const Expr *> &WorkList;
14574 
14575   /// RAII object wrapping the visitation of a sequenced subexpression of an
14576   /// expression. At the end of this process, the side-effects of the evaluation
14577   /// become sequenced with respect to the value computation of the result, so
14578   /// we downgrade any UK_ModAsSideEffect within the evaluation to
14579   /// UK_ModAsValue.
14580   struct SequencedSubexpression {
14581     SequencedSubexpression(SequenceChecker &Self)
14582       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14583       Self.ModAsSideEffect = &ModAsSideEffect;
14584     }
14585 
14586     ~SequencedSubexpression() {
14587       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14588         // Add a new usage with usage kind UK_ModAsValue, and then restore
14589         // the previous usage with UK_ModAsSideEffect (thus clearing it if
14590         // the previous one was empty).
14591         UsageInfo &UI = Self.UsageMap[M.first];
14592         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14593         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14594         SideEffectUsage = M.second;
14595       }
14596       Self.ModAsSideEffect = OldModAsSideEffect;
14597     }
14598 
14599     SequenceChecker &Self;
14600     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14601     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14602   };
14603 
14604   /// RAII object wrapping the visitation of a subexpression which we might
14605   /// choose to evaluate as a constant. If any subexpression is evaluated and
14606   /// found to be non-constant, this allows us to suppress the evaluation of
14607   /// the outer expression.
14608   class EvaluationTracker {
14609   public:
14610     EvaluationTracker(SequenceChecker &Self)
14611         : Self(Self), Prev(Self.EvalTracker) {
14612       Self.EvalTracker = this;
14613     }
14614 
14615     ~EvaluationTracker() {
14616       Self.EvalTracker = Prev;
14617       if (Prev)
14618         Prev->EvalOK &= EvalOK;
14619     }
14620 
14621     bool evaluate(const Expr *E, bool &Result) {
14622       if (!EvalOK || E->isValueDependent())
14623         return false;
14624       EvalOK = E->EvaluateAsBooleanCondition(
14625           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
14626       return EvalOK;
14627     }
14628 
14629   private:
14630     SequenceChecker &Self;
14631     EvaluationTracker *Prev;
14632     bool EvalOK = true;
14633   } *EvalTracker = nullptr;
14634 
14635   /// Find the object which is produced by the specified expression,
14636   /// if any.
14637   Object getObject(const Expr *E, bool Mod) const {
14638     E = E->IgnoreParenCasts();
14639     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14640       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14641         return getObject(UO->getSubExpr(), Mod);
14642     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14643       if (BO->getOpcode() == BO_Comma)
14644         return getObject(BO->getRHS(), Mod);
14645       if (Mod && BO->isAssignmentOp())
14646         return getObject(BO->getLHS(), Mod);
14647     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14648       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14649       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14650         return ME->getMemberDecl();
14651     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14652       // FIXME: If this is a reference, map through to its value.
14653       return DRE->getDecl();
14654     return nullptr;
14655   }
14656 
14657   /// Note that an object \p O was modified or used by an expression
14658   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14659   /// the object \p O as obtained via the \p UsageMap.
14660   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14661     // Get the old usage for the given object and usage kind.
14662     Usage &U = UI.Uses[UK];
14663     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14664       // If we have a modification as side effect and are in a sequenced
14665       // subexpression, save the old Usage so that we can restore it later
14666       // in SequencedSubexpression::~SequencedSubexpression.
14667       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14668         ModAsSideEffect->push_back(std::make_pair(O, U));
14669       // Then record the new usage with the current sequencing region.
14670       U.UsageExpr = UsageExpr;
14671       U.Seq = Region;
14672     }
14673   }
14674 
14675   /// Check whether a modification or use of an object \p O in an expression
14676   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14677   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14678   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14679   /// usage and false we are checking for a mod-use unsequenced usage.
14680   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14681                   UsageKind OtherKind, bool IsModMod) {
14682     if (UI.Diagnosed)
14683       return;
14684 
14685     const Usage &U = UI.Uses[OtherKind];
14686     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14687       return;
14688 
14689     const Expr *Mod = U.UsageExpr;
14690     const Expr *ModOrUse = UsageExpr;
14691     if (OtherKind == UK_Use)
14692       std::swap(Mod, ModOrUse);
14693 
14694     SemaRef.DiagRuntimeBehavior(
14695         Mod->getExprLoc(), {Mod, ModOrUse},
14696         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14697                                : diag::warn_unsequenced_mod_use)
14698             << O << SourceRange(ModOrUse->getExprLoc()));
14699     UI.Diagnosed = true;
14700   }
14701 
14702   // A note on note{Pre, Post}{Use, Mod}:
14703   //
14704   // (It helps to follow the algorithm with an expression such as
14705   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14706   //  operations before C++17 and both are well-defined in C++17).
14707   //
14708   // When visiting a node which uses/modify an object we first call notePreUse
14709   // or notePreMod before visiting its sub-expression(s). At this point the
14710   // children of the current node have not yet been visited and so the eventual
14711   // uses/modifications resulting from the children of the current node have not
14712   // been recorded yet.
14713   //
14714   // We then visit the children of the current node. After that notePostUse or
14715   // notePostMod is called. These will 1) detect an unsequenced modification
14716   // as side effect (as in "k++ + k") and 2) add a new usage with the
14717   // appropriate usage kind.
14718   //
14719   // We also have to be careful that some operation sequences modification as
14720   // side effect as well (for example: || or ,). To account for this we wrap
14721   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14722   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14723   // which record usages which are modifications as side effect, and then
14724   // downgrade them (or more accurately restore the previous usage which was a
14725   // modification as side effect) when exiting the scope of the sequenced
14726   // subexpression.
14727 
14728   void notePreUse(Object O, const Expr *UseExpr) {
14729     UsageInfo &UI = UsageMap[O];
14730     // Uses conflict with other modifications.
14731     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14732   }
14733 
14734   void notePostUse(Object O, const Expr *UseExpr) {
14735     UsageInfo &UI = UsageMap[O];
14736     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14737                /*IsModMod=*/false);
14738     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14739   }
14740 
14741   void notePreMod(Object O, const Expr *ModExpr) {
14742     UsageInfo &UI = UsageMap[O];
14743     // Modifications conflict with other modifications and with uses.
14744     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14745     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14746   }
14747 
14748   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14749     UsageInfo &UI = UsageMap[O];
14750     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14751                /*IsModMod=*/true);
14752     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14753   }
14754 
14755 public:
14756   SequenceChecker(Sema &S, const Expr *E,
14757                   SmallVectorImpl<const Expr *> &WorkList)
14758       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14759     Visit(E);
14760     // Silence a -Wunused-private-field since WorkList is now unused.
14761     // TODO: Evaluate if it can be used, and if not remove it.
14762     (void)this->WorkList;
14763   }
14764 
14765   void VisitStmt(const Stmt *S) {
14766     // Skip all statements which aren't expressions for now.
14767   }
14768 
14769   void VisitExpr(const Expr *E) {
14770     // By default, just recurse to evaluated subexpressions.
14771     Base::VisitStmt(E);
14772   }
14773 
14774   void VisitCastExpr(const CastExpr *E) {
14775     Object O = Object();
14776     if (E->getCastKind() == CK_LValueToRValue)
14777       O = getObject(E->getSubExpr(), false);
14778 
14779     if (O)
14780       notePreUse(O, E);
14781     VisitExpr(E);
14782     if (O)
14783       notePostUse(O, E);
14784   }
14785 
14786   void VisitSequencedExpressions(const Expr *SequencedBefore,
14787                                  const Expr *SequencedAfter) {
14788     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14789     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14790     SequenceTree::Seq OldRegion = Region;
14791 
14792     {
14793       SequencedSubexpression SeqBefore(*this);
14794       Region = BeforeRegion;
14795       Visit(SequencedBefore);
14796     }
14797 
14798     Region = AfterRegion;
14799     Visit(SequencedAfter);
14800 
14801     Region = OldRegion;
14802 
14803     Tree.merge(BeforeRegion);
14804     Tree.merge(AfterRegion);
14805   }
14806 
14807   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14808     // C++17 [expr.sub]p1:
14809     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14810     //   expression E1 is sequenced before the expression E2.
14811     if (SemaRef.getLangOpts().CPlusPlus17)
14812       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14813     else {
14814       Visit(ASE->getLHS());
14815       Visit(ASE->getRHS());
14816     }
14817   }
14818 
14819   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14820   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14821   void VisitBinPtrMem(const BinaryOperator *BO) {
14822     // C++17 [expr.mptr.oper]p4:
14823     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14824     //  the expression E1 is sequenced before the expression E2.
14825     if (SemaRef.getLangOpts().CPlusPlus17)
14826       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14827     else {
14828       Visit(BO->getLHS());
14829       Visit(BO->getRHS());
14830     }
14831   }
14832 
14833   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14834   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14835   void VisitBinShlShr(const BinaryOperator *BO) {
14836     // C++17 [expr.shift]p4:
14837     //  The expression E1 is sequenced before the expression E2.
14838     if (SemaRef.getLangOpts().CPlusPlus17)
14839       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14840     else {
14841       Visit(BO->getLHS());
14842       Visit(BO->getRHS());
14843     }
14844   }
14845 
14846   void VisitBinComma(const BinaryOperator *BO) {
14847     // C++11 [expr.comma]p1:
14848     //   Every value computation and side effect associated with the left
14849     //   expression is sequenced before every value computation and side
14850     //   effect associated with the right expression.
14851     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14852   }
14853 
14854   void VisitBinAssign(const BinaryOperator *BO) {
14855     SequenceTree::Seq RHSRegion;
14856     SequenceTree::Seq LHSRegion;
14857     if (SemaRef.getLangOpts().CPlusPlus17) {
14858       RHSRegion = Tree.allocate(Region);
14859       LHSRegion = Tree.allocate(Region);
14860     } else {
14861       RHSRegion = Region;
14862       LHSRegion = Region;
14863     }
14864     SequenceTree::Seq OldRegion = Region;
14865 
14866     // C++11 [expr.ass]p1:
14867     //  [...] the assignment is sequenced after the value computation
14868     //  of the right and left operands, [...]
14869     //
14870     // so check it before inspecting the operands and update the
14871     // map afterwards.
14872     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14873     if (O)
14874       notePreMod(O, BO);
14875 
14876     if (SemaRef.getLangOpts().CPlusPlus17) {
14877       // C++17 [expr.ass]p1:
14878       //  [...] The right operand is sequenced before the left operand. [...]
14879       {
14880         SequencedSubexpression SeqBefore(*this);
14881         Region = RHSRegion;
14882         Visit(BO->getRHS());
14883       }
14884 
14885       Region = LHSRegion;
14886       Visit(BO->getLHS());
14887 
14888       if (O && isa<CompoundAssignOperator>(BO))
14889         notePostUse(O, BO);
14890 
14891     } else {
14892       // C++11 does not specify any sequencing between the LHS and RHS.
14893       Region = LHSRegion;
14894       Visit(BO->getLHS());
14895 
14896       if (O && isa<CompoundAssignOperator>(BO))
14897         notePostUse(O, BO);
14898 
14899       Region = RHSRegion;
14900       Visit(BO->getRHS());
14901     }
14902 
14903     // C++11 [expr.ass]p1:
14904     //  the assignment is sequenced [...] before the value computation of the
14905     //  assignment expression.
14906     // C11 6.5.16/3 has no such rule.
14907     Region = OldRegion;
14908     if (O)
14909       notePostMod(O, BO,
14910                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14911                                                   : UK_ModAsSideEffect);
14912     if (SemaRef.getLangOpts().CPlusPlus17) {
14913       Tree.merge(RHSRegion);
14914       Tree.merge(LHSRegion);
14915     }
14916   }
14917 
14918   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14919     VisitBinAssign(CAO);
14920   }
14921 
14922   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14923   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14924   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14925     Object O = getObject(UO->getSubExpr(), true);
14926     if (!O)
14927       return VisitExpr(UO);
14928 
14929     notePreMod(O, UO);
14930     Visit(UO->getSubExpr());
14931     // C++11 [expr.pre.incr]p1:
14932     //   the expression ++x is equivalent to x+=1
14933     notePostMod(O, UO,
14934                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14935                                                 : UK_ModAsSideEffect);
14936   }
14937 
14938   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14939   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14940   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14941     Object O = getObject(UO->getSubExpr(), true);
14942     if (!O)
14943       return VisitExpr(UO);
14944 
14945     notePreMod(O, UO);
14946     Visit(UO->getSubExpr());
14947     notePostMod(O, UO, UK_ModAsSideEffect);
14948   }
14949 
14950   void VisitBinLOr(const BinaryOperator *BO) {
14951     // C++11 [expr.log.or]p2:
14952     //  If the second expression is evaluated, every value computation and
14953     //  side effect associated with the first expression is sequenced before
14954     //  every value computation and side effect associated with the
14955     //  second expression.
14956     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14957     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14958     SequenceTree::Seq OldRegion = Region;
14959 
14960     EvaluationTracker Eval(*this);
14961     {
14962       SequencedSubexpression Sequenced(*this);
14963       Region = LHSRegion;
14964       Visit(BO->getLHS());
14965     }
14966 
14967     // C++11 [expr.log.or]p1:
14968     //  [...] the second operand is not evaluated if the first operand
14969     //  evaluates to true.
14970     bool EvalResult = false;
14971     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14972     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14973     if (ShouldVisitRHS) {
14974       Region = RHSRegion;
14975       Visit(BO->getRHS());
14976     }
14977 
14978     Region = OldRegion;
14979     Tree.merge(LHSRegion);
14980     Tree.merge(RHSRegion);
14981   }
14982 
14983   void VisitBinLAnd(const BinaryOperator *BO) {
14984     // C++11 [expr.log.and]p2:
14985     //  If the second expression is evaluated, every value computation and
14986     //  side effect associated with the first expression is sequenced before
14987     //  every value computation and side effect associated with the
14988     //  second expression.
14989     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14990     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14991     SequenceTree::Seq OldRegion = Region;
14992 
14993     EvaluationTracker Eval(*this);
14994     {
14995       SequencedSubexpression Sequenced(*this);
14996       Region = LHSRegion;
14997       Visit(BO->getLHS());
14998     }
14999 
15000     // C++11 [expr.log.and]p1:
15001     //  [...] the second operand is not evaluated if the first operand is false.
15002     bool EvalResult = false;
15003     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15004     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
15005     if (ShouldVisitRHS) {
15006       Region = RHSRegion;
15007       Visit(BO->getRHS());
15008     }
15009 
15010     Region = OldRegion;
15011     Tree.merge(LHSRegion);
15012     Tree.merge(RHSRegion);
15013   }
15014 
15015   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15016     // C++11 [expr.cond]p1:
15017     //  [...] Every value computation and side effect associated with the first
15018     //  expression is sequenced before every value computation and side effect
15019     //  associated with the second or third expression.
15020     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
15021 
15022     // No sequencing is specified between the true and false expression.
15023     // However since exactly one of both is going to be evaluated we can
15024     // consider them to be sequenced. This is needed to avoid warning on
15025     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15026     // both the true and false expressions because we can't evaluate x.
15027     // This will still allow us to detect an expression like (pre C++17)
15028     // "(x ? y += 1 : y += 2) = y".
15029     //
15030     // We don't wrap the visitation of the true and false expression with
15031     // SequencedSubexpression because we don't want to downgrade modifications
15032     // as side effect in the true and false expressions after the visition
15033     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15034     // not warn between the two "y++", but we should warn between the "y++"
15035     // and the "y".
15036     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
15037     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
15038     SequenceTree::Seq OldRegion = Region;
15039 
15040     EvaluationTracker Eval(*this);
15041     {
15042       SequencedSubexpression Sequenced(*this);
15043       Region = ConditionRegion;
15044       Visit(CO->getCond());
15045     }
15046 
15047     // C++11 [expr.cond]p1:
15048     // [...] The first expression is contextually converted to bool (Clause 4).
15049     // It is evaluated and if it is true, the result of the conditional
15050     // expression is the value of the second expression, otherwise that of the
15051     // third expression. Only one of the second and third expressions is
15052     // evaluated. [...]
15053     bool EvalResult = false;
15054     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
15055     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
15056     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
15057     if (ShouldVisitTrueExpr) {
15058       Region = TrueRegion;
15059       Visit(CO->getTrueExpr());
15060     }
15061     if (ShouldVisitFalseExpr) {
15062       Region = FalseRegion;
15063       Visit(CO->getFalseExpr());
15064     }
15065 
15066     Region = OldRegion;
15067     Tree.merge(ConditionRegion);
15068     Tree.merge(TrueRegion);
15069     Tree.merge(FalseRegion);
15070   }
15071 
15072   void VisitCallExpr(const CallExpr *CE) {
15073     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15074 
15075     if (CE->isUnevaluatedBuiltinCall(Context))
15076       return;
15077 
15078     // C++11 [intro.execution]p15:
15079     //   When calling a function [...], every value computation and side effect
15080     //   associated with any argument expression, or with the postfix expression
15081     //   designating the called function, is sequenced before execution of every
15082     //   expression or statement in the body of the function [and thus before
15083     //   the value computation of its result].
15084     SequencedSubexpression Sequenced(*this);
15085     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
15086       // C++17 [expr.call]p5
15087       //   The postfix-expression is sequenced before each expression in the
15088       //   expression-list and any default argument. [...]
15089       SequenceTree::Seq CalleeRegion;
15090       SequenceTree::Seq OtherRegion;
15091       if (SemaRef.getLangOpts().CPlusPlus17) {
15092         CalleeRegion = Tree.allocate(Region);
15093         OtherRegion = Tree.allocate(Region);
15094       } else {
15095         CalleeRegion = Region;
15096         OtherRegion = Region;
15097       }
15098       SequenceTree::Seq OldRegion = Region;
15099 
15100       // Visit the callee expression first.
15101       Region = CalleeRegion;
15102       if (SemaRef.getLangOpts().CPlusPlus17) {
15103         SequencedSubexpression Sequenced(*this);
15104         Visit(CE->getCallee());
15105       } else {
15106         Visit(CE->getCallee());
15107       }
15108 
15109       // Then visit the argument expressions.
15110       Region = OtherRegion;
15111       for (const Expr *Argument : CE->arguments())
15112         Visit(Argument);
15113 
15114       Region = OldRegion;
15115       if (SemaRef.getLangOpts().CPlusPlus17) {
15116         Tree.merge(CalleeRegion);
15117         Tree.merge(OtherRegion);
15118       }
15119     });
15120   }
15121 
15122   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15123     // C++17 [over.match.oper]p2:
15124     //   [...] the operator notation is first transformed to the equivalent
15125     //   function-call notation as summarized in Table 12 (where @ denotes one
15126     //   of the operators covered in the specified subclause). However, the
15127     //   operands are sequenced in the order prescribed for the built-in
15128     //   operator (Clause 8).
15129     //
15130     // From the above only overloaded binary operators and overloaded call
15131     // operators have sequencing rules in C++17 that we need to handle
15132     // separately.
15133     if (!SemaRef.getLangOpts().CPlusPlus17 ||
15134         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15135       return VisitCallExpr(CXXOCE);
15136 
15137     enum {
15138       NoSequencing,
15139       LHSBeforeRHS,
15140       RHSBeforeLHS,
15141       LHSBeforeRest
15142     } SequencingKind;
15143     switch (CXXOCE->getOperator()) {
15144     case OO_Equal:
15145     case OO_PlusEqual:
15146     case OO_MinusEqual:
15147     case OO_StarEqual:
15148     case OO_SlashEqual:
15149     case OO_PercentEqual:
15150     case OO_CaretEqual:
15151     case OO_AmpEqual:
15152     case OO_PipeEqual:
15153     case OO_LessLessEqual:
15154     case OO_GreaterGreaterEqual:
15155       SequencingKind = RHSBeforeLHS;
15156       break;
15157 
15158     case OO_LessLess:
15159     case OO_GreaterGreater:
15160     case OO_AmpAmp:
15161     case OO_PipePipe:
15162     case OO_Comma:
15163     case OO_ArrowStar:
15164     case OO_Subscript:
15165       SequencingKind = LHSBeforeRHS;
15166       break;
15167 
15168     case OO_Call:
15169       SequencingKind = LHSBeforeRest;
15170       break;
15171 
15172     default:
15173       SequencingKind = NoSequencing;
15174       break;
15175     }
15176 
15177     if (SequencingKind == NoSequencing)
15178       return VisitCallExpr(CXXOCE);
15179 
15180     // This is a call, so all subexpressions are sequenced before the result.
15181     SequencedSubexpression Sequenced(*this);
15182 
15183     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15184       assert(SemaRef.getLangOpts().CPlusPlus17 &&
15185              "Should only get there with C++17 and above!");
15186       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15187              "Should only get there with an overloaded binary operator"
15188              " or an overloaded call operator!");
15189 
15190       if (SequencingKind == LHSBeforeRest) {
15191         assert(CXXOCE->getOperator() == OO_Call &&
15192                "We should only have an overloaded call operator here!");
15193 
15194         // This is very similar to VisitCallExpr, except that we only have the
15195         // C++17 case. The postfix-expression is the first argument of the
15196         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15197         // are in the following arguments.
15198         //
15199         // Note that we intentionally do not visit the callee expression since
15200         // it is just a decayed reference to a function.
15201         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15202         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15203         SequenceTree::Seq OldRegion = Region;
15204 
15205         assert(CXXOCE->getNumArgs() >= 1 &&
15206                "An overloaded call operator must have at least one argument"
15207                " for the postfix-expression!");
15208         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15209         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15210                                           CXXOCE->getNumArgs() - 1);
15211 
15212         // Visit the postfix-expression first.
15213         {
15214           Region = PostfixExprRegion;
15215           SequencedSubexpression Sequenced(*this);
15216           Visit(PostfixExpr);
15217         }
15218 
15219         // Then visit the argument expressions.
15220         Region = ArgsRegion;
15221         for (const Expr *Arg : Args)
15222           Visit(Arg);
15223 
15224         Region = OldRegion;
15225         Tree.merge(PostfixExprRegion);
15226         Tree.merge(ArgsRegion);
15227       } else {
15228         assert(CXXOCE->getNumArgs() == 2 &&
15229                "Should only have two arguments here!");
15230         assert((SequencingKind == LHSBeforeRHS ||
15231                 SequencingKind == RHSBeforeLHS) &&
15232                "Unexpected sequencing kind!");
15233 
15234         // We do not visit the callee expression since it is just a decayed
15235         // reference to a function.
15236         const Expr *E1 = CXXOCE->getArg(0);
15237         const Expr *E2 = CXXOCE->getArg(1);
15238         if (SequencingKind == RHSBeforeLHS)
15239           std::swap(E1, E2);
15240 
15241         return VisitSequencedExpressions(E1, E2);
15242       }
15243     });
15244   }
15245 
15246   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15247     // This is a call, so all subexpressions are sequenced before the result.
15248     SequencedSubexpression Sequenced(*this);
15249 
15250     if (!CCE->isListInitialization())
15251       return VisitExpr(CCE);
15252 
15253     // In C++11, list initializations are sequenced.
15254     SmallVector<SequenceTree::Seq, 32> Elts;
15255     SequenceTree::Seq Parent = Region;
15256     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
15257                                               E = CCE->arg_end();
15258          I != E; ++I) {
15259       Region = Tree.allocate(Parent);
15260       Elts.push_back(Region);
15261       Visit(*I);
15262     }
15263 
15264     // Forget that the initializers are sequenced.
15265     Region = Parent;
15266     for (unsigned I = 0; I < Elts.size(); ++I)
15267       Tree.merge(Elts[I]);
15268   }
15269 
15270   void VisitInitListExpr(const InitListExpr *ILE) {
15271     if (!SemaRef.getLangOpts().CPlusPlus11)
15272       return VisitExpr(ILE);
15273 
15274     // In C++11, list initializations are sequenced.
15275     SmallVector<SequenceTree::Seq, 32> Elts;
15276     SequenceTree::Seq Parent = Region;
15277     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
15278       const Expr *E = ILE->getInit(I);
15279       if (!E)
15280         continue;
15281       Region = Tree.allocate(Parent);
15282       Elts.push_back(Region);
15283       Visit(E);
15284     }
15285 
15286     // Forget that the initializers are sequenced.
15287     Region = Parent;
15288     for (unsigned I = 0; I < Elts.size(); ++I)
15289       Tree.merge(Elts[I]);
15290   }
15291 };
15292 
15293 } // namespace
15294 
15295 void Sema::CheckUnsequencedOperations(const Expr *E) {
15296   SmallVector<const Expr *, 8> WorkList;
15297   WorkList.push_back(E);
15298   while (!WorkList.empty()) {
15299     const Expr *Item = WorkList.pop_back_val();
15300     SequenceChecker(*this, Item, WorkList);
15301   }
15302 }
15303 
15304 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15305                               bool IsConstexpr) {
15306   llvm::SaveAndRestore<bool> ConstantContext(
15307       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
15308   CheckImplicitConversions(E, CheckLoc);
15309   if (!E->isInstantiationDependent())
15310     CheckUnsequencedOperations(E);
15311   if (!IsConstexpr && !E->isValueDependent())
15312     CheckForIntOverflow(E);
15313   DiagnoseMisalignedMembers();
15314 }
15315 
15316 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15317                                        FieldDecl *BitField,
15318                                        Expr *Init) {
15319   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15320 }
15321 
15322 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
15323                                          SourceLocation Loc) {
15324   if (!PType->isVariablyModifiedType())
15325     return;
15326   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15327     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15328     return;
15329   }
15330   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15331     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15332     return;
15333   }
15334   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15335     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15336     return;
15337   }
15338 
15339   const ArrayType *AT = S.Context.getAsArrayType(PType);
15340   if (!AT)
15341     return;
15342 
15343   if (AT->getSizeModifier() != ArrayType::Star) {
15344     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
15345     return;
15346   }
15347 
15348   S.Diag(Loc, diag::err_array_star_in_function_definition);
15349 }
15350 
15351 /// CheckParmsForFunctionDef - Check that the parameters of the given
15352 /// function are appropriate for the definition of a function. This
15353 /// takes care of any checks that cannot be performed on the
15354 /// declaration itself, e.g., that the types of each of the function
15355 /// parameters are complete.
15356 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15357                                     bool CheckParameterNames) {
15358   bool HasInvalidParm = false;
15359   for (ParmVarDecl *Param : Parameters) {
15360     // C99 6.7.5.3p4: the parameters in a parameter type list in a
15361     // function declarator that is part of a function definition of
15362     // that function shall not have incomplete type.
15363     //
15364     // This is also C++ [dcl.fct]p6.
15365     if (!Param->isInvalidDecl() &&
15366         RequireCompleteType(Param->getLocation(), Param->getType(),
15367                             diag::err_typecheck_decl_incomplete_type)) {
15368       Param->setInvalidDecl();
15369       HasInvalidParm = true;
15370     }
15371 
15372     // C99 6.9.1p5: If the declarator includes a parameter type list, the
15373     // declaration of each parameter shall include an identifier.
15374     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15375         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15376       // Diagnose this as an extension in C17 and earlier.
15377       if (!getLangOpts().C2x)
15378         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15379     }
15380 
15381     // C99 6.7.5.3p12:
15382     //   If the function declarator is not part of a definition of that
15383     //   function, parameters may have incomplete type and may use the [*]
15384     //   notation in their sequences of declarator specifiers to specify
15385     //   variable length array types.
15386     QualType PType = Param->getOriginalType();
15387     // FIXME: This diagnostic should point the '[*]' if source-location
15388     // information is added for it.
15389     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15390 
15391     // If the parameter is a c++ class type and it has to be destructed in the
15392     // callee function, declare the destructor so that it can be called by the
15393     // callee function. Do not perform any direct access check on the dtor here.
15394     if (!Param->isInvalidDecl()) {
15395       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15396         if (!ClassDecl->isInvalidDecl() &&
15397             !ClassDecl->hasIrrelevantDestructor() &&
15398             !ClassDecl->isDependentContext() &&
15399             ClassDecl->isParamDestroyedInCallee()) {
15400           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15401           MarkFunctionReferenced(Param->getLocation(), Destructor);
15402           DiagnoseUseOfDecl(Destructor, Param->getLocation());
15403         }
15404       }
15405     }
15406 
15407     // Parameters with the pass_object_size attribute only need to be marked
15408     // constant at function definitions. Because we lack information about
15409     // whether we're on a declaration or definition when we're instantiating the
15410     // attribute, we need to check for constness here.
15411     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15412       if (!Param->getType().isConstQualified())
15413         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15414             << Attr->getSpelling() << 1;
15415 
15416     // Check for parameter names shadowing fields from the class.
15417     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15418       // The owning context for the parameter should be the function, but we
15419       // want to see if this function's declaration context is a record.
15420       DeclContext *DC = Param->getDeclContext();
15421       if (DC && DC->isFunctionOrMethod()) {
15422         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15423           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15424                                      RD, /*DeclIsField*/ false);
15425       }
15426     }
15427   }
15428 
15429   return HasInvalidParm;
15430 }
15431 
15432 Optional<std::pair<CharUnits, CharUnits>>
15433 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
15434 
15435 /// Compute the alignment and offset of the base class object given the
15436 /// derived-to-base cast expression and the alignment and offset of the derived
15437 /// class object.
15438 static std::pair<CharUnits, CharUnits>
15439 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15440                                    CharUnits BaseAlignment, CharUnits Offset,
15441                                    ASTContext &Ctx) {
15442   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15443        ++PathI) {
15444     const CXXBaseSpecifier *Base = *PathI;
15445     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15446     if (Base->isVirtual()) {
15447       // The complete object may have a lower alignment than the non-virtual
15448       // alignment of the base, in which case the base may be misaligned. Choose
15449       // the smaller of the non-virtual alignment and BaseAlignment, which is a
15450       // conservative lower bound of the complete object alignment.
15451       CharUnits NonVirtualAlignment =
15452           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
15453       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15454       Offset = CharUnits::Zero();
15455     } else {
15456       const ASTRecordLayout &RL =
15457           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15458       Offset += RL.getBaseClassOffset(BaseDecl);
15459     }
15460     DerivedType = Base->getType();
15461   }
15462 
15463   return std::make_pair(BaseAlignment, Offset);
15464 }
15465 
15466 /// Compute the alignment and offset of a binary additive operator.
15467 static Optional<std::pair<CharUnits, CharUnits>>
15468 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15469                                      bool IsSub, ASTContext &Ctx) {
15470   QualType PointeeType = PtrE->getType()->getPointeeType();
15471 
15472   if (!PointeeType->isConstantSizeType())
15473     return llvm::None;
15474 
15475   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15476 
15477   if (!P)
15478     return llvm::None;
15479 
15480   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15481   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15482     CharUnits Offset = EltSize * IdxRes->getExtValue();
15483     if (IsSub)
15484       Offset = -Offset;
15485     return std::make_pair(P->first, P->second + Offset);
15486   }
15487 
15488   // If the integer expression isn't a constant expression, compute the lower
15489   // bound of the alignment using the alignment and offset of the pointer
15490   // expression and the element size.
15491   return std::make_pair(
15492       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15493       CharUnits::Zero());
15494 }
15495 
15496 /// This helper function takes an lvalue expression and returns the alignment of
15497 /// a VarDecl and a constant offset from the VarDecl.
15498 Optional<std::pair<CharUnits, CharUnits>>
15499 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
15500   E = E->IgnoreParens();
15501   switch (E->getStmtClass()) {
15502   default:
15503     break;
15504   case Stmt::CStyleCastExprClass:
15505   case Stmt::CXXStaticCastExprClass:
15506   case Stmt::ImplicitCastExprClass: {
15507     auto *CE = cast<CastExpr>(E);
15508     const Expr *From = CE->getSubExpr();
15509     switch (CE->getCastKind()) {
15510     default:
15511       break;
15512     case CK_NoOp:
15513       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15514     case CK_UncheckedDerivedToBase:
15515     case CK_DerivedToBase: {
15516       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15517       if (!P)
15518         break;
15519       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15520                                                 P->second, Ctx);
15521     }
15522     }
15523     break;
15524   }
15525   case Stmt::ArraySubscriptExprClass: {
15526     auto *ASE = cast<ArraySubscriptExpr>(E);
15527     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
15528                                                 false, Ctx);
15529   }
15530   case Stmt::DeclRefExprClass: {
15531     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15532       // FIXME: If VD is captured by copy or is an escaping __block variable,
15533       // use the alignment of VD's type.
15534       if (!VD->getType()->isReferenceType())
15535         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15536       if (VD->hasInit())
15537         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15538     }
15539     break;
15540   }
15541   case Stmt::MemberExprClass: {
15542     auto *ME = cast<MemberExpr>(E);
15543     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15544     if (!FD || FD->getType()->isReferenceType() ||
15545         FD->getParent()->isInvalidDecl())
15546       break;
15547     Optional<std::pair<CharUnits, CharUnits>> P;
15548     if (ME->isArrow())
15549       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15550     else
15551       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15552     if (!P)
15553       break;
15554     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15555     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15556     return std::make_pair(P->first,
15557                           P->second + CharUnits::fromQuantity(Offset));
15558   }
15559   case Stmt::UnaryOperatorClass: {
15560     auto *UO = cast<UnaryOperator>(E);
15561     switch (UO->getOpcode()) {
15562     default:
15563       break;
15564     case UO_Deref:
15565       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
15566     }
15567     break;
15568   }
15569   case Stmt::BinaryOperatorClass: {
15570     auto *BO = cast<BinaryOperator>(E);
15571     auto Opcode = BO->getOpcode();
15572     switch (Opcode) {
15573     default:
15574       break;
15575     case BO_Comma:
15576       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
15577     }
15578     break;
15579   }
15580   }
15581   return llvm::None;
15582 }
15583 
15584 /// This helper function takes a pointer expression and returns the alignment of
15585 /// a VarDecl and a constant offset from the VarDecl.
15586 Optional<std::pair<CharUnits, CharUnits>>
15587 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
15588   E = E->IgnoreParens();
15589   switch (E->getStmtClass()) {
15590   default:
15591     break;
15592   case Stmt::CStyleCastExprClass:
15593   case Stmt::CXXStaticCastExprClass:
15594   case Stmt::ImplicitCastExprClass: {
15595     auto *CE = cast<CastExpr>(E);
15596     const Expr *From = CE->getSubExpr();
15597     switch (CE->getCastKind()) {
15598     default:
15599       break;
15600     case CK_NoOp:
15601       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15602     case CK_ArrayToPointerDecay:
15603       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15604     case CK_UncheckedDerivedToBase:
15605     case CK_DerivedToBase: {
15606       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15607       if (!P)
15608         break;
15609       return getDerivedToBaseAlignmentAndOffset(
15610           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15611     }
15612     }
15613     break;
15614   }
15615   case Stmt::CXXThisExprClass: {
15616     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15617     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
15618     return std::make_pair(Alignment, CharUnits::Zero());
15619   }
15620   case Stmt::UnaryOperatorClass: {
15621     auto *UO = cast<UnaryOperator>(E);
15622     if (UO->getOpcode() == UO_AddrOf)
15623       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
15624     break;
15625   }
15626   case Stmt::BinaryOperatorClass: {
15627     auto *BO = cast<BinaryOperator>(E);
15628     auto Opcode = BO->getOpcode();
15629     switch (Opcode) {
15630     default:
15631       break;
15632     case BO_Add:
15633     case BO_Sub: {
15634       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15635       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15636         std::swap(LHS, RHS);
15637       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15638                                                   Ctx);
15639     }
15640     case BO_Comma:
15641       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15642     }
15643     break;
15644   }
15645   }
15646   return llvm::None;
15647 }
15648 
15649 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15650   // See if we can compute the alignment of a VarDecl and an offset from it.
15651   Optional<std::pair<CharUnits, CharUnits>> P =
15652       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
15653 
15654   if (P)
15655     return P->first.alignmentAtOffset(P->second);
15656 
15657   // If that failed, return the type's alignment.
15658   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
15659 }
15660 
15661 /// CheckCastAlign - Implements -Wcast-align, which warns when a
15662 /// pointer cast increases the alignment requirements.
15663 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15664   // This is actually a lot of work to potentially be doing on every
15665   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15666   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15667     return;
15668 
15669   // Ignore dependent types.
15670   if (T->isDependentType() || Op->getType()->isDependentType())
15671     return;
15672 
15673   // Require that the destination be a pointer type.
15674   const PointerType *DestPtr = T->getAs<PointerType>();
15675   if (!DestPtr) return;
15676 
15677   // If the destination has alignment 1, we're done.
15678   QualType DestPointee = DestPtr->getPointeeType();
15679   if (DestPointee->isIncompleteType()) return;
15680   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15681   if (DestAlign.isOne()) return;
15682 
15683   // Require that the source be a pointer type.
15684   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15685   if (!SrcPtr) return;
15686   QualType SrcPointee = SrcPtr->getPointeeType();
15687 
15688   // Explicitly allow casts from cv void*.  We already implicitly
15689   // allowed casts to cv void*, since they have alignment 1.
15690   // Also allow casts involving incomplete types, which implicitly
15691   // includes 'void'.
15692   if (SrcPointee->isIncompleteType()) return;
15693 
15694   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15695 
15696   if (SrcAlign >= DestAlign) return;
15697 
15698   Diag(TRange.getBegin(), diag::warn_cast_align)
15699     << Op->getType() << T
15700     << static_cast<unsigned>(SrcAlign.getQuantity())
15701     << static_cast<unsigned>(DestAlign.getQuantity())
15702     << TRange << Op->getSourceRange();
15703 }
15704 
15705 /// Check whether this array fits the idiom of a size-one tail padded
15706 /// array member of a struct.
15707 ///
15708 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15709 /// commonly used to emulate flexible arrays in C89 code.
15710 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15711                                     const NamedDecl *ND) {
15712   if (Size != 1 || !ND) return false;
15713 
15714   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15715   if (!FD) return false;
15716 
15717   // Don't consider sizes resulting from macro expansions or template argument
15718   // substitution to form C89 tail-padded arrays.
15719 
15720   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15721   while (TInfo) {
15722     TypeLoc TL = TInfo->getTypeLoc();
15723     // Look through typedefs.
15724     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15725       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15726       TInfo = TDL->getTypeSourceInfo();
15727       continue;
15728     }
15729     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15730       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15731       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15732         return false;
15733     }
15734     break;
15735   }
15736 
15737   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15738   if (!RD) return false;
15739   if (RD->isUnion()) return false;
15740   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15741     if (!CRD->isStandardLayout()) return false;
15742   }
15743 
15744   // See if this is the last field decl in the record.
15745   const Decl *D = FD;
15746   while ((D = D->getNextDeclInContext()))
15747     if (isa<FieldDecl>(D))
15748       return false;
15749   return true;
15750 }
15751 
15752 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15753                             const ArraySubscriptExpr *ASE,
15754                             bool AllowOnePastEnd, bool IndexNegated) {
15755   // Already diagnosed by the constant evaluator.
15756   if (isConstantEvaluated())
15757     return;
15758 
15759   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15760   if (IndexExpr->isValueDependent())
15761     return;
15762 
15763   const Type *EffectiveType =
15764       BaseExpr->getType()->getPointeeOrArrayElementType();
15765   BaseExpr = BaseExpr->IgnoreParenCasts();
15766   const ConstantArrayType *ArrayTy =
15767       Context.getAsConstantArrayType(BaseExpr->getType());
15768 
15769   const Type *BaseType =
15770       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15771   bool IsUnboundedArray = (BaseType == nullptr);
15772   if (EffectiveType->isDependentType() ||
15773       (!IsUnboundedArray && BaseType->isDependentType()))
15774     return;
15775 
15776   Expr::EvalResult Result;
15777   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15778     return;
15779 
15780   llvm::APSInt index = Result.Val.getInt();
15781   if (IndexNegated) {
15782     index.setIsUnsigned(false);
15783     index = -index;
15784   }
15785 
15786   const NamedDecl *ND = nullptr;
15787   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15788     ND = DRE->getDecl();
15789   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15790     ND = ME->getMemberDecl();
15791 
15792   if (IsUnboundedArray) {
15793     if (EffectiveType->isFunctionType())
15794       return;
15795     if (index.isUnsigned() || !index.isNegative()) {
15796       const auto &ASTC = getASTContext();
15797       unsigned AddrBits =
15798           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15799               EffectiveType->getCanonicalTypeInternal()));
15800       if (index.getBitWidth() < AddrBits)
15801         index = index.zext(AddrBits);
15802       Optional<CharUnits> ElemCharUnits =
15803           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15804       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15805       // pointer) bounds-checking isn't meaningful.
15806       if (!ElemCharUnits)
15807         return;
15808       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15809       // If index has more active bits than address space, we already know
15810       // we have a bounds violation to warn about.  Otherwise, compute
15811       // address of (index + 1)th element, and warn about bounds violation
15812       // only if that address exceeds address space.
15813       if (index.getActiveBits() <= AddrBits) {
15814         bool Overflow;
15815         llvm::APInt Product(index);
15816         Product += 1;
15817         Product = Product.umul_ov(ElemBytes, Overflow);
15818         if (!Overflow && Product.getActiveBits() <= AddrBits)
15819           return;
15820       }
15821 
15822       // Need to compute max possible elements in address space, since that
15823       // is included in diag message.
15824       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15825       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15826       MaxElems += 1;
15827       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15828       MaxElems = MaxElems.udiv(ElemBytes);
15829 
15830       unsigned DiagID =
15831           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15832               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15833 
15834       // Diag message shows element size in bits and in "bytes" (platform-
15835       // dependent CharUnits)
15836       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15837                           PDiag(DiagID)
15838                               << toString(index, 10, true) << AddrBits
15839                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15840                               << toString(ElemBytes, 10, false)
15841                               << toString(MaxElems, 10, false)
15842                               << (unsigned)MaxElems.getLimitedValue(~0U)
15843                               << IndexExpr->getSourceRange());
15844 
15845       if (!ND) {
15846         // Try harder to find a NamedDecl to point at in the note.
15847         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15848           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15849         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15850           ND = DRE->getDecl();
15851         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15852           ND = ME->getMemberDecl();
15853       }
15854 
15855       if (ND)
15856         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15857                             PDiag(diag::note_array_declared_here) << ND);
15858     }
15859     return;
15860   }
15861 
15862   if (index.isUnsigned() || !index.isNegative()) {
15863     // It is possible that the type of the base expression after
15864     // IgnoreParenCasts is incomplete, even though the type of the base
15865     // expression before IgnoreParenCasts is complete (see PR39746 for an
15866     // example). In this case we have no information about whether the array
15867     // access exceeds the array bounds. However we can still diagnose an array
15868     // access which precedes the array bounds.
15869     if (BaseType->isIncompleteType())
15870       return;
15871 
15872     llvm::APInt size = ArrayTy->getSize();
15873     if (!size.isStrictlyPositive())
15874       return;
15875 
15876     if (BaseType != EffectiveType) {
15877       // Make sure we're comparing apples to apples when comparing index to size
15878       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15879       uint64_t array_typesize = Context.getTypeSize(BaseType);
15880       // Handle ptrarith_typesize being zero, such as when casting to void*
15881       if (!ptrarith_typesize) ptrarith_typesize = 1;
15882       if (ptrarith_typesize != array_typesize) {
15883         // There's a cast to a different size type involved
15884         uint64_t ratio = array_typesize / ptrarith_typesize;
15885         // TODO: Be smarter about handling cases where array_typesize is not a
15886         // multiple of ptrarith_typesize
15887         if (ptrarith_typesize * ratio == array_typesize)
15888           size *= llvm::APInt(size.getBitWidth(), ratio);
15889       }
15890     }
15891 
15892     if (size.getBitWidth() > index.getBitWidth())
15893       index = index.zext(size.getBitWidth());
15894     else if (size.getBitWidth() < index.getBitWidth())
15895       size = size.zext(index.getBitWidth());
15896 
15897     // For array subscripting the index must be less than size, but for pointer
15898     // arithmetic also allow the index (offset) to be equal to size since
15899     // computing the next address after the end of the array is legal and
15900     // commonly done e.g. in C++ iterators and range-based for loops.
15901     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15902       return;
15903 
15904     // Also don't warn for arrays of size 1 which are members of some
15905     // structure. These are often used to approximate flexible arrays in C89
15906     // code.
15907     if (IsTailPaddedMemberArray(*this, size, ND))
15908       return;
15909 
15910     // Suppress the warning if the subscript expression (as identified by the
15911     // ']' location) and the index expression are both from macro expansions
15912     // within a system header.
15913     if (ASE) {
15914       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15915           ASE->getRBracketLoc());
15916       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15917         SourceLocation IndexLoc =
15918             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15919         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15920           return;
15921       }
15922     }
15923 
15924     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15925                           : diag::warn_ptr_arith_exceeds_bounds;
15926 
15927     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15928                         PDiag(DiagID) << toString(index, 10, true)
15929                                       << toString(size, 10, true)
15930                                       << (unsigned)size.getLimitedValue(~0U)
15931                                       << IndexExpr->getSourceRange());
15932   } else {
15933     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15934     if (!ASE) {
15935       DiagID = diag::warn_ptr_arith_precedes_bounds;
15936       if (index.isNegative()) index = -index;
15937     }
15938 
15939     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15940                         PDiag(DiagID) << toString(index, 10, true)
15941                                       << IndexExpr->getSourceRange());
15942   }
15943 
15944   if (!ND) {
15945     // Try harder to find a NamedDecl to point at in the note.
15946     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15947       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15948     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15949       ND = DRE->getDecl();
15950     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15951       ND = ME->getMemberDecl();
15952   }
15953 
15954   if (ND)
15955     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15956                         PDiag(diag::note_array_declared_here) << ND);
15957 }
15958 
15959 void Sema::CheckArrayAccess(const Expr *expr) {
15960   int AllowOnePastEnd = 0;
15961   while (expr) {
15962     expr = expr->IgnoreParenImpCasts();
15963     switch (expr->getStmtClass()) {
15964       case Stmt::ArraySubscriptExprClass: {
15965         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15966         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15967                          AllowOnePastEnd > 0);
15968         expr = ASE->getBase();
15969         break;
15970       }
15971       case Stmt::MemberExprClass: {
15972         expr = cast<MemberExpr>(expr)->getBase();
15973         break;
15974       }
15975       case Stmt::OMPArraySectionExprClass: {
15976         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15977         if (ASE->getLowerBound())
15978           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15979                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15980         return;
15981       }
15982       case Stmt::UnaryOperatorClass: {
15983         // Only unwrap the * and & unary operators
15984         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15985         expr = UO->getSubExpr();
15986         switch (UO->getOpcode()) {
15987           case UO_AddrOf:
15988             AllowOnePastEnd++;
15989             break;
15990           case UO_Deref:
15991             AllowOnePastEnd--;
15992             break;
15993           default:
15994             return;
15995         }
15996         break;
15997       }
15998       case Stmt::ConditionalOperatorClass: {
15999         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
16000         if (const Expr *lhs = cond->getLHS())
16001           CheckArrayAccess(lhs);
16002         if (const Expr *rhs = cond->getRHS())
16003           CheckArrayAccess(rhs);
16004         return;
16005       }
16006       case Stmt::CXXOperatorCallExprClass: {
16007         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
16008         for (const auto *Arg : OCE->arguments())
16009           CheckArrayAccess(Arg);
16010         return;
16011       }
16012       default:
16013         return;
16014     }
16015   }
16016 }
16017 
16018 //===--- CHECK: Objective-C retain cycles ----------------------------------//
16019 
16020 namespace {
16021 
16022 struct RetainCycleOwner {
16023   VarDecl *Variable = nullptr;
16024   SourceRange Range;
16025   SourceLocation Loc;
16026   bool Indirect = false;
16027 
16028   RetainCycleOwner() = default;
16029 
16030   void setLocsFrom(Expr *e) {
16031     Loc = e->getExprLoc();
16032     Range = e->getSourceRange();
16033   }
16034 };
16035 
16036 } // namespace
16037 
16038 /// Consider whether capturing the given variable can possibly lead to
16039 /// a retain cycle.
16040 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
16041   // In ARC, it's captured strongly iff the variable has __strong
16042   // lifetime.  In MRR, it's captured strongly if the variable is
16043   // __block and has an appropriate type.
16044   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
16045     return false;
16046 
16047   owner.Variable = var;
16048   if (ref)
16049     owner.setLocsFrom(ref);
16050   return true;
16051 }
16052 
16053 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
16054   while (true) {
16055     e = e->IgnoreParens();
16056     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
16057       switch (cast->getCastKind()) {
16058       case CK_BitCast:
16059       case CK_LValueBitCast:
16060       case CK_LValueToRValue:
16061       case CK_ARCReclaimReturnedObject:
16062         e = cast->getSubExpr();
16063         continue;
16064 
16065       default:
16066         return false;
16067       }
16068     }
16069 
16070     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
16071       ObjCIvarDecl *ivar = ref->getDecl();
16072       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
16073         return false;
16074 
16075       // Try to find a retain cycle in the base.
16076       if (!findRetainCycleOwner(S, ref->getBase(), owner))
16077         return false;
16078 
16079       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
16080       owner.Indirect = true;
16081       return true;
16082     }
16083 
16084     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
16085       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
16086       if (!var) return false;
16087       return considerVariable(var, ref, owner);
16088     }
16089 
16090     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
16091       if (member->isArrow()) return false;
16092 
16093       // Don't count this as an indirect ownership.
16094       e = member->getBase();
16095       continue;
16096     }
16097 
16098     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
16099       // Only pay attention to pseudo-objects on property references.
16100       ObjCPropertyRefExpr *pre
16101         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
16102                                               ->IgnoreParens());
16103       if (!pre) return false;
16104       if (pre->isImplicitProperty()) return false;
16105       ObjCPropertyDecl *property = pre->getExplicitProperty();
16106       if (!property->isRetaining() &&
16107           !(property->getPropertyIvarDecl() &&
16108             property->getPropertyIvarDecl()->getType()
16109               .getObjCLifetime() == Qualifiers::OCL_Strong))
16110           return false;
16111 
16112       owner.Indirect = true;
16113       if (pre->isSuperReceiver()) {
16114         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
16115         if (!owner.Variable)
16116           return false;
16117         owner.Loc = pre->getLocation();
16118         owner.Range = pre->getSourceRange();
16119         return true;
16120       }
16121       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
16122                               ->getSourceExpr());
16123       continue;
16124     }
16125 
16126     // Array ivars?
16127 
16128     return false;
16129   }
16130 }
16131 
16132 namespace {
16133 
16134   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
16135     ASTContext &Context;
16136     VarDecl *Variable;
16137     Expr *Capturer = nullptr;
16138     bool VarWillBeReased = false;
16139 
16140     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
16141         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
16142           Context(Context), Variable(variable) {}
16143 
16144     void VisitDeclRefExpr(DeclRefExpr *ref) {
16145       if (ref->getDecl() == Variable && !Capturer)
16146         Capturer = ref;
16147     }
16148 
16149     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
16150       if (Capturer) return;
16151       Visit(ref->getBase());
16152       if (Capturer && ref->isFreeIvar())
16153         Capturer = ref;
16154     }
16155 
16156     void VisitBlockExpr(BlockExpr *block) {
16157       // Look inside nested blocks
16158       if (block->getBlockDecl()->capturesVariable(Variable))
16159         Visit(block->getBlockDecl()->getBody());
16160     }
16161 
16162     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
16163       if (Capturer) return;
16164       if (OVE->getSourceExpr())
16165         Visit(OVE->getSourceExpr());
16166     }
16167 
16168     void VisitBinaryOperator(BinaryOperator *BinOp) {
16169       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
16170         return;
16171       Expr *LHS = BinOp->getLHS();
16172       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
16173         if (DRE->getDecl() != Variable)
16174           return;
16175         if (Expr *RHS = BinOp->getRHS()) {
16176           RHS = RHS->IgnoreParenCasts();
16177           Optional<llvm::APSInt> Value;
16178           VarWillBeReased =
16179               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
16180                *Value == 0);
16181         }
16182       }
16183     }
16184   };
16185 
16186 } // namespace
16187 
16188 /// Check whether the given argument is a block which captures a
16189 /// variable.
16190 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
16191   assert(owner.Variable && owner.Loc.isValid());
16192 
16193   e = e->IgnoreParenCasts();
16194 
16195   // Look through [^{...} copy] and Block_copy(^{...}).
16196   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
16197     Selector Cmd = ME->getSelector();
16198     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
16199       e = ME->getInstanceReceiver();
16200       if (!e)
16201         return nullptr;
16202       e = e->IgnoreParenCasts();
16203     }
16204   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
16205     if (CE->getNumArgs() == 1) {
16206       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
16207       if (Fn) {
16208         const IdentifierInfo *FnI = Fn->getIdentifier();
16209         if (FnI && FnI->isStr("_Block_copy")) {
16210           e = CE->getArg(0)->IgnoreParenCasts();
16211         }
16212       }
16213     }
16214   }
16215 
16216   BlockExpr *block = dyn_cast<BlockExpr>(e);
16217   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
16218     return nullptr;
16219 
16220   FindCaptureVisitor visitor(S.Context, owner.Variable);
16221   visitor.Visit(block->getBlockDecl()->getBody());
16222   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
16223 }
16224 
16225 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
16226                                 RetainCycleOwner &owner) {
16227   assert(capturer);
16228   assert(owner.Variable && owner.Loc.isValid());
16229 
16230   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
16231     << owner.Variable << capturer->getSourceRange();
16232   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
16233     << owner.Indirect << owner.Range;
16234 }
16235 
16236 /// Check for a keyword selector that starts with the word 'add' or
16237 /// 'set'.
16238 static bool isSetterLikeSelector(Selector sel) {
16239   if (sel.isUnarySelector()) return false;
16240 
16241   StringRef str = sel.getNameForSlot(0);
16242   while (!str.empty() && str.front() == '_') str = str.substr(1);
16243   if (str.startswith("set"))
16244     str = str.substr(3);
16245   else if (str.startswith("add")) {
16246     // Specially allow 'addOperationWithBlock:'.
16247     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
16248       return false;
16249     str = str.substr(3);
16250   }
16251   else
16252     return false;
16253 
16254   if (str.empty()) return true;
16255   return !isLowercase(str.front());
16256 }
16257 
16258 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
16259                                                     ObjCMessageExpr *Message) {
16260   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
16261                                                 Message->getReceiverInterface(),
16262                                                 NSAPI::ClassId_NSMutableArray);
16263   if (!IsMutableArray) {
16264     return None;
16265   }
16266 
16267   Selector Sel = Message->getSelector();
16268 
16269   Optional<NSAPI::NSArrayMethodKind> MKOpt =
16270     S.NSAPIObj->getNSArrayMethodKind(Sel);
16271   if (!MKOpt) {
16272     return None;
16273   }
16274 
16275   NSAPI::NSArrayMethodKind MK = *MKOpt;
16276 
16277   switch (MK) {
16278     case NSAPI::NSMutableArr_addObject:
16279     case NSAPI::NSMutableArr_insertObjectAtIndex:
16280     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
16281       return 0;
16282     case NSAPI::NSMutableArr_replaceObjectAtIndex:
16283       return 1;
16284 
16285     default:
16286       return None;
16287   }
16288 
16289   return None;
16290 }
16291 
16292 static
16293 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
16294                                                   ObjCMessageExpr *Message) {
16295   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
16296                                             Message->getReceiverInterface(),
16297                                             NSAPI::ClassId_NSMutableDictionary);
16298   if (!IsMutableDictionary) {
16299     return None;
16300   }
16301 
16302   Selector Sel = Message->getSelector();
16303 
16304   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
16305     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
16306   if (!MKOpt) {
16307     return None;
16308   }
16309 
16310   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
16311 
16312   switch (MK) {
16313     case NSAPI::NSMutableDict_setObjectForKey:
16314     case NSAPI::NSMutableDict_setValueForKey:
16315     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
16316       return 0;
16317 
16318     default:
16319       return None;
16320   }
16321 
16322   return None;
16323 }
16324 
16325 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
16326   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
16327                                                 Message->getReceiverInterface(),
16328                                                 NSAPI::ClassId_NSMutableSet);
16329 
16330   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
16331                                             Message->getReceiverInterface(),
16332                                             NSAPI::ClassId_NSMutableOrderedSet);
16333   if (!IsMutableSet && !IsMutableOrderedSet) {
16334     return None;
16335   }
16336 
16337   Selector Sel = Message->getSelector();
16338 
16339   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
16340   if (!MKOpt) {
16341     return None;
16342   }
16343 
16344   NSAPI::NSSetMethodKind MK = *MKOpt;
16345 
16346   switch (MK) {
16347     case NSAPI::NSMutableSet_addObject:
16348     case NSAPI::NSOrderedSet_setObjectAtIndex:
16349     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
16350     case NSAPI::NSOrderedSet_insertObjectAtIndex:
16351       return 0;
16352     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
16353       return 1;
16354   }
16355 
16356   return None;
16357 }
16358 
16359 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
16360   if (!Message->isInstanceMessage()) {
16361     return;
16362   }
16363 
16364   Optional<int> ArgOpt;
16365 
16366   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
16367       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
16368       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
16369     return;
16370   }
16371 
16372   int ArgIndex = *ArgOpt;
16373 
16374   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
16375   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
16376     Arg = OE->getSourceExpr()->IgnoreImpCasts();
16377   }
16378 
16379   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
16380     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16381       if (ArgRE->isObjCSelfExpr()) {
16382         Diag(Message->getSourceRange().getBegin(),
16383              diag::warn_objc_circular_container)
16384           << ArgRE->getDecl() << StringRef("'super'");
16385       }
16386     }
16387   } else {
16388     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
16389 
16390     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
16391       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
16392     }
16393 
16394     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
16395       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
16396         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
16397           ValueDecl *Decl = ReceiverRE->getDecl();
16398           Diag(Message->getSourceRange().getBegin(),
16399                diag::warn_objc_circular_container)
16400             << Decl << Decl;
16401           if (!ArgRE->isObjCSelfExpr()) {
16402             Diag(Decl->getLocation(),
16403                  diag::note_objc_circular_container_declared_here)
16404               << Decl;
16405           }
16406         }
16407       }
16408     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
16409       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
16410         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
16411           ObjCIvarDecl *Decl = IvarRE->getDecl();
16412           Diag(Message->getSourceRange().getBegin(),
16413                diag::warn_objc_circular_container)
16414             << Decl << Decl;
16415           Diag(Decl->getLocation(),
16416                diag::note_objc_circular_container_declared_here)
16417             << Decl;
16418         }
16419       }
16420     }
16421   }
16422 }
16423 
16424 /// Check a message send to see if it's likely to cause a retain cycle.
16425 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
16426   // Only check instance methods whose selector looks like a setter.
16427   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
16428     return;
16429 
16430   // Try to find a variable that the receiver is strongly owned by.
16431   RetainCycleOwner owner;
16432   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
16433     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
16434       return;
16435   } else {
16436     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
16437     owner.Variable = getCurMethodDecl()->getSelfDecl();
16438     owner.Loc = msg->getSuperLoc();
16439     owner.Range = msg->getSuperLoc();
16440   }
16441 
16442   // Check whether the receiver is captured by any of the arguments.
16443   const ObjCMethodDecl *MD = msg->getMethodDecl();
16444   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
16445     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
16446       // noescape blocks should not be retained by the method.
16447       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
16448         continue;
16449       return diagnoseRetainCycle(*this, capturer, owner);
16450     }
16451   }
16452 }
16453 
16454 /// Check a property assign to see if it's likely to cause a retain cycle.
16455 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
16456   RetainCycleOwner owner;
16457   if (!findRetainCycleOwner(*this, receiver, owner))
16458     return;
16459 
16460   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
16461     diagnoseRetainCycle(*this, capturer, owner);
16462 }
16463 
16464 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
16465   RetainCycleOwner Owner;
16466   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
16467     return;
16468 
16469   // Because we don't have an expression for the variable, we have to set the
16470   // location explicitly here.
16471   Owner.Loc = Var->getLocation();
16472   Owner.Range = Var->getSourceRange();
16473 
16474   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
16475     diagnoseRetainCycle(*this, Capturer, Owner);
16476 }
16477 
16478 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16479                                      Expr *RHS, bool isProperty) {
16480   // Check if RHS is an Objective-C object literal, which also can get
16481   // immediately zapped in a weak reference.  Note that we explicitly
16482   // allow ObjCStringLiterals, since those are designed to never really die.
16483   RHS = RHS->IgnoreParenImpCasts();
16484 
16485   // This enum needs to match with the 'select' in
16486   // warn_objc_arc_literal_assign (off-by-1).
16487   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
16488   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
16489     return false;
16490 
16491   S.Diag(Loc, diag::warn_arc_literal_assign)
16492     << (unsigned) Kind
16493     << (isProperty ? 0 : 1)
16494     << RHS->getSourceRange();
16495 
16496   return true;
16497 }
16498 
16499 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16500                                     Qualifiers::ObjCLifetime LT,
16501                                     Expr *RHS, bool isProperty) {
16502   // Strip off any implicit cast added to get to the one ARC-specific.
16503   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16504     if (cast->getCastKind() == CK_ARCConsumeObject) {
16505       S.Diag(Loc, diag::warn_arc_retained_assign)
16506         << (LT == Qualifiers::OCL_ExplicitNone)
16507         << (isProperty ? 0 : 1)
16508         << RHS->getSourceRange();
16509       return true;
16510     }
16511     RHS = cast->getSubExpr();
16512   }
16513 
16514   if (LT == Qualifiers::OCL_Weak &&
16515       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16516     return true;
16517 
16518   return false;
16519 }
16520 
16521 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16522                               QualType LHS, Expr *RHS) {
16523   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16524 
16525   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16526     return false;
16527 
16528   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16529     return true;
16530 
16531   return false;
16532 }
16533 
16534 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16535                               Expr *LHS, Expr *RHS) {
16536   QualType LHSType;
16537   // PropertyRef on LHS type need be directly obtained from
16538   // its declaration as it has a PseudoType.
16539   ObjCPropertyRefExpr *PRE
16540     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16541   if (PRE && !PRE->isImplicitProperty()) {
16542     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16543     if (PD)
16544       LHSType = PD->getType();
16545   }
16546 
16547   if (LHSType.isNull())
16548     LHSType = LHS->getType();
16549 
16550   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16551 
16552   if (LT == Qualifiers::OCL_Weak) {
16553     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16554       getCurFunction()->markSafeWeakUse(LHS);
16555   }
16556 
16557   if (checkUnsafeAssigns(Loc, LHSType, RHS))
16558     return;
16559 
16560   // FIXME. Check for other life times.
16561   if (LT != Qualifiers::OCL_None)
16562     return;
16563 
16564   if (PRE) {
16565     if (PRE->isImplicitProperty())
16566       return;
16567     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16568     if (!PD)
16569       return;
16570 
16571     unsigned Attributes = PD->getPropertyAttributes();
16572     if (Attributes & ObjCPropertyAttribute::kind_assign) {
16573       // when 'assign' attribute was not explicitly specified
16574       // by user, ignore it and rely on property type itself
16575       // for lifetime info.
16576       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16577       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16578           LHSType->isObjCRetainableType())
16579         return;
16580 
16581       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16582         if (cast->getCastKind() == CK_ARCConsumeObject) {
16583           Diag(Loc, diag::warn_arc_retained_property_assign)
16584           << RHS->getSourceRange();
16585           return;
16586         }
16587         RHS = cast->getSubExpr();
16588       }
16589     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16590       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16591         return;
16592     }
16593   }
16594 }
16595 
16596 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16597 
16598 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16599                                         SourceLocation StmtLoc,
16600                                         const NullStmt *Body) {
16601   // Do not warn if the body is a macro that expands to nothing, e.g:
16602   //
16603   // #define CALL(x)
16604   // if (condition)
16605   //   CALL(0);
16606   if (Body->hasLeadingEmptyMacro())
16607     return false;
16608 
16609   // Get line numbers of statement and body.
16610   bool StmtLineInvalid;
16611   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16612                                                       &StmtLineInvalid);
16613   if (StmtLineInvalid)
16614     return false;
16615 
16616   bool BodyLineInvalid;
16617   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16618                                                       &BodyLineInvalid);
16619   if (BodyLineInvalid)
16620     return false;
16621 
16622   // Warn if null statement and body are on the same line.
16623   if (StmtLine != BodyLine)
16624     return false;
16625 
16626   return true;
16627 }
16628 
16629 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16630                                  const Stmt *Body,
16631                                  unsigned DiagID) {
16632   // Since this is a syntactic check, don't emit diagnostic for template
16633   // instantiations, this just adds noise.
16634   if (CurrentInstantiationScope)
16635     return;
16636 
16637   // The body should be a null statement.
16638   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16639   if (!NBody)
16640     return;
16641 
16642   // Do the usual checks.
16643   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16644     return;
16645 
16646   Diag(NBody->getSemiLoc(), DiagID);
16647   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16648 }
16649 
16650 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16651                                  const Stmt *PossibleBody) {
16652   assert(!CurrentInstantiationScope); // Ensured by caller
16653 
16654   SourceLocation StmtLoc;
16655   const Stmt *Body;
16656   unsigned DiagID;
16657   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16658     StmtLoc = FS->getRParenLoc();
16659     Body = FS->getBody();
16660     DiagID = diag::warn_empty_for_body;
16661   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16662     StmtLoc = WS->getCond()->getSourceRange().getEnd();
16663     Body = WS->getBody();
16664     DiagID = diag::warn_empty_while_body;
16665   } else
16666     return; // Neither `for' nor `while'.
16667 
16668   // The body should be a null statement.
16669   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16670   if (!NBody)
16671     return;
16672 
16673   // Skip expensive checks if diagnostic is disabled.
16674   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16675     return;
16676 
16677   // Do the usual checks.
16678   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16679     return;
16680 
16681   // `for(...);' and `while(...);' are popular idioms, so in order to keep
16682   // noise level low, emit diagnostics only if for/while is followed by a
16683   // CompoundStmt, e.g.:
16684   //    for (int i = 0; i < n; i++);
16685   //    {
16686   //      a(i);
16687   //    }
16688   // or if for/while is followed by a statement with more indentation
16689   // than for/while itself:
16690   //    for (int i = 0; i < n; i++);
16691   //      a(i);
16692   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16693   if (!ProbableTypo) {
16694     bool BodyColInvalid;
16695     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16696         PossibleBody->getBeginLoc(), &BodyColInvalid);
16697     if (BodyColInvalid)
16698       return;
16699 
16700     bool StmtColInvalid;
16701     unsigned StmtCol =
16702         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16703     if (StmtColInvalid)
16704       return;
16705 
16706     if (BodyCol > StmtCol)
16707       ProbableTypo = true;
16708   }
16709 
16710   if (ProbableTypo) {
16711     Diag(NBody->getSemiLoc(), DiagID);
16712     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16713   }
16714 }
16715 
16716 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16717 
16718 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16719 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16720                              SourceLocation OpLoc) {
16721   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16722     return;
16723 
16724   if (inTemplateInstantiation())
16725     return;
16726 
16727   // Strip parens and casts away.
16728   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16729   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16730 
16731   // Check for a call expression
16732   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16733   if (!CE || CE->getNumArgs() != 1)
16734     return;
16735 
16736   // Check for a call to std::move
16737   if (!CE->isCallToStdMove())
16738     return;
16739 
16740   // Get argument from std::move
16741   RHSExpr = CE->getArg(0);
16742 
16743   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16744   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16745 
16746   // Two DeclRefExpr's, check that the decls are the same.
16747   if (LHSDeclRef && RHSDeclRef) {
16748     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16749       return;
16750     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16751         RHSDeclRef->getDecl()->getCanonicalDecl())
16752       return;
16753 
16754     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16755                                         << LHSExpr->getSourceRange()
16756                                         << RHSExpr->getSourceRange();
16757     return;
16758   }
16759 
16760   // Member variables require a different approach to check for self moves.
16761   // MemberExpr's are the same if every nested MemberExpr refers to the same
16762   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16763   // the base Expr's are CXXThisExpr's.
16764   const Expr *LHSBase = LHSExpr;
16765   const Expr *RHSBase = RHSExpr;
16766   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16767   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16768   if (!LHSME || !RHSME)
16769     return;
16770 
16771   while (LHSME && RHSME) {
16772     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16773         RHSME->getMemberDecl()->getCanonicalDecl())
16774       return;
16775 
16776     LHSBase = LHSME->getBase();
16777     RHSBase = RHSME->getBase();
16778     LHSME = dyn_cast<MemberExpr>(LHSBase);
16779     RHSME = dyn_cast<MemberExpr>(RHSBase);
16780   }
16781 
16782   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16783   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16784   if (LHSDeclRef && RHSDeclRef) {
16785     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16786       return;
16787     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16788         RHSDeclRef->getDecl()->getCanonicalDecl())
16789       return;
16790 
16791     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16792                                         << LHSExpr->getSourceRange()
16793                                         << RHSExpr->getSourceRange();
16794     return;
16795   }
16796 
16797   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16798     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16799                                         << LHSExpr->getSourceRange()
16800                                         << RHSExpr->getSourceRange();
16801 }
16802 
16803 //===--- Layout compatibility ----------------------------------------------//
16804 
16805 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16806 
16807 /// Check if two enumeration types are layout-compatible.
16808 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16809   // C++11 [dcl.enum] p8:
16810   // Two enumeration types are layout-compatible if they have the same
16811   // underlying type.
16812   return ED1->isComplete() && ED2->isComplete() &&
16813          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16814 }
16815 
16816 /// Check if two fields are layout-compatible.
16817 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16818                                FieldDecl *Field2) {
16819   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16820     return false;
16821 
16822   if (Field1->isBitField() != Field2->isBitField())
16823     return false;
16824 
16825   if (Field1->isBitField()) {
16826     // Make sure that the bit-fields are the same length.
16827     unsigned Bits1 = Field1->getBitWidthValue(C);
16828     unsigned Bits2 = Field2->getBitWidthValue(C);
16829 
16830     if (Bits1 != Bits2)
16831       return false;
16832   }
16833 
16834   return true;
16835 }
16836 
16837 /// Check if two standard-layout structs are layout-compatible.
16838 /// (C++11 [class.mem] p17)
16839 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16840                                      RecordDecl *RD2) {
16841   // If both records are C++ classes, check that base classes match.
16842   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16843     // If one of records is a CXXRecordDecl we are in C++ mode,
16844     // thus the other one is a CXXRecordDecl, too.
16845     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16846     // Check number of base classes.
16847     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16848       return false;
16849 
16850     // Check the base classes.
16851     for (CXXRecordDecl::base_class_const_iterator
16852                Base1 = D1CXX->bases_begin(),
16853            BaseEnd1 = D1CXX->bases_end(),
16854               Base2 = D2CXX->bases_begin();
16855          Base1 != BaseEnd1;
16856          ++Base1, ++Base2) {
16857       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16858         return false;
16859     }
16860   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16861     // If only RD2 is a C++ class, it should have zero base classes.
16862     if (D2CXX->getNumBases() > 0)
16863       return false;
16864   }
16865 
16866   // Check the fields.
16867   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16868                              Field2End = RD2->field_end(),
16869                              Field1 = RD1->field_begin(),
16870                              Field1End = RD1->field_end();
16871   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16872     if (!isLayoutCompatible(C, *Field1, *Field2))
16873       return false;
16874   }
16875   if (Field1 != Field1End || Field2 != Field2End)
16876     return false;
16877 
16878   return true;
16879 }
16880 
16881 /// Check if two standard-layout unions are layout-compatible.
16882 /// (C++11 [class.mem] p18)
16883 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16884                                     RecordDecl *RD2) {
16885   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16886   for (auto *Field2 : RD2->fields())
16887     UnmatchedFields.insert(Field2);
16888 
16889   for (auto *Field1 : RD1->fields()) {
16890     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16891         I = UnmatchedFields.begin(),
16892         E = UnmatchedFields.end();
16893 
16894     for ( ; I != E; ++I) {
16895       if (isLayoutCompatible(C, Field1, *I)) {
16896         bool Result = UnmatchedFields.erase(*I);
16897         (void) Result;
16898         assert(Result);
16899         break;
16900       }
16901     }
16902     if (I == E)
16903       return false;
16904   }
16905 
16906   return UnmatchedFields.empty();
16907 }
16908 
16909 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16910                                RecordDecl *RD2) {
16911   if (RD1->isUnion() != RD2->isUnion())
16912     return false;
16913 
16914   if (RD1->isUnion())
16915     return isLayoutCompatibleUnion(C, RD1, RD2);
16916   else
16917     return isLayoutCompatibleStruct(C, RD1, RD2);
16918 }
16919 
16920 /// Check if two types are layout-compatible in C++11 sense.
16921 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16922   if (T1.isNull() || T2.isNull())
16923     return false;
16924 
16925   // C++11 [basic.types] p11:
16926   // If two types T1 and T2 are the same type, then T1 and T2 are
16927   // layout-compatible types.
16928   if (C.hasSameType(T1, T2))
16929     return true;
16930 
16931   T1 = T1.getCanonicalType().getUnqualifiedType();
16932   T2 = T2.getCanonicalType().getUnqualifiedType();
16933 
16934   const Type::TypeClass TC1 = T1->getTypeClass();
16935   const Type::TypeClass TC2 = T2->getTypeClass();
16936 
16937   if (TC1 != TC2)
16938     return false;
16939 
16940   if (TC1 == Type::Enum) {
16941     return isLayoutCompatible(C,
16942                               cast<EnumType>(T1)->getDecl(),
16943                               cast<EnumType>(T2)->getDecl());
16944   } else if (TC1 == Type::Record) {
16945     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16946       return false;
16947 
16948     return isLayoutCompatible(C,
16949                               cast<RecordType>(T1)->getDecl(),
16950                               cast<RecordType>(T2)->getDecl());
16951   }
16952 
16953   return false;
16954 }
16955 
16956 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16957 
16958 /// Given a type tag expression find the type tag itself.
16959 ///
16960 /// \param TypeExpr Type tag expression, as it appears in user's code.
16961 ///
16962 /// \param VD Declaration of an identifier that appears in a type tag.
16963 ///
16964 /// \param MagicValue Type tag magic value.
16965 ///
16966 /// \param isConstantEvaluated whether the evalaution should be performed in
16967 
16968 /// constant context.
16969 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16970                             const ValueDecl **VD, uint64_t *MagicValue,
16971                             bool isConstantEvaluated) {
16972   while(true) {
16973     if (!TypeExpr)
16974       return false;
16975 
16976     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16977 
16978     switch (TypeExpr->getStmtClass()) {
16979     case Stmt::UnaryOperatorClass: {
16980       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16981       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16982         TypeExpr = UO->getSubExpr();
16983         continue;
16984       }
16985       return false;
16986     }
16987 
16988     case Stmt::DeclRefExprClass: {
16989       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16990       *VD = DRE->getDecl();
16991       return true;
16992     }
16993 
16994     case Stmt::IntegerLiteralClass: {
16995       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16996       llvm::APInt MagicValueAPInt = IL->getValue();
16997       if (MagicValueAPInt.getActiveBits() <= 64) {
16998         *MagicValue = MagicValueAPInt.getZExtValue();
16999         return true;
17000       } else
17001         return false;
17002     }
17003 
17004     case Stmt::BinaryConditionalOperatorClass:
17005     case Stmt::ConditionalOperatorClass: {
17006       const AbstractConditionalOperator *ACO =
17007           cast<AbstractConditionalOperator>(TypeExpr);
17008       bool Result;
17009       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
17010                                                      isConstantEvaluated)) {
17011         if (Result)
17012           TypeExpr = ACO->getTrueExpr();
17013         else
17014           TypeExpr = ACO->getFalseExpr();
17015         continue;
17016       }
17017       return false;
17018     }
17019 
17020     case Stmt::BinaryOperatorClass: {
17021       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
17022       if (BO->getOpcode() == BO_Comma) {
17023         TypeExpr = BO->getRHS();
17024         continue;
17025       }
17026       return false;
17027     }
17028 
17029     default:
17030       return false;
17031     }
17032   }
17033 }
17034 
17035 /// Retrieve the C type corresponding to type tag TypeExpr.
17036 ///
17037 /// \param TypeExpr Expression that specifies a type tag.
17038 ///
17039 /// \param MagicValues Registered magic values.
17040 ///
17041 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
17042 ///        kind.
17043 ///
17044 /// \param TypeInfo Information about the corresponding C type.
17045 ///
17046 /// \param isConstantEvaluated whether the evalaution should be performed in
17047 /// constant context.
17048 ///
17049 /// \returns true if the corresponding C type was found.
17050 static bool GetMatchingCType(
17051     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
17052     const ASTContext &Ctx,
17053     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
17054         *MagicValues,
17055     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
17056     bool isConstantEvaluated) {
17057   FoundWrongKind = false;
17058 
17059   // Variable declaration that has type_tag_for_datatype attribute.
17060   const ValueDecl *VD = nullptr;
17061 
17062   uint64_t MagicValue;
17063 
17064   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
17065     return false;
17066 
17067   if (VD) {
17068     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
17069       if (I->getArgumentKind() != ArgumentKind) {
17070         FoundWrongKind = true;
17071         return false;
17072       }
17073       TypeInfo.Type = I->getMatchingCType();
17074       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
17075       TypeInfo.MustBeNull = I->getMustBeNull();
17076       return true;
17077     }
17078     return false;
17079   }
17080 
17081   if (!MagicValues)
17082     return false;
17083 
17084   llvm::DenseMap<Sema::TypeTagMagicValue,
17085                  Sema::TypeTagData>::const_iterator I =
17086       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
17087   if (I == MagicValues->end())
17088     return false;
17089 
17090   TypeInfo = I->second;
17091   return true;
17092 }
17093 
17094 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
17095                                       uint64_t MagicValue, QualType Type,
17096                                       bool LayoutCompatible,
17097                                       bool MustBeNull) {
17098   if (!TypeTagForDatatypeMagicValues)
17099     TypeTagForDatatypeMagicValues.reset(
17100         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
17101 
17102   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
17103   (*TypeTagForDatatypeMagicValues)[Magic] =
17104       TypeTagData(Type, LayoutCompatible, MustBeNull);
17105 }
17106 
17107 static bool IsSameCharType(QualType T1, QualType T2) {
17108   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
17109   if (!BT1)
17110     return false;
17111 
17112   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
17113   if (!BT2)
17114     return false;
17115 
17116   BuiltinType::Kind T1Kind = BT1->getKind();
17117   BuiltinType::Kind T2Kind = BT2->getKind();
17118 
17119   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
17120          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
17121          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
17122          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
17123 }
17124 
17125 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
17126                                     const ArrayRef<const Expr *> ExprArgs,
17127                                     SourceLocation CallSiteLoc) {
17128   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
17129   bool IsPointerAttr = Attr->getIsPointer();
17130 
17131   // Retrieve the argument representing the 'type_tag'.
17132   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
17133   if (TypeTagIdxAST >= ExprArgs.size()) {
17134     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
17135         << 0 << Attr->getTypeTagIdx().getSourceIndex();
17136     return;
17137   }
17138   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
17139   bool FoundWrongKind;
17140   TypeTagData TypeInfo;
17141   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
17142                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
17143                         TypeInfo, isConstantEvaluated())) {
17144     if (FoundWrongKind)
17145       Diag(TypeTagExpr->getExprLoc(),
17146            diag::warn_type_tag_for_datatype_wrong_kind)
17147         << TypeTagExpr->getSourceRange();
17148     return;
17149   }
17150 
17151   // Retrieve the argument representing the 'arg_idx'.
17152   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
17153   if (ArgumentIdxAST >= ExprArgs.size()) {
17154     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
17155         << 1 << Attr->getArgumentIdx().getSourceIndex();
17156     return;
17157   }
17158   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
17159   if (IsPointerAttr) {
17160     // Skip implicit cast of pointer to `void *' (as a function argument).
17161     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
17162       if (ICE->getType()->isVoidPointerType() &&
17163           ICE->getCastKind() == CK_BitCast)
17164         ArgumentExpr = ICE->getSubExpr();
17165   }
17166   QualType ArgumentType = ArgumentExpr->getType();
17167 
17168   // Passing a `void*' pointer shouldn't trigger a warning.
17169   if (IsPointerAttr && ArgumentType->isVoidPointerType())
17170     return;
17171 
17172   if (TypeInfo.MustBeNull) {
17173     // Type tag with matching void type requires a null pointer.
17174     if (!ArgumentExpr->isNullPointerConstant(Context,
17175                                              Expr::NPC_ValueDependentIsNotNull)) {
17176       Diag(ArgumentExpr->getExprLoc(),
17177            diag::warn_type_safety_null_pointer_required)
17178           << ArgumentKind->getName()
17179           << ArgumentExpr->getSourceRange()
17180           << TypeTagExpr->getSourceRange();
17181     }
17182     return;
17183   }
17184 
17185   QualType RequiredType = TypeInfo.Type;
17186   if (IsPointerAttr)
17187     RequiredType = Context.getPointerType(RequiredType);
17188 
17189   bool mismatch = false;
17190   if (!TypeInfo.LayoutCompatible) {
17191     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
17192 
17193     // C++11 [basic.fundamental] p1:
17194     // Plain char, signed char, and unsigned char are three distinct types.
17195     //
17196     // But we treat plain `char' as equivalent to `signed char' or `unsigned
17197     // char' depending on the current char signedness mode.
17198     if (mismatch)
17199       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
17200                                            RequiredType->getPointeeType())) ||
17201           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
17202         mismatch = false;
17203   } else
17204     if (IsPointerAttr)
17205       mismatch = !isLayoutCompatible(Context,
17206                                      ArgumentType->getPointeeType(),
17207                                      RequiredType->getPointeeType());
17208     else
17209       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
17210 
17211   if (mismatch)
17212     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
17213         << ArgumentType << ArgumentKind
17214         << TypeInfo.LayoutCompatible << RequiredType
17215         << ArgumentExpr->getSourceRange()
17216         << TypeTagExpr->getSourceRange();
17217 }
17218 
17219 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
17220                                          CharUnits Alignment) {
17221   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
17222 }
17223 
17224 void Sema::DiagnoseMisalignedMembers() {
17225   for (MisalignedMember &m : MisalignedMembers) {
17226     const NamedDecl *ND = m.RD;
17227     if (ND->getName().empty()) {
17228       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
17229         ND = TD;
17230     }
17231     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
17232         << m.MD << ND << m.E->getSourceRange();
17233   }
17234   MisalignedMembers.clear();
17235 }
17236 
17237 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
17238   E = E->IgnoreParens();
17239   if (!T->isPointerType() && !T->isIntegerType())
17240     return;
17241   if (isa<UnaryOperator>(E) &&
17242       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
17243     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
17244     if (isa<MemberExpr>(Op)) {
17245       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
17246       if (MA != MisalignedMembers.end() &&
17247           (T->isIntegerType() ||
17248            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
17249                                    Context.getTypeAlignInChars(
17250                                        T->getPointeeType()) <= MA->Alignment))))
17251         MisalignedMembers.erase(MA);
17252     }
17253   }
17254 }
17255 
17256 void Sema::RefersToMemberWithReducedAlignment(
17257     Expr *E,
17258     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
17259         Action) {
17260   const auto *ME = dyn_cast<MemberExpr>(E);
17261   if (!ME)
17262     return;
17263 
17264   // No need to check expressions with an __unaligned-qualified type.
17265   if (E->getType().getQualifiers().hasUnaligned())
17266     return;
17267 
17268   // For a chain of MemberExpr like "a.b.c.d" this list
17269   // will keep FieldDecl's like [d, c, b].
17270   SmallVector<FieldDecl *, 4> ReverseMemberChain;
17271   const MemberExpr *TopME = nullptr;
17272   bool AnyIsPacked = false;
17273   do {
17274     QualType BaseType = ME->getBase()->getType();
17275     if (BaseType->isDependentType())
17276       return;
17277     if (ME->isArrow())
17278       BaseType = BaseType->getPointeeType();
17279     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
17280     if (RD->isInvalidDecl())
17281       return;
17282 
17283     ValueDecl *MD = ME->getMemberDecl();
17284     auto *FD = dyn_cast<FieldDecl>(MD);
17285     // We do not care about non-data members.
17286     if (!FD || FD->isInvalidDecl())
17287       return;
17288 
17289     AnyIsPacked =
17290         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17291     ReverseMemberChain.push_back(FD);
17292 
17293     TopME = ME;
17294     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
17295   } while (ME);
17296   assert(TopME && "We did not compute a topmost MemberExpr!");
17297 
17298   // Not the scope of this diagnostic.
17299   if (!AnyIsPacked)
17300     return;
17301 
17302   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17303   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
17304   // TODO: The innermost base of the member expression may be too complicated.
17305   // For now, just disregard these cases. This is left for future
17306   // improvement.
17307   if (!DRE && !isa<CXXThisExpr>(TopBase))
17308       return;
17309 
17310   // Alignment expected by the whole expression.
17311   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
17312 
17313   // No need to do anything else with this case.
17314   if (ExpectedAlignment.isOne())
17315     return;
17316 
17317   // Synthesize offset of the whole access.
17318   CharUnits Offset;
17319   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
17320     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
17321 
17322   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17323   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17324       ReverseMemberChain.back()->getParent()->getTypeForDecl());
17325 
17326   // The base expression of the innermost MemberExpr may give
17327   // stronger guarantees than the class containing the member.
17328   if (DRE && !TopME->isArrow()) {
17329     const ValueDecl *VD = DRE->getDecl();
17330     if (!VD->getType()->isReferenceType())
17331       CompleteObjectAlignment =
17332           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
17333   }
17334 
17335   // Check if the synthesized offset fulfills the alignment.
17336   if (Offset % ExpectedAlignment != 0 ||
17337       // It may fulfill the offset it but the effective alignment may still be
17338       // lower than the expected expression alignment.
17339       CompleteObjectAlignment < ExpectedAlignment) {
17340     // If this happens, we want to determine a sensible culprit of this.
17341     // Intuitively, watching the chain of member expressions from right to
17342     // left, we start with the required alignment (as required by the field
17343     // type) but some packed attribute in that chain has reduced the alignment.
17344     // It may happen that another packed structure increases it again. But if
17345     // we are here such increase has not been enough. So pointing the first
17346     // FieldDecl that either is packed or else its RecordDecl is,
17347     // seems reasonable.
17348     FieldDecl *FD = nullptr;
17349     CharUnits Alignment;
17350     for (FieldDecl *FDI : ReverseMemberChain) {
17351       if (FDI->hasAttr<PackedAttr>() ||
17352           FDI->getParent()->hasAttr<PackedAttr>()) {
17353         FD = FDI;
17354         Alignment = std::min(
17355             Context.getTypeAlignInChars(FD->getType()),
17356             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
17357         break;
17358       }
17359     }
17360     assert(FD && "We did not find a packed FieldDecl!");
17361     Action(E, FD->getParent(), FD, Alignment);
17362   }
17363 }
17364 
17365 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17366   using namespace std::placeholders;
17367 
17368   RefersToMemberWithReducedAlignment(
17369       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
17370                      _2, _3, _4));
17371 }
17372 
17373 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
17374 // not a valid type, emit an error message and return true. Otherwise return
17375 // false.
17376 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
17377                                         QualType Ty) {
17378   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
17379     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
17380         << 1 << /* vector, integer or float ty*/ 0 << Ty;
17381     return true;
17382   }
17383   return false;
17384 }
17385 
17386 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
17387   if (checkArgCount(*this, TheCall, 1))
17388     return true;
17389 
17390   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17391   if (A.isInvalid())
17392     return true;
17393 
17394   TheCall->setArg(0, A.get());
17395   QualType TyA = A.get()->getType();
17396 
17397   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17398     return true;
17399 
17400   TheCall->setType(TyA);
17401   return false;
17402 }
17403 
17404 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
17405   if (checkArgCount(*this, TheCall, 2))
17406     return true;
17407 
17408   ExprResult A = TheCall->getArg(0);
17409   ExprResult B = TheCall->getArg(1);
17410   // Do standard promotions between the two arguments, returning their common
17411   // type.
17412   QualType Res =
17413       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
17414   if (A.isInvalid() || B.isInvalid())
17415     return true;
17416 
17417   QualType TyA = A.get()->getType();
17418   QualType TyB = B.get()->getType();
17419 
17420   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
17421     return Diag(A.get()->getBeginLoc(),
17422                 diag::err_typecheck_call_different_arg_types)
17423            << TyA << TyB;
17424 
17425   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
17426     return true;
17427 
17428   TheCall->setArg(0, A.get());
17429   TheCall->setArg(1, B.get());
17430   TheCall->setType(Res);
17431   return false;
17432 }
17433 
17434 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17435   if (checkArgCount(*this, TheCall, 1))
17436     return true;
17437 
17438   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17439   if (A.isInvalid())
17440     return true;
17441 
17442   TheCall->setArg(0, A.get());
17443   return false;
17444 }
17445 
17446 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
17447                                             ExprResult CallResult) {
17448   if (checkArgCount(*this, TheCall, 1))
17449     return ExprError();
17450 
17451   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17452   if (MatrixArg.isInvalid())
17453     return MatrixArg;
17454   Expr *Matrix = MatrixArg.get();
17455 
17456   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17457   if (!MType) {
17458     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17459         << 1 << /* matrix ty*/ 1 << Matrix->getType();
17460     return ExprError();
17461   }
17462 
17463   // Create returned matrix type by swapping rows and columns of the argument
17464   // matrix type.
17465   QualType ResultType = Context.getConstantMatrixType(
17466       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17467 
17468   // Change the return type to the type of the returned matrix.
17469   TheCall->setType(ResultType);
17470 
17471   // Update call argument to use the possibly converted matrix argument.
17472   TheCall->setArg(0, Matrix);
17473   return CallResult;
17474 }
17475 
17476 // Get and verify the matrix dimensions.
17477 static llvm::Optional<unsigned>
17478 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17479   SourceLocation ErrorPos;
17480   Optional<llvm::APSInt> Value =
17481       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
17482   if (!Value) {
17483     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17484         << Name;
17485     return {};
17486   }
17487   uint64_t Dim = Value->getZExtValue();
17488   if (!ConstantMatrixType::isDimensionValid(Dim)) {
17489     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17490         << Name << ConstantMatrixType::getMaxElementsPerDimension();
17491     return {};
17492   }
17493   return Dim;
17494 }
17495 
17496 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17497                                                   ExprResult CallResult) {
17498   if (!getLangOpts().MatrixTypes) {
17499     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17500     return ExprError();
17501   }
17502 
17503   if (checkArgCount(*this, TheCall, 4))
17504     return ExprError();
17505 
17506   unsigned PtrArgIdx = 0;
17507   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17508   Expr *RowsExpr = TheCall->getArg(1);
17509   Expr *ColumnsExpr = TheCall->getArg(2);
17510   Expr *StrideExpr = TheCall->getArg(3);
17511 
17512   bool ArgError = false;
17513 
17514   // Check pointer argument.
17515   {
17516     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17517     if (PtrConv.isInvalid())
17518       return PtrConv;
17519     PtrExpr = PtrConv.get();
17520     TheCall->setArg(0, PtrExpr);
17521     if (PtrExpr->isTypeDependent()) {
17522       TheCall->setType(Context.DependentTy);
17523       return TheCall;
17524     }
17525   }
17526 
17527   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17528   QualType ElementTy;
17529   if (!PtrTy) {
17530     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17531         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17532     ArgError = true;
17533   } else {
17534     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17535 
17536     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
17537       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17538           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
17539           << PtrExpr->getType();
17540       ArgError = true;
17541     }
17542   }
17543 
17544   // Apply default Lvalue conversions and convert the expression to size_t.
17545   auto ApplyArgumentConversions = [this](Expr *E) {
17546     ExprResult Conv = DefaultLvalueConversion(E);
17547     if (Conv.isInvalid())
17548       return Conv;
17549 
17550     return tryConvertExprToType(Conv.get(), Context.getSizeType());
17551   };
17552 
17553   // Apply conversion to row and column expressions.
17554   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17555   if (!RowsConv.isInvalid()) {
17556     RowsExpr = RowsConv.get();
17557     TheCall->setArg(1, RowsExpr);
17558   } else
17559     RowsExpr = nullptr;
17560 
17561   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17562   if (!ColumnsConv.isInvalid()) {
17563     ColumnsExpr = ColumnsConv.get();
17564     TheCall->setArg(2, ColumnsExpr);
17565   } else
17566     ColumnsExpr = nullptr;
17567 
17568   // If any any part of the result matrix type is still pending, just use
17569   // Context.DependentTy, until all parts are resolved.
17570   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17571       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17572     TheCall->setType(Context.DependentTy);
17573     return CallResult;
17574   }
17575 
17576   // Check row and column dimensions.
17577   llvm::Optional<unsigned> MaybeRows;
17578   if (RowsExpr)
17579     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17580 
17581   llvm::Optional<unsigned> MaybeColumns;
17582   if (ColumnsExpr)
17583     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17584 
17585   // Check stride argument.
17586   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17587   if (StrideConv.isInvalid())
17588     return ExprError();
17589   StrideExpr = StrideConv.get();
17590   TheCall->setArg(3, StrideExpr);
17591 
17592   if (MaybeRows) {
17593     if (Optional<llvm::APSInt> Value =
17594             StrideExpr->getIntegerConstantExpr(Context)) {
17595       uint64_t Stride = Value->getZExtValue();
17596       if (Stride < *MaybeRows) {
17597         Diag(StrideExpr->getBeginLoc(),
17598              diag::err_builtin_matrix_stride_too_small);
17599         ArgError = true;
17600       }
17601     }
17602   }
17603 
17604   if (ArgError || !MaybeRows || !MaybeColumns)
17605     return ExprError();
17606 
17607   TheCall->setType(
17608       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17609   return CallResult;
17610 }
17611 
17612 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17613                                                    ExprResult CallResult) {
17614   if (checkArgCount(*this, TheCall, 3))
17615     return ExprError();
17616 
17617   unsigned PtrArgIdx = 1;
17618   Expr *MatrixExpr = TheCall->getArg(0);
17619   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17620   Expr *StrideExpr = TheCall->getArg(2);
17621 
17622   bool ArgError = false;
17623 
17624   {
17625     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17626     if (MatrixConv.isInvalid())
17627       return MatrixConv;
17628     MatrixExpr = MatrixConv.get();
17629     TheCall->setArg(0, MatrixExpr);
17630   }
17631   if (MatrixExpr->isTypeDependent()) {
17632     TheCall->setType(Context.DependentTy);
17633     return TheCall;
17634   }
17635 
17636   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17637   if (!MatrixTy) {
17638     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17639         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
17640     ArgError = true;
17641   }
17642 
17643   {
17644     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
17645     if (PtrConv.isInvalid())
17646       return PtrConv;
17647     PtrExpr = PtrConv.get();
17648     TheCall->setArg(1, PtrExpr);
17649     if (PtrExpr->isTypeDependent()) {
17650       TheCall->setType(Context.DependentTy);
17651       return TheCall;
17652     }
17653   }
17654 
17655   // Check pointer argument.
17656   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17657   if (!PtrTy) {
17658     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17659         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
17660     ArgError = true;
17661   } else {
17662     QualType ElementTy = PtrTy->getPointeeType();
17663     if (ElementTy.isConstQualified()) {
17664       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17665       ArgError = true;
17666     }
17667     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17668     if (MatrixTy &&
17669         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17670       Diag(PtrExpr->getBeginLoc(),
17671            diag::err_builtin_matrix_pointer_arg_mismatch)
17672           << ElementTy << MatrixTy->getElementType();
17673       ArgError = true;
17674     }
17675   }
17676 
17677   // Apply default Lvalue conversions and convert the stride expression to
17678   // size_t.
17679   {
17680     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17681     if (StrideConv.isInvalid())
17682       return StrideConv;
17683 
17684     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17685     if (StrideConv.isInvalid())
17686       return StrideConv;
17687     StrideExpr = StrideConv.get();
17688     TheCall->setArg(2, StrideExpr);
17689   }
17690 
17691   // Check stride argument.
17692   if (MatrixTy) {
17693     if (Optional<llvm::APSInt> Value =
17694             StrideExpr->getIntegerConstantExpr(Context)) {
17695       uint64_t Stride = Value->getZExtValue();
17696       if (Stride < MatrixTy->getNumRows()) {
17697         Diag(StrideExpr->getBeginLoc(),
17698              diag::err_builtin_matrix_stride_too_small);
17699         ArgError = true;
17700       }
17701     }
17702   }
17703 
17704   if (ArgError)
17705     return ExprError();
17706 
17707   return CallResult;
17708 }
17709 
17710 /// \brief Enforce the bounds of a TCB
17711 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17712 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17713 /// and enforce_tcb_leaf attributes.
17714 void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17715                                const NamedDecl *Callee) {
17716   const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17717 
17718   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17719     return;
17720 
17721   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17722   // all TCBs the callee is a part of.
17723   llvm::StringSet<> CalleeTCBs;
17724   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17725            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17726   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17727            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17728 
17729   // Go through the TCBs the caller is a part of and emit warnings if Caller
17730   // is in a TCB that the Callee is not.
17731   for_each(
17732       Caller->specific_attrs<EnforceTCBAttr>(),
17733       [&](const auto *A) {
17734         StringRef CallerTCB = A->getTCBName();
17735         if (CalleeTCBs.count(CallerTCB) == 0) {
17736           this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17737               << Callee << CallerTCB;
17738         }
17739       });
17740 }
17741