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/Stmt.h"
34 #include "clang/AST/TemplateBase.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/UnresolvedSet.h"
38 #include "clang/Basic/AddressSpaces.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/OpenCLOptions.h"
45 #include "clang/Basic/OperatorKinds.h"
46 #include "clang/Basic/PartialDiagnostic.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/SyncScope.h"
51 #include "clang/Basic/TargetBuiltins.h"
52 #include "clang/Basic/TargetCXXABI.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TypeTraits.h"
55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
56 #include "clang/Sema/Initialization.h"
57 #include "clang/Sema/Lookup.h"
58 #include "clang/Sema/Ownership.h"
59 #include "clang/Sema/Scope.h"
60 #include "clang/Sema/ScopeInfo.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/SemaInternal.h"
63 #include "llvm/ADT/APFloat.h"
64 #include "llvm/ADT/APInt.h"
65 #include "llvm/ADT/APSInt.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallString.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/StringSwitch.h"
78 #include "llvm/ADT/Triple.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ConvertUTF.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/Locale.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include <algorithm>
89 #include <cassert>
90 #include <cstddef>
91 #include <cstdint>
92 #include <functional>
93 #include <limits>
94 #include <string>
95 #include <tuple>
96 #include <utility>
97 
98 using namespace clang;
99 using namespace sema;
100 
101 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
102                                                     unsigned ByteNo) const {
103   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104                                Context.getTargetInfo());
105 }
106 
107 /// Checks that a call expression's argument count is the desired number.
108 /// This is useful when doing custom type-checking.  Returns true on error.
109 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
110   unsigned argCount = call->getNumArgs();
111   if (argCount == desiredArgCount) return false;
112 
113   if (argCount < desiredArgCount)
114     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
115            << 0 /*function call*/ << desiredArgCount << argCount
116            << call->getSourceRange();
117 
118   // Highlight all the excess arguments.
119   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
120                     call->getArg(argCount - 1)->getEndLoc());
121 
122   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123     << 0 /*function call*/ << desiredArgCount << argCount
124     << call->getArg(1)->getSourceRange();
125 }
126 
127 /// Check that the first argument to __builtin_annotation is an integer
128 /// and the second argument is a non-wide string literal.
129 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
130   if (checkArgCount(S, TheCall, 2))
131     return true;
132 
133   // First argument should be an integer.
134   Expr *ValArg = TheCall->getArg(0);
135   QualType Ty = ValArg->getType();
136   if (!Ty->isIntegerType()) {
137     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
138         << ValArg->getSourceRange();
139     return true;
140   }
141 
142   // Second argument should be a constant string.
143   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
144   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
145   if (!Literal || !Literal->isAscii()) {
146     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
147         << StrArg->getSourceRange();
148     return true;
149   }
150 
151   TheCall->setType(Ty);
152   return false;
153 }
154 
155 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
156   // We need at least one argument.
157   if (TheCall->getNumArgs() < 1) {
158     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
159         << 0 << 1 << TheCall->getNumArgs()
160         << TheCall->getCallee()->getSourceRange();
161     return true;
162   }
163 
164   // All arguments should be wide string literals.
165   for (Expr *Arg : TheCall->arguments()) {
166     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
167     if (!Literal || !Literal->isWide()) {
168       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
169           << Arg->getSourceRange();
170       return true;
171     }
172   }
173 
174   return false;
175 }
176 
177 /// Check that the argument to __builtin_addressof is a glvalue, and set the
178 /// result type to the corresponding pointer type.
179 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180   if (checkArgCount(S, TheCall, 1))
181     return true;
182 
183   ExprResult Arg(TheCall->getArg(0));
184   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
185   if (ResultType.isNull())
186     return true;
187 
188   TheCall->setArg(0, Arg.get());
189   TheCall->setType(ResultType);
190   return false;
191 }
192 
193 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
194   if (checkArgCount(S, TheCall, 3))
195     return true;
196 
197   // First two arguments should be integers.
198   for (unsigned I = 0; I < 2; ++I) {
199     ExprResult Arg = TheCall->getArg(I);
200     QualType Ty = Arg.get()->getType();
201     if (!Ty->isIntegerType()) {
202       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
203           << Ty << Arg.get()->getSourceRange();
204       return true;
205     }
206     InitializedEntity Entity = InitializedEntity::InitializeParameter(
207         S.getASTContext(), Ty, /*consume*/ false);
208     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
209     if (Arg.isInvalid())
210       return true;
211     TheCall->setArg(I, Arg.get());
212   }
213 
214   // Third argument should be a pointer to a non-const integer.
215   // IRGen correctly handles volatile, restrict, and address spaces, and
216   // the other qualifiers aren't possible.
217   {
218     ExprResult Arg = TheCall->getArg(2);
219     QualType Ty = Arg.get()->getType();
220     const auto *PtrTy = Ty->getAs<PointerType>();
221     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
222           !PtrTy->getPointeeType().isConstQualified())) {
223       S.Diag(Arg.get()->getBeginLoc(),
224              diag::err_overflow_builtin_must_be_ptr_int)
225           << Ty << Arg.get()->getSourceRange();
226       return true;
227     }
228     InitializedEntity Entity = InitializedEntity::InitializeParameter(
229         S.getASTContext(), Ty, /*consume*/ false);
230     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
231     if (Arg.isInvalid())
232       return true;
233     TheCall->setArg(2, Arg.get());
234   }
235   return false;
236 }
237 
238 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
239   if (checkArgCount(S, BuiltinCall, 2))
240     return true;
241 
242   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
243   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
244   Expr *Call = BuiltinCall->getArg(0);
245   Expr *Chain = BuiltinCall->getArg(1);
246 
247   if (Call->getStmtClass() != Stmt::CallExprClass) {
248     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
249         << Call->getSourceRange();
250     return true;
251   }
252 
253   auto CE = cast<CallExpr>(Call);
254   if (CE->getCallee()->getType()->isBlockPointerType()) {
255     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
256         << Call->getSourceRange();
257     return true;
258   }
259 
260   const Decl *TargetDecl = CE->getCalleeDecl();
261   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
262     if (FD->getBuiltinID()) {
263       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
264           << Call->getSourceRange();
265       return true;
266     }
267 
268   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
269     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
270         << Call->getSourceRange();
271     return true;
272   }
273 
274   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
275   if (ChainResult.isInvalid())
276     return true;
277   if (!ChainResult.get()->getType()->isPointerType()) {
278     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
279         << Chain->getSourceRange();
280     return true;
281   }
282 
283   QualType ReturnTy = CE->getCallReturnType(S.Context);
284   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
285   QualType BuiltinTy = S.Context.getFunctionType(
286       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
287   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
288 
289   Builtin =
290       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
291 
292   BuiltinCall->setType(CE->getType());
293   BuiltinCall->setValueKind(CE->getValueKind());
294   BuiltinCall->setObjectKind(CE->getObjectKind());
295   BuiltinCall->setCallee(Builtin);
296   BuiltinCall->setArg(1, ChainResult.get());
297 
298   return false;
299 }
300 
301 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
302 /// __builtin_*_chk function, then use the object size argument specified in the
303 /// source. Otherwise, infer the object size using __builtin_object_size.
304 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
305                                                CallExpr *TheCall) {
306   // FIXME: There are some more useful checks we could be doing here:
307   //  - Analyze the format string of sprintf to see how much of buffer is used.
308   //  - Evaluate strlen of strcpy arguments, use as object size.
309 
310   if (TheCall->isValueDependent() || TheCall->isTypeDependent())
311     return;
312 
313   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
314   if (!BuiltinID)
315     return;
316 
317   unsigned DiagID = 0;
318   bool IsChkVariant = false;
319   unsigned SizeIndex, ObjectIndex;
320   switch (BuiltinID) {
321   default:
322     return;
323   case Builtin::BI__builtin___memcpy_chk:
324   case Builtin::BI__builtin___memmove_chk:
325   case Builtin::BI__builtin___memset_chk:
326   case Builtin::BI__builtin___strlcat_chk:
327   case Builtin::BI__builtin___strlcpy_chk:
328   case Builtin::BI__builtin___strncat_chk:
329   case Builtin::BI__builtin___strncpy_chk:
330   case Builtin::BI__builtin___stpncpy_chk:
331   case Builtin::BI__builtin___memccpy_chk: {
332     DiagID = diag::warn_builtin_chk_overflow;
333     IsChkVariant = true;
334     SizeIndex = TheCall->getNumArgs() - 2;
335     ObjectIndex = TheCall->getNumArgs() - 1;
336     break;
337   }
338 
339   case Builtin::BI__builtin___snprintf_chk:
340   case Builtin::BI__builtin___vsnprintf_chk: {
341     DiagID = diag::warn_builtin_chk_overflow;
342     IsChkVariant = true;
343     SizeIndex = 1;
344     ObjectIndex = 3;
345     break;
346   }
347 
348   case Builtin::BIstrncat:
349   case Builtin::BI__builtin_strncat:
350   case Builtin::BIstrncpy:
351   case Builtin::BI__builtin_strncpy:
352   case Builtin::BIstpncpy:
353   case Builtin::BI__builtin_stpncpy: {
354     // Whether these functions overflow depends on the runtime strlen of the
355     // string, not just the buffer size, so emitting the "always overflow"
356     // diagnostic isn't quite right. We should still diagnose passing a buffer
357     // size larger than the destination buffer though; this is a runtime abort
358     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
359     DiagID = diag::warn_fortify_source_size_mismatch;
360     SizeIndex = TheCall->getNumArgs() - 1;
361     ObjectIndex = 0;
362     break;
363   }
364 
365   case Builtin::BImemcpy:
366   case Builtin::BI__builtin_memcpy:
367   case Builtin::BImemmove:
368   case Builtin::BI__builtin_memmove:
369   case Builtin::BImemset:
370   case Builtin::BI__builtin_memset: {
371     DiagID = diag::warn_fortify_source_overflow;
372     SizeIndex = TheCall->getNumArgs() - 1;
373     ObjectIndex = 0;
374     break;
375   }
376   case Builtin::BIsnprintf:
377   case Builtin::BI__builtin_snprintf:
378   case Builtin::BIvsnprintf:
379   case Builtin::BI__builtin_vsnprintf: {
380     DiagID = diag::warn_fortify_source_size_mismatch;
381     SizeIndex = 1;
382     ObjectIndex = 0;
383     break;
384   }
385   }
386 
387   llvm::APSInt ObjectSize;
388   // For __builtin___*_chk, the object size is explicitly provided by the caller
389   // (usually using __builtin_object_size). Use that value to check this call.
390   if (IsChkVariant) {
391     Expr::EvalResult Result;
392     Expr *SizeArg = TheCall->getArg(ObjectIndex);
393     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
394       return;
395     ObjectSize = Result.Val.getInt();
396 
397   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
398   } else {
399     // If the parameter has a pass_object_size attribute, then we should use its
400     // (potentially) more strict checking mode. Otherwise, conservatively assume
401     // type 0.
402     int BOSType = 0;
403     if (const auto *POS =
404             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
405       BOSType = POS->getType();
406 
407     Expr *ObjArg = TheCall->getArg(ObjectIndex);
408     uint64_t Result;
409     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
410       return;
411     // Get the object size in the target's size_t width.
412     const TargetInfo &TI = getASTContext().getTargetInfo();
413     unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
414     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
415   }
416 
417   // Evaluate the number of bytes of the object that this call will use.
418   Expr::EvalResult Result;
419   Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
420   if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
421     return;
422   llvm::APSInt UsedSize = Result.Val.getInt();
423 
424   if (UsedSize.ule(ObjectSize))
425     return;
426 
427   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
428   // Skim off the details of whichever builtin was called to produce a better
429   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
430   if (IsChkVariant) {
431     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
432     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
433   } else if (FunctionName.startswith("__builtin_")) {
434     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
435   }
436 
437   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
438                       PDiag(DiagID)
439                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
440                           << UsedSize.toString(/*Radix=*/10));
441 }
442 
443 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
444                                      Scope::ScopeFlags NeededScopeFlags,
445                                      unsigned DiagID) {
446   // Scopes aren't available during instantiation. Fortunately, builtin
447   // functions cannot be template args so they cannot be formed through template
448   // instantiation. Therefore checking once during the parse is sufficient.
449   if (SemaRef.inTemplateInstantiation())
450     return false;
451 
452   Scope *S = SemaRef.getCurScope();
453   while (S && !S->isSEHExceptScope())
454     S = S->getParent();
455   if (!S || !(S->getFlags() & NeededScopeFlags)) {
456     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
457     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
458         << DRE->getDecl()->getIdentifier();
459     return true;
460   }
461 
462   return false;
463 }
464 
465 static inline bool isBlockPointer(Expr *Arg) {
466   return Arg->getType()->isBlockPointerType();
467 }
468 
469 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
470 /// void*, which is a requirement of device side enqueue.
471 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
472   const BlockPointerType *BPT =
473       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
474   ArrayRef<QualType> Params =
475       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
476   unsigned ArgCounter = 0;
477   bool IllegalParams = false;
478   // Iterate through the block parameters until either one is found that is not
479   // a local void*, or the block is valid.
480   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
481        I != E; ++I, ++ArgCounter) {
482     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
483         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
484             LangAS::opencl_local) {
485       // Get the location of the error. If a block literal has been passed
486       // (BlockExpr) then we can point straight to the offending argument,
487       // else we just point to the variable reference.
488       SourceLocation ErrorLoc;
489       if (isa<BlockExpr>(BlockArg)) {
490         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
491         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
492       } else if (isa<DeclRefExpr>(BlockArg)) {
493         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
494       }
495       S.Diag(ErrorLoc,
496              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
497       IllegalParams = true;
498     }
499   }
500 
501   return IllegalParams;
502 }
503 
504 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
505   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
506     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
507         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
508     return true;
509   }
510   return false;
511 }
512 
513 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
514   if (checkArgCount(S, TheCall, 2))
515     return true;
516 
517   if (checkOpenCLSubgroupExt(S, TheCall))
518     return true;
519 
520   // First argument is an ndrange_t type.
521   Expr *NDRangeArg = TheCall->getArg(0);
522   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
523     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
524         << TheCall->getDirectCallee() << "'ndrange_t'";
525     return true;
526   }
527 
528   Expr *BlockArg = TheCall->getArg(1);
529   if (!isBlockPointer(BlockArg)) {
530     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
531         << TheCall->getDirectCallee() << "block";
532     return true;
533   }
534   return checkOpenCLBlockArgs(S, BlockArg);
535 }
536 
537 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
538 /// get_kernel_work_group_size
539 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
540 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
541   if (checkArgCount(S, TheCall, 1))
542     return true;
543 
544   Expr *BlockArg = TheCall->getArg(0);
545   if (!isBlockPointer(BlockArg)) {
546     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
547         << TheCall->getDirectCallee() << "block";
548     return true;
549   }
550   return checkOpenCLBlockArgs(S, BlockArg);
551 }
552 
553 /// Diagnose integer type and any valid implicit conversion to it.
554 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
555                                       const QualType &IntType);
556 
557 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
558                                             unsigned Start, unsigned End) {
559   bool IllegalParams = false;
560   for (unsigned I = Start; I <= End; ++I)
561     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
562                                               S.Context.getSizeType());
563   return IllegalParams;
564 }
565 
566 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
567 /// 'local void*' parameter of passed block.
568 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
569                                            Expr *BlockArg,
570                                            unsigned NumNonVarArgs) {
571   const BlockPointerType *BPT =
572       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
573   unsigned NumBlockParams =
574       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
575   unsigned TotalNumArgs = TheCall->getNumArgs();
576 
577   // For each argument passed to the block, a corresponding uint needs to
578   // be passed to describe the size of the local memory.
579   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
580     S.Diag(TheCall->getBeginLoc(),
581            diag::err_opencl_enqueue_kernel_local_size_args);
582     return true;
583   }
584 
585   // Check that the sizes of the local memory are specified by integers.
586   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
587                                          TotalNumArgs - 1);
588 }
589 
590 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
591 /// overload formats specified in Table 6.13.17.1.
592 /// int enqueue_kernel(queue_t queue,
593 ///                    kernel_enqueue_flags_t flags,
594 ///                    const ndrange_t ndrange,
595 ///                    void (^block)(void))
596 /// int enqueue_kernel(queue_t queue,
597 ///                    kernel_enqueue_flags_t flags,
598 ///                    const ndrange_t ndrange,
599 ///                    uint num_events_in_wait_list,
600 ///                    clk_event_t *event_wait_list,
601 ///                    clk_event_t *event_ret,
602 ///                    void (^block)(void))
603 /// int enqueue_kernel(queue_t queue,
604 ///                    kernel_enqueue_flags_t flags,
605 ///                    const ndrange_t ndrange,
606 ///                    void (^block)(local void*, ...),
607 ///                    uint size0, ...)
608 /// int enqueue_kernel(queue_t queue,
609 ///                    kernel_enqueue_flags_t flags,
610 ///                    const ndrange_t ndrange,
611 ///                    uint num_events_in_wait_list,
612 ///                    clk_event_t *event_wait_list,
613 ///                    clk_event_t *event_ret,
614 ///                    void (^block)(local void*, ...),
615 ///                    uint size0, ...)
616 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
617   unsigned NumArgs = TheCall->getNumArgs();
618 
619   if (NumArgs < 4) {
620     S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
621     return true;
622   }
623 
624   Expr *Arg0 = TheCall->getArg(0);
625   Expr *Arg1 = TheCall->getArg(1);
626   Expr *Arg2 = TheCall->getArg(2);
627   Expr *Arg3 = TheCall->getArg(3);
628 
629   // First argument always needs to be a queue_t type.
630   if (!Arg0->getType()->isQueueT()) {
631     S.Diag(TheCall->getArg(0)->getBeginLoc(),
632            diag::err_opencl_builtin_expected_type)
633         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
634     return true;
635   }
636 
637   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
638   if (!Arg1->getType()->isIntegerType()) {
639     S.Diag(TheCall->getArg(1)->getBeginLoc(),
640            diag::err_opencl_builtin_expected_type)
641         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
642     return true;
643   }
644 
645   // Third argument is always an ndrange_t type.
646   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
647     S.Diag(TheCall->getArg(2)->getBeginLoc(),
648            diag::err_opencl_builtin_expected_type)
649         << TheCall->getDirectCallee() << "'ndrange_t'";
650     return true;
651   }
652 
653   // With four arguments, there is only one form that the function could be
654   // called in: no events and no variable arguments.
655   if (NumArgs == 4) {
656     // check that the last argument is the right block type.
657     if (!isBlockPointer(Arg3)) {
658       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
659           << TheCall->getDirectCallee() << "block";
660       return true;
661     }
662     // we have a block type, check the prototype
663     const BlockPointerType *BPT =
664         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
665     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
666       S.Diag(Arg3->getBeginLoc(),
667              diag::err_opencl_enqueue_kernel_blocks_no_args);
668       return true;
669     }
670     return false;
671   }
672   // we can have block + varargs.
673   if (isBlockPointer(Arg3))
674     return (checkOpenCLBlockArgs(S, Arg3) ||
675             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
676   // last two cases with either exactly 7 args or 7 args and varargs.
677   if (NumArgs >= 7) {
678     // check common block argument.
679     Expr *Arg6 = TheCall->getArg(6);
680     if (!isBlockPointer(Arg6)) {
681       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
682           << TheCall->getDirectCallee() << "block";
683       return true;
684     }
685     if (checkOpenCLBlockArgs(S, Arg6))
686       return true;
687 
688     // Forth argument has to be any integer type.
689     if (!Arg3->getType()->isIntegerType()) {
690       S.Diag(TheCall->getArg(3)->getBeginLoc(),
691              diag::err_opencl_builtin_expected_type)
692           << TheCall->getDirectCallee() << "integer";
693       return true;
694     }
695     // check remaining common arguments.
696     Expr *Arg4 = TheCall->getArg(4);
697     Expr *Arg5 = TheCall->getArg(5);
698 
699     // Fifth argument is always passed as a pointer to clk_event_t.
700     if (!Arg4->isNullPointerConstant(S.Context,
701                                      Expr::NPC_ValueDependentIsNotNull) &&
702         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
703       S.Diag(TheCall->getArg(4)->getBeginLoc(),
704              diag::err_opencl_builtin_expected_type)
705           << TheCall->getDirectCallee()
706           << S.Context.getPointerType(S.Context.OCLClkEventTy);
707       return true;
708     }
709 
710     // Sixth argument is always passed as a pointer to clk_event_t.
711     if (!Arg5->isNullPointerConstant(S.Context,
712                                      Expr::NPC_ValueDependentIsNotNull) &&
713         !(Arg5->getType()->isPointerType() &&
714           Arg5->getType()->getPointeeType()->isClkEventT())) {
715       S.Diag(TheCall->getArg(5)->getBeginLoc(),
716              diag::err_opencl_builtin_expected_type)
717           << TheCall->getDirectCallee()
718           << S.Context.getPointerType(S.Context.OCLClkEventTy);
719       return true;
720     }
721 
722     if (NumArgs == 7)
723       return false;
724 
725     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
726   }
727 
728   // None of the specific case has been detected, give generic error
729   S.Diag(TheCall->getBeginLoc(),
730          diag::err_opencl_enqueue_kernel_incorrect_args);
731   return true;
732 }
733 
734 /// Returns OpenCL access qual.
735 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
736     return D->getAttr<OpenCLAccessAttr>();
737 }
738 
739 /// Returns true if pipe element type is different from the pointer.
740 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
741   const Expr *Arg0 = Call->getArg(0);
742   // First argument type should always be pipe.
743   if (!Arg0->getType()->isPipeType()) {
744     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
745         << Call->getDirectCallee() << Arg0->getSourceRange();
746     return true;
747   }
748   OpenCLAccessAttr *AccessQual =
749       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
750   // Validates the access qualifier is compatible with the call.
751   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
752   // read_only and write_only, and assumed to be read_only if no qualifier is
753   // specified.
754   switch (Call->getDirectCallee()->getBuiltinID()) {
755   case Builtin::BIread_pipe:
756   case Builtin::BIreserve_read_pipe:
757   case Builtin::BIcommit_read_pipe:
758   case Builtin::BIwork_group_reserve_read_pipe:
759   case Builtin::BIsub_group_reserve_read_pipe:
760   case Builtin::BIwork_group_commit_read_pipe:
761   case Builtin::BIsub_group_commit_read_pipe:
762     if (!(!AccessQual || AccessQual->isReadOnly())) {
763       S.Diag(Arg0->getBeginLoc(),
764              diag::err_opencl_builtin_pipe_invalid_access_modifier)
765           << "read_only" << Arg0->getSourceRange();
766       return true;
767     }
768     break;
769   case Builtin::BIwrite_pipe:
770   case Builtin::BIreserve_write_pipe:
771   case Builtin::BIcommit_write_pipe:
772   case Builtin::BIwork_group_reserve_write_pipe:
773   case Builtin::BIsub_group_reserve_write_pipe:
774   case Builtin::BIwork_group_commit_write_pipe:
775   case Builtin::BIsub_group_commit_write_pipe:
776     if (!(AccessQual && AccessQual->isWriteOnly())) {
777       S.Diag(Arg0->getBeginLoc(),
778              diag::err_opencl_builtin_pipe_invalid_access_modifier)
779           << "write_only" << Arg0->getSourceRange();
780       return true;
781     }
782     break;
783   default:
784     break;
785   }
786   return false;
787 }
788 
789 /// Returns true if pipe element type is different from the pointer.
790 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
791   const Expr *Arg0 = Call->getArg(0);
792   const Expr *ArgIdx = Call->getArg(Idx);
793   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
794   const QualType EltTy = PipeTy->getElementType();
795   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
796   // The Idx argument should be a pointer and the type of the pointer and
797   // the type of pipe element should also be the same.
798   if (!ArgTy ||
799       !S.Context.hasSameType(
800           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
801     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
802         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
803         << ArgIdx->getType() << ArgIdx->getSourceRange();
804     return true;
805   }
806   return false;
807 }
808 
809 // Performs semantic analysis for the read/write_pipe call.
810 // \param S Reference to the semantic analyzer.
811 // \param Call A pointer to the builtin call.
812 // \return True if a semantic error has been found, false otherwise.
813 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
814   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
815   // functions have two forms.
816   switch (Call->getNumArgs()) {
817   case 2:
818     if (checkOpenCLPipeArg(S, Call))
819       return true;
820     // The call with 2 arguments should be
821     // read/write_pipe(pipe T, T*).
822     // Check packet type T.
823     if (checkOpenCLPipePacketType(S, Call, 1))
824       return true;
825     break;
826 
827   case 4: {
828     if (checkOpenCLPipeArg(S, Call))
829       return true;
830     // The call with 4 arguments should be
831     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
832     // Check reserve_id_t.
833     if (!Call->getArg(1)->getType()->isReserveIDT()) {
834       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
835           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
836           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
837       return true;
838     }
839 
840     // Check the index.
841     const Expr *Arg2 = Call->getArg(2);
842     if (!Arg2->getType()->isIntegerType() &&
843         !Arg2->getType()->isUnsignedIntegerType()) {
844       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
845           << Call->getDirectCallee() << S.Context.UnsignedIntTy
846           << Arg2->getType() << Arg2->getSourceRange();
847       return true;
848     }
849 
850     // Check packet type T.
851     if (checkOpenCLPipePacketType(S, Call, 3))
852       return true;
853   } break;
854   default:
855     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
856         << Call->getDirectCallee() << Call->getSourceRange();
857     return true;
858   }
859 
860   return false;
861 }
862 
863 // Performs a semantic analysis on the {work_group_/sub_group_
864 //        /_}reserve_{read/write}_pipe
865 // \param S Reference to the semantic analyzer.
866 // \param Call The call to the builtin function to be analyzed.
867 // \return True if a semantic error was found, false otherwise.
868 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
869   if (checkArgCount(S, Call, 2))
870     return true;
871 
872   if (checkOpenCLPipeArg(S, Call))
873     return true;
874 
875   // Check the reserve size.
876   if (!Call->getArg(1)->getType()->isIntegerType() &&
877       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
878     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
879         << Call->getDirectCallee() << S.Context.UnsignedIntTy
880         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
881     return true;
882   }
883 
884   // Since return type of reserve_read/write_pipe built-in function is
885   // reserve_id_t, which is not defined in the builtin def file , we used int
886   // as return type and need to override the return type of these functions.
887   Call->setType(S.Context.OCLReserveIDTy);
888 
889   return false;
890 }
891 
892 // Performs a semantic analysis on {work_group_/sub_group_
893 //        /_}commit_{read/write}_pipe
894 // \param S Reference to the semantic analyzer.
895 // \param Call The call to the builtin function to be analyzed.
896 // \return True if a semantic error was found, false otherwise.
897 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
898   if (checkArgCount(S, Call, 2))
899     return true;
900 
901   if (checkOpenCLPipeArg(S, Call))
902     return true;
903 
904   // Check reserve_id_t.
905   if (!Call->getArg(1)->getType()->isReserveIDT()) {
906     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
907         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
908         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
909     return true;
910   }
911 
912   return false;
913 }
914 
915 // Performs a semantic analysis on the call to built-in Pipe
916 //        Query Functions.
917 // \param S Reference to the semantic analyzer.
918 // \param Call The call to the builtin function to be analyzed.
919 // \return True if a semantic error was found, false otherwise.
920 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
921   if (checkArgCount(S, Call, 1))
922     return true;
923 
924   if (!Call->getArg(0)->getType()->isPipeType()) {
925     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
926         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
927     return true;
928   }
929 
930   return false;
931 }
932 
933 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
934 // Performs semantic analysis for the to_global/local/private call.
935 // \param S Reference to the semantic analyzer.
936 // \param BuiltinID ID of the builtin function.
937 // \param Call A pointer to the builtin call.
938 // \return True if a semantic error has been found, false otherwise.
939 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
940                                     CallExpr *Call) {
941   if (Call->getNumArgs() != 1) {
942     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
943         << Call->getDirectCallee() << Call->getSourceRange();
944     return true;
945   }
946 
947   auto RT = Call->getArg(0)->getType();
948   if (!RT->isPointerType() || RT->getPointeeType()
949       .getAddressSpace() == LangAS::opencl_constant) {
950     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
951         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
952     return true;
953   }
954 
955   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
956     S.Diag(Call->getArg(0)->getBeginLoc(),
957            diag::warn_opencl_generic_address_space_arg)
958         << Call->getDirectCallee()->getNameInfo().getAsString()
959         << Call->getArg(0)->getSourceRange();
960   }
961 
962   RT = RT->getPointeeType();
963   auto Qual = RT.getQualifiers();
964   switch (BuiltinID) {
965   case Builtin::BIto_global:
966     Qual.setAddressSpace(LangAS::opencl_global);
967     break;
968   case Builtin::BIto_local:
969     Qual.setAddressSpace(LangAS::opencl_local);
970     break;
971   case Builtin::BIto_private:
972     Qual.setAddressSpace(LangAS::opencl_private);
973     break;
974   default:
975     llvm_unreachable("Invalid builtin function");
976   }
977   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
978       RT.getUnqualifiedType(), Qual)));
979 
980   return false;
981 }
982 
983 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
984   if (checkArgCount(S, TheCall, 1))
985     return ExprError();
986 
987   // Compute __builtin_launder's parameter type from the argument.
988   // The parameter type is:
989   //  * The type of the argument if it's not an array or function type,
990   //  Otherwise,
991   //  * The decayed argument type.
992   QualType ParamTy = [&]() {
993     QualType ArgTy = TheCall->getArg(0)->getType();
994     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
995       return S.Context.getPointerType(Ty->getElementType());
996     if (ArgTy->isFunctionType()) {
997       return S.Context.getPointerType(ArgTy);
998     }
999     return ArgTy;
1000   }();
1001 
1002   TheCall->setType(ParamTy);
1003 
1004   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1005     if (!ParamTy->isPointerType())
1006       return 0;
1007     if (ParamTy->isFunctionPointerType())
1008       return 1;
1009     if (ParamTy->isVoidPointerType())
1010       return 2;
1011     return llvm::Optional<unsigned>{};
1012   }();
1013   if (DiagSelect.hasValue()) {
1014     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1015         << DiagSelect.getValue() << TheCall->getSourceRange();
1016     return ExprError();
1017   }
1018 
1019   // We either have an incomplete class type, or we have a class template
1020   // whose instantiation has not been forced. Example:
1021   //
1022   //   template <class T> struct Foo { T value; };
1023   //   Foo<int> *p = nullptr;
1024   //   auto *d = __builtin_launder(p);
1025   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1026                             diag::err_incomplete_type))
1027     return ExprError();
1028 
1029   assert(ParamTy->getPointeeType()->isObjectType() &&
1030          "Unhandled non-object pointer case");
1031 
1032   InitializedEntity Entity =
1033       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1034   ExprResult Arg =
1035       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1036   if (Arg.isInvalid())
1037     return ExprError();
1038   TheCall->setArg(0, Arg.get());
1039 
1040   return TheCall;
1041 }
1042 
1043 // Emit an error and return true if the current architecture is not in the list
1044 // of supported architectures.
1045 static bool
1046 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1047                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1048   llvm::Triple::ArchType CurArch =
1049       S.getASTContext().getTargetInfo().getTriple().getArch();
1050   if (llvm::is_contained(SupportedArchs, CurArch))
1051     return false;
1052   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1053       << TheCall->getSourceRange();
1054   return true;
1055 }
1056 
1057 ExprResult
1058 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1059                                CallExpr *TheCall) {
1060   ExprResult TheCallResult(TheCall);
1061 
1062   // Find out if any arguments are required to be integer constant expressions.
1063   unsigned ICEArguments = 0;
1064   ASTContext::GetBuiltinTypeError Error;
1065   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1066   if (Error != ASTContext::GE_None)
1067     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1068 
1069   // If any arguments are required to be ICE's, check and diagnose.
1070   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1071     // Skip arguments not required to be ICE's.
1072     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1073 
1074     llvm::APSInt Result;
1075     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1076       return true;
1077     ICEArguments &= ~(1 << ArgNo);
1078   }
1079 
1080   switch (BuiltinID) {
1081   case Builtin::BI__builtin___CFStringMakeConstantString:
1082     assert(TheCall->getNumArgs() == 1 &&
1083            "Wrong # arguments to builtin CFStringMakeConstantString");
1084     if (CheckObjCString(TheCall->getArg(0)))
1085       return ExprError();
1086     break;
1087   case Builtin::BI__builtin_ms_va_start:
1088   case Builtin::BI__builtin_stdarg_start:
1089   case Builtin::BI__builtin_va_start:
1090     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1091       return ExprError();
1092     break;
1093   case Builtin::BI__va_start: {
1094     switch (Context.getTargetInfo().getTriple().getArch()) {
1095     case llvm::Triple::aarch64:
1096     case llvm::Triple::arm:
1097     case llvm::Triple::thumb:
1098       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1099         return ExprError();
1100       break;
1101     default:
1102       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1103         return ExprError();
1104       break;
1105     }
1106     break;
1107   }
1108 
1109   // The acquire, release, and no fence variants are ARM and AArch64 only.
1110   case Builtin::BI_interlockedbittestandset_acq:
1111   case Builtin::BI_interlockedbittestandset_rel:
1112   case Builtin::BI_interlockedbittestandset_nf:
1113   case Builtin::BI_interlockedbittestandreset_acq:
1114   case Builtin::BI_interlockedbittestandreset_rel:
1115   case Builtin::BI_interlockedbittestandreset_nf:
1116     if (CheckBuiltinTargetSupport(
1117             *this, BuiltinID, TheCall,
1118             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1119       return ExprError();
1120     break;
1121 
1122   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1123   case Builtin::BI_bittest64:
1124   case Builtin::BI_bittestandcomplement64:
1125   case Builtin::BI_bittestandreset64:
1126   case Builtin::BI_bittestandset64:
1127   case Builtin::BI_interlockedbittestandreset64:
1128   case Builtin::BI_interlockedbittestandset64:
1129     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1130                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1131                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1132       return ExprError();
1133     break;
1134 
1135   case Builtin::BI__builtin_isgreater:
1136   case Builtin::BI__builtin_isgreaterequal:
1137   case Builtin::BI__builtin_isless:
1138   case Builtin::BI__builtin_islessequal:
1139   case Builtin::BI__builtin_islessgreater:
1140   case Builtin::BI__builtin_isunordered:
1141     if (SemaBuiltinUnorderedCompare(TheCall))
1142       return ExprError();
1143     break;
1144   case Builtin::BI__builtin_fpclassify:
1145     if (SemaBuiltinFPClassification(TheCall, 6))
1146       return ExprError();
1147     break;
1148   case Builtin::BI__builtin_isfinite:
1149   case Builtin::BI__builtin_isinf:
1150   case Builtin::BI__builtin_isinf_sign:
1151   case Builtin::BI__builtin_isnan:
1152   case Builtin::BI__builtin_isnormal:
1153   case Builtin::BI__builtin_signbit:
1154   case Builtin::BI__builtin_signbitf:
1155   case Builtin::BI__builtin_signbitl:
1156     if (SemaBuiltinFPClassification(TheCall, 1))
1157       return ExprError();
1158     break;
1159   case Builtin::BI__builtin_shufflevector:
1160     return SemaBuiltinShuffleVector(TheCall);
1161     // TheCall will be freed by the smart pointer here, but that's fine, since
1162     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1163   case Builtin::BI__builtin_prefetch:
1164     if (SemaBuiltinPrefetch(TheCall))
1165       return ExprError();
1166     break;
1167   case Builtin::BI__builtin_alloca_with_align:
1168     if (SemaBuiltinAllocaWithAlign(TheCall))
1169       return ExprError();
1170     break;
1171   case Builtin::BI__assume:
1172   case Builtin::BI__builtin_assume:
1173     if (SemaBuiltinAssume(TheCall))
1174       return ExprError();
1175     break;
1176   case Builtin::BI__builtin_assume_aligned:
1177     if (SemaBuiltinAssumeAligned(TheCall))
1178       return ExprError();
1179     break;
1180   case Builtin::BI__builtin_dynamic_object_size:
1181   case Builtin::BI__builtin_object_size:
1182     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1183       return ExprError();
1184     break;
1185   case Builtin::BI__builtin_longjmp:
1186     if (SemaBuiltinLongjmp(TheCall))
1187       return ExprError();
1188     break;
1189   case Builtin::BI__builtin_setjmp:
1190     if (SemaBuiltinSetjmp(TheCall))
1191       return ExprError();
1192     break;
1193   case Builtin::BI_setjmp:
1194   case Builtin::BI_setjmpex:
1195     if (checkArgCount(*this, TheCall, 1))
1196       return true;
1197     break;
1198   case Builtin::BI__builtin_classify_type:
1199     if (checkArgCount(*this, TheCall, 1)) return true;
1200     TheCall->setType(Context.IntTy);
1201     break;
1202   case Builtin::BI__builtin_constant_p: {
1203     if (checkArgCount(*this, TheCall, 1)) return true;
1204     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1205     if (Arg.isInvalid()) return true;
1206     TheCall->setArg(0, Arg.get());
1207     TheCall->setType(Context.IntTy);
1208     break;
1209   }
1210   case Builtin::BI__builtin_launder:
1211     return SemaBuiltinLaunder(*this, TheCall);
1212   case Builtin::BI__sync_fetch_and_add:
1213   case Builtin::BI__sync_fetch_and_add_1:
1214   case Builtin::BI__sync_fetch_and_add_2:
1215   case Builtin::BI__sync_fetch_and_add_4:
1216   case Builtin::BI__sync_fetch_and_add_8:
1217   case Builtin::BI__sync_fetch_and_add_16:
1218   case Builtin::BI__sync_fetch_and_sub:
1219   case Builtin::BI__sync_fetch_and_sub_1:
1220   case Builtin::BI__sync_fetch_and_sub_2:
1221   case Builtin::BI__sync_fetch_and_sub_4:
1222   case Builtin::BI__sync_fetch_and_sub_8:
1223   case Builtin::BI__sync_fetch_and_sub_16:
1224   case Builtin::BI__sync_fetch_and_or:
1225   case Builtin::BI__sync_fetch_and_or_1:
1226   case Builtin::BI__sync_fetch_and_or_2:
1227   case Builtin::BI__sync_fetch_and_or_4:
1228   case Builtin::BI__sync_fetch_and_or_8:
1229   case Builtin::BI__sync_fetch_and_or_16:
1230   case Builtin::BI__sync_fetch_and_and:
1231   case Builtin::BI__sync_fetch_and_and_1:
1232   case Builtin::BI__sync_fetch_and_and_2:
1233   case Builtin::BI__sync_fetch_and_and_4:
1234   case Builtin::BI__sync_fetch_and_and_8:
1235   case Builtin::BI__sync_fetch_and_and_16:
1236   case Builtin::BI__sync_fetch_and_xor:
1237   case Builtin::BI__sync_fetch_and_xor_1:
1238   case Builtin::BI__sync_fetch_and_xor_2:
1239   case Builtin::BI__sync_fetch_and_xor_4:
1240   case Builtin::BI__sync_fetch_and_xor_8:
1241   case Builtin::BI__sync_fetch_and_xor_16:
1242   case Builtin::BI__sync_fetch_and_nand:
1243   case Builtin::BI__sync_fetch_and_nand_1:
1244   case Builtin::BI__sync_fetch_and_nand_2:
1245   case Builtin::BI__sync_fetch_and_nand_4:
1246   case Builtin::BI__sync_fetch_and_nand_8:
1247   case Builtin::BI__sync_fetch_and_nand_16:
1248   case Builtin::BI__sync_add_and_fetch:
1249   case Builtin::BI__sync_add_and_fetch_1:
1250   case Builtin::BI__sync_add_and_fetch_2:
1251   case Builtin::BI__sync_add_and_fetch_4:
1252   case Builtin::BI__sync_add_and_fetch_8:
1253   case Builtin::BI__sync_add_and_fetch_16:
1254   case Builtin::BI__sync_sub_and_fetch:
1255   case Builtin::BI__sync_sub_and_fetch_1:
1256   case Builtin::BI__sync_sub_and_fetch_2:
1257   case Builtin::BI__sync_sub_and_fetch_4:
1258   case Builtin::BI__sync_sub_and_fetch_8:
1259   case Builtin::BI__sync_sub_and_fetch_16:
1260   case Builtin::BI__sync_and_and_fetch:
1261   case Builtin::BI__sync_and_and_fetch_1:
1262   case Builtin::BI__sync_and_and_fetch_2:
1263   case Builtin::BI__sync_and_and_fetch_4:
1264   case Builtin::BI__sync_and_and_fetch_8:
1265   case Builtin::BI__sync_and_and_fetch_16:
1266   case Builtin::BI__sync_or_and_fetch:
1267   case Builtin::BI__sync_or_and_fetch_1:
1268   case Builtin::BI__sync_or_and_fetch_2:
1269   case Builtin::BI__sync_or_and_fetch_4:
1270   case Builtin::BI__sync_or_and_fetch_8:
1271   case Builtin::BI__sync_or_and_fetch_16:
1272   case Builtin::BI__sync_xor_and_fetch:
1273   case Builtin::BI__sync_xor_and_fetch_1:
1274   case Builtin::BI__sync_xor_and_fetch_2:
1275   case Builtin::BI__sync_xor_and_fetch_4:
1276   case Builtin::BI__sync_xor_and_fetch_8:
1277   case Builtin::BI__sync_xor_and_fetch_16:
1278   case Builtin::BI__sync_nand_and_fetch:
1279   case Builtin::BI__sync_nand_and_fetch_1:
1280   case Builtin::BI__sync_nand_and_fetch_2:
1281   case Builtin::BI__sync_nand_and_fetch_4:
1282   case Builtin::BI__sync_nand_and_fetch_8:
1283   case Builtin::BI__sync_nand_and_fetch_16:
1284   case Builtin::BI__sync_val_compare_and_swap:
1285   case Builtin::BI__sync_val_compare_and_swap_1:
1286   case Builtin::BI__sync_val_compare_and_swap_2:
1287   case Builtin::BI__sync_val_compare_and_swap_4:
1288   case Builtin::BI__sync_val_compare_and_swap_8:
1289   case Builtin::BI__sync_val_compare_and_swap_16:
1290   case Builtin::BI__sync_bool_compare_and_swap:
1291   case Builtin::BI__sync_bool_compare_and_swap_1:
1292   case Builtin::BI__sync_bool_compare_and_swap_2:
1293   case Builtin::BI__sync_bool_compare_and_swap_4:
1294   case Builtin::BI__sync_bool_compare_and_swap_8:
1295   case Builtin::BI__sync_bool_compare_and_swap_16:
1296   case Builtin::BI__sync_lock_test_and_set:
1297   case Builtin::BI__sync_lock_test_and_set_1:
1298   case Builtin::BI__sync_lock_test_and_set_2:
1299   case Builtin::BI__sync_lock_test_and_set_4:
1300   case Builtin::BI__sync_lock_test_and_set_8:
1301   case Builtin::BI__sync_lock_test_and_set_16:
1302   case Builtin::BI__sync_lock_release:
1303   case Builtin::BI__sync_lock_release_1:
1304   case Builtin::BI__sync_lock_release_2:
1305   case Builtin::BI__sync_lock_release_4:
1306   case Builtin::BI__sync_lock_release_8:
1307   case Builtin::BI__sync_lock_release_16:
1308   case Builtin::BI__sync_swap:
1309   case Builtin::BI__sync_swap_1:
1310   case Builtin::BI__sync_swap_2:
1311   case Builtin::BI__sync_swap_4:
1312   case Builtin::BI__sync_swap_8:
1313   case Builtin::BI__sync_swap_16:
1314     return SemaBuiltinAtomicOverloaded(TheCallResult);
1315   case Builtin::BI__sync_synchronize:
1316     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1317         << TheCall->getCallee()->getSourceRange();
1318     break;
1319   case Builtin::BI__builtin_nontemporal_load:
1320   case Builtin::BI__builtin_nontemporal_store:
1321     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1322 #define BUILTIN(ID, TYPE, ATTRS)
1323 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1324   case Builtin::BI##ID: \
1325     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1326 #include "clang/Basic/Builtins.def"
1327   case Builtin::BI__annotation:
1328     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1329       return ExprError();
1330     break;
1331   case Builtin::BI__builtin_annotation:
1332     if (SemaBuiltinAnnotation(*this, TheCall))
1333       return ExprError();
1334     break;
1335   case Builtin::BI__builtin_addressof:
1336     if (SemaBuiltinAddressof(*this, TheCall))
1337       return ExprError();
1338     break;
1339   case Builtin::BI__builtin_add_overflow:
1340   case Builtin::BI__builtin_sub_overflow:
1341   case Builtin::BI__builtin_mul_overflow:
1342     if (SemaBuiltinOverflow(*this, TheCall))
1343       return ExprError();
1344     break;
1345   case Builtin::BI__builtin_operator_new:
1346   case Builtin::BI__builtin_operator_delete: {
1347     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1348     ExprResult Res =
1349         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1350     if (Res.isInvalid())
1351       CorrectDelayedTyposInExpr(TheCallResult.get());
1352     return Res;
1353   }
1354   case Builtin::BI__builtin_dump_struct: {
1355     // We first want to ensure we are called with 2 arguments
1356     if (checkArgCount(*this, TheCall, 2))
1357       return ExprError();
1358     // Ensure that the first argument is of type 'struct XX *'
1359     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1360     const QualType PtrArgType = PtrArg->getType();
1361     if (!PtrArgType->isPointerType() ||
1362         !PtrArgType->getPointeeType()->isRecordType()) {
1363       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1364           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1365           << "structure pointer";
1366       return ExprError();
1367     }
1368 
1369     // Ensure that the second argument is of type 'FunctionType'
1370     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1371     const QualType FnPtrArgType = FnPtrArg->getType();
1372     if (!FnPtrArgType->isPointerType()) {
1373       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1374           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1375           << FnPtrArgType << "'int (*)(const char *, ...)'";
1376       return ExprError();
1377     }
1378 
1379     const auto *FuncType =
1380         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1381 
1382     if (!FuncType) {
1383       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1384           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1385           << FnPtrArgType << "'int (*)(const char *, ...)'";
1386       return ExprError();
1387     }
1388 
1389     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1390       if (!FT->getNumParams()) {
1391         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1392             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1393             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1394         return ExprError();
1395       }
1396       QualType PT = FT->getParamType(0);
1397       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1398           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1399           !PT->getPointeeType().isConstQualified()) {
1400         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1401             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1402             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1403         return ExprError();
1404       }
1405     }
1406 
1407     TheCall->setType(Context.IntTy);
1408     break;
1409   }
1410   case Builtin::BI__builtin_call_with_static_chain:
1411     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1412       return ExprError();
1413     break;
1414   case Builtin::BI__exception_code:
1415   case Builtin::BI_exception_code:
1416     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1417                                  diag::err_seh___except_block))
1418       return ExprError();
1419     break;
1420   case Builtin::BI__exception_info:
1421   case Builtin::BI_exception_info:
1422     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1423                                  diag::err_seh___except_filter))
1424       return ExprError();
1425     break;
1426   case Builtin::BI__GetExceptionInfo:
1427     if (checkArgCount(*this, TheCall, 1))
1428       return ExprError();
1429 
1430     if (CheckCXXThrowOperand(
1431             TheCall->getBeginLoc(),
1432             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1433             TheCall))
1434       return ExprError();
1435 
1436     TheCall->setType(Context.VoidPtrTy);
1437     break;
1438   // OpenCL v2.0, s6.13.16 - Pipe functions
1439   case Builtin::BIread_pipe:
1440   case Builtin::BIwrite_pipe:
1441     // Since those two functions are declared with var args, we need a semantic
1442     // check for the argument.
1443     if (SemaBuiltinRWPipe(*this, TheCall))
1444       return ExprError();
1445     break;
1446   case Builtin::BIreserve_read_pipe:
1447   case Builtin::BIreserve_write_pipe:
1448   case Builtin::BIwork_group_reserve_read_pipe:
1449   case Builtin::BIwork_group_reserve_write_pipe:
1450     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1451       return ExprError();
1452     break;
1453   case Builtin::BIsub_group_reserve_read_pipe:
1454   case Builtin::BIsub_group_reserve_write_pipe:
1455     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1456         SemaBuiltinReserveRWPipe(*this, TheCall))
1457       return ExprError();
1458     break;
1459   case Builtin::BIcommit_read_pipe:
1460   case Builtin::BIcommit_write_pipe:
1461   case Builtin::BIwork_group_commit_read_pipe:
1462   case Builtin::BIwork_group_commit_write_pipe:
1463     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1464       return ExprError();
1465     break;
1466   case Builtin::BIsub_group_commit_read_pipe:
1467   case Builtin::BIsub_group_commit_write_pipe:
1468     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1469         SemaBuiltinCommitRWPipe(*this, TheCall))
1470       return ExprError();
1471     break;
1472   case Builtin::BIget_pipe_num_packets:
1473   case Builtin::BIget_pipe_max_packets:
1474     if (SemaBuiltinPipePackets(*this, TheCall))
1475       return ExprError();
1476     break;
1477   case Builtin::BIto_global:
1478   case Builtin::BIto_local:
1479   case Builtin::BIto_private:
1480     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1481       return ExprError();
1482     break;
1483   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1484   case Builtin::BIenqueue_kernel:
1485     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1486       return ExprError();
1487     break;
1488   case Builtin::BIget_kernel_work_group_size:
1489   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1490     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1491       return ExprError();
1492     break;
1493   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1494   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1495     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1496       return ExprError();
1497     break;
1498   case Builtin::BI__builtin_os_log_format:
1499   case Builtin::BI__builtin_os_log_format_buffer_size:
1500     if (SemaBuiltinOSLogFormat(TheCall))
1501       return ExprError();
1502     break;
1503   }
1504 
1505   // Since the target specific builtins for each arch overlap, only check those
1506   // of the arch we are compiling for.
1507   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1508     switch (Context.getTargetInfo().getTriple().getArch()) {
1509       case llvm::Triple::arm:
1510       case llvm::Triple::armeb:
1511       case llvm::Triple::thumb:
1512       case llvm::Triple::thumbeb:
1513         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1514           return ExprError();
1515         break;
1516       case llvm::Triple::aarch64:
1517       case llvm::Triple::aarch64_be:
1518         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1519           return ExprError();
1520         break;
1521       case llvm::Triple::hexagon:
1522         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1523           return ExprError();
1524         break;
1525       case llvm::Triple::mips:
1526       case llvm::Triple::mipsel:
1527       case llvm::Triple::mips64:
1528       case llvm::Triple::mips64el:
1529         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1530           return ExprError();
1531         break;
1532       case llvm::Triple::systemz:
1533         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1534           return ExprError();
1535         break;
1536       case llvm::Triple::x86:
1537       case llvm::Triple::x86_64:
1538         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1539           return ExprError();
1540         break;
1541       case llvm::Triple::ppc:
1542       case llvm::Triple::ppc64:
1543       case llvm::Triple::ppc64le:
1544         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1545           return ExprError();
1546         break;
1547       default:
1548         break;
1549     }
1550   }
1551 
1552   return TheCallResult;
1553 }
1554 
1555 // Get the valid immediate range for the specified NEON type code.
1556 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1557   NeonTypeFlags Type(t);
1558   int IsQuad = ForceQuad ? true : Type.isQuad();
1559   switch (Type.getEltType()) {
1560   case NeonTypeFlags::Int8:
1561   case NeonTypeFlags::Poly8:
1562     return shift ? 7 : (8 << IsQuad) - 1;
1563   case NeonTypeFlags::Int16:
1564   case NeonTypeFlags::Poly16:
1565     return shift ? 15 : (4 << IsQuad) - 1;
1566   case NeonTypeFlags::Int32:
1567     return shift ? 31 : (2 << IsQuad) - 1;
1568   case NeonTypeFlags::Int64:
1569   case NeonTypeFlags::Poly64:
1570     return shift ? 63 : (1 << IsQuad) - 1;
1571   case NeonTypeFlags::Poly128:
1572     return shift ? 127 : (1 << IsQuad) - 1;
1573   case NeonTypeFlags::Float16:
1574     assert(!shift && "cannot shift float types!");
1575     return (4 << IsQuad) - 1;
1576   case NeonTypeFlags::Float32:
1577     assert(!shift && "cannot shift float types!");
1578     return (2 << IsQuad) - 1;
1579   case NeonTypeFlags::Float64:
1580     assert(!shift && "cannot shift float types!");
1581     return (1 << IsQuad) - 1;
1582   }
1583   llvm_unreachable("Invalid NeonTypeFlag!");
1584 }
1585 
1586 /// getNeonEltType - Return the QualType corresponding to the elements of
1587 /// the vector type specified by the NeonTypeFlags.  This is used to check
1588 /// the pointer arguments for Neon load/store intrinsics.
1589 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1590                                bool IsPolyUnsigned, bool IsInt64Long) {
1591   switch (Flags.getEltType()) {
1592   case NeonTypeFlags::Int8:
1593     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1594   case NeonTypeFlags::Int16:
1595     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1596   case NeonTypeFlags::Int32:
1597     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1598   case NeonTypeFlags::Int64:
1599     if (IsInt64Long)
1600       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1601     else
1602       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1603                                 : Context.LongLongTy;
1604   case NeonTypeFlags::Poly8:
1605     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1606   case NeonTypeFlags::Poly16:
1607     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1608   case NeonTypeFlags::Poly64:
1609     if (IsInt64Long)
1610       return Context.UnsignedLongTy;
1611     else
1612       return Context.UnsignedLongLongTy;
1613   case NeonTypeFlags::Poly128:
1614     break;
1615   case NeonTypeFlags::Float16:
1616     return Context.HalfTy;
1617   case NeonTypeFlags::Float32:
1618     return Context.FloatTy;
1619   case NeonTypeFlags::Float64:
1620     return Context.DoubleTy;
1621   }
1622   llvm_unreachable("Invalid NeonTypeFlag!");
1623 }
1624 
1625 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1626   llvm::APSInt Result;
1627   uint64_t mask = 0;
1628   unsigned TV = 0;
1629   int PtrArgNum = -1;
1630   bool HasConstPtr = false;
1631   switch (BuiltinID) {
1632 #define GET_NEON_OVERLOAD_CHECK
1633 #include "clang/Basic/arm_neon.inc"
1634 #include "clang/Basic/arm_fp16.inc"
1635 #undef GET_NEON_OVERLOAD_CHECK
1636   }
1637 
1638   // For NEON intrinsics which are overloaded on vector element type, validate
1639   // the immediate which specifies which variant to emit.
1640   unsigned ImmArg = TheCall->getNumArgs()-1;
1641   if (mask) {
1642     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1643       return true;
1644 
1645     TV = Result.getLimitedValue(64);
1646     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1647       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1648              << TheCall->getArg(ImmArg)->getSourceRange();
1649   }
1650 
1651   if (PtrArgNum >= 0) {
1652     // Check that pointer arguments have the specified type.
1653     Expr *Arg = TheCall->getArg(PtrArgNum);
1654     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1655       Arg = ICE->getSubExpr();
1656     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1657     QualType RHSTy = RHS.get()->getType();
1658 
1659     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1660     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1661                           Arch == llvm::Triple::aarch64_be;
1662     bool IsInt64Long =
1663         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1664     QualType EltTy =
1665         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1666     if (HasConstPtr)
1667       EltTy = EltTy.withConst();
1668     QualType LHSTy = Context.getPointerType(EltTy);
1669     AssignConvertType ConvTy;
1670     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1671     if (RHS.isInvalid())
1672       return true;
1673     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1674                                  RHS.get(), AA_Assigning))
1675       return true;
1676   }
1677 
1678   // For NEON intrinsics which take an immediate value as part of the
1679   // instruction, range check them here.
1680   unsigned i = 0, l = 0, u = 0;
1681   switch (BuiltinID) {
1682   default:
1683     return false;
1684   #define GET_NEON_IMMEDIATE_CHECK
1685   #include "clang/Basic/arm_neon.inc"
1686   #include "clang/Basic/arm_fp16.inc"
1687   #undef GET_NEON_IMMEDIATE_CHECK
1688   }
1689 
1690   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1691 }
1692 
1693 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1694                                         unsigned MaxWidth) {
1695   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1696           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1697           BuiltinID == ARM::BI__builtin_arm_strex ||
1698           BuiltinID == ARM::BI__builtin_arm_stlex ||
1699           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1700           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1701           BuiltinID == AArch64::BI__builtin_arm_strex ||
1702           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1703          "unexpected ARM builtin");
1704   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1705                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1706                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1707                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1708 
1709   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1710 
1711   // Ensure that we have the proper number of arguments.
1712   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1713     return true;
1714 
1715   // Inspect the pointer argument of the atomic builtin.  This should always be
1716   // a pointer type, whose element is an integral scalar or pointer type.
1717   // Because it is a pointer type, we don't have to worry about any implicit
1718   // casts here.
1719   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1720   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1721   if (PointerArgRes.isInvalid())
1722     return true;
1723   PointerArg = PointerArgRes.get();
1724 
1725   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1726   if (!pointerType) {
1727     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1728         << PointerArg->getType() << PointerArg->getSourceRange();
1729     return true;
1730   }
1731 
1732   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1733   // task is to insert the appropriate casts into the AST. First work out just
1734   // what the appropriate type is.
1735   QualType ValType = pointerType->getPointeeType();
1736   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1737   if (IsLdrex)
1738     AddrType.addConst();
1739 
1740   // Issue a warning if the cast is dodgy.
1741   CastKind CastNeeded = CK_NoOp;
1742   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1743     CastNeeded = CK_BitCast;
1744     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1745         << PointerArg->getType() << Context.getPointerType(AddrType)
1746         << AA_Passing << PointerArg->getSourceRange();
1747   }
1748 
1749   // Finally, do the cast and replace the argument with the corrected version.
1750   AddrType = Context.getPointerType(AddrType);
1751   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1752   if (PointerArgRes.isInvalid())
1753     return true;
1754   PointerArg = PointerArgRes.get();
1755 
1756   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1757 
1758   // In general, we allow ints, floats and pointers to be loaded and stored.
1759   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1760       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1761     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1762         << PointerArg->getType() << PointerArg->getSourceRange();
1763     return true;
1764   }
1765 
1766   // But ARM doesn't have instructions to deal with 128-bit versions.
1767   if (Context.getTypeSize(ValType) > MaxWidth) {
1768     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1769     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1770         << PointerArg->getType() << PointerArg->getSourceRange();
1771     return true;
1772   }
1773 
1774   switch (ValType.getObjCLifetime()) {
1775   case Qualifiers::OCL_None:
1776   case Qualifiers::OCL_ExplicitNone:
1777     // okay
1778     break;
1779 
1780   case Qualifiers::OCL_Weak:
1781   case Qualifiers::OCL_Strong:
1782   case Qualifiers::OCL_Autoreleasing:
1783     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1784         << ValType << PointerArg->getSourceRange();
1785     return true;
1786   }
1787 
1788   if (IsLdrex) {
1789     TheCall->setType(ValType);
1790     return false;
1791   }
1792 
1793   // Initialize the argument to be stored.
1794   ExprResult ValArg = TheCall->getArg(0);
1795   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1796       Context, ValType, /*consume*/ false);
1797   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1798   if (ValArg.isInvalid())
1799     return true;
1800   TheCall->setArg(0, ValArg.get());
1801 
1802   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1803   // but the custom checker bypasses all default analysis.
1804   TheCall->setType(Context.IntTy);
1805   return false;
1806 }
1807 
1808 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1809   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1810       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1811       BuiltinID == ARM::BI__builtin_arm_strex ||
1812       BuiltinID == ARM::BI__builtin_arm_stlex) {
1813     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1814   }
1815 
1816   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1817     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1818       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1819   }
1820 
1821   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1822       BuiltinID == ARM::BI__builtin_arm_wsr64)
1823     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1824 
1825   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1826       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1827       BuiltinID == ARM::BI__builtin_arm_wsr ||
1828       BuiltinID == ARM::BI__builtin_arm_wsrp)
1829     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1830 
1831   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1832     return true;
1833 
1834   // For intrinsics which take an immediate value as part of the instruction,
1835   // range check them here.
1836   // FIXME: VFP Intrinsics should error if VFP not present.
1837   switch (BuiltinID) {
1838   default: return false;
1839   case ARM::BI__builtin_arm_ssat:
1840     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1841   case ARM::BI__builtin_arm_usat:
1842     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1843   case ARM::BI__builtin_arm_ssat16:
1844     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1845   case ARM::BI__builtin_arm_usat16:
1846     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1847   case ARM::BI__builtin_arm_vcvtr_f:
1848   case ARM::BI__builtin_arm_vcvtr_d:
1849     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1850   case ARM::BI__builtin_arm_dmb:
1851   case ARM::BI__builtin_arm_dsb:
1852   case ARM::BI__builtin_arm_isb:
1853   case ARM::BI__builtin_arm_dbg:
1854     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1855   }
1856 }
1857 
1858 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1859                                          CallExpr *TheCall) {
1860   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1861       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1862       BuiltinID == AArch64::BI__builtin_arm_strex ||
1863       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1864     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1865   }
1866 
1867   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1868     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1869       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1870       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1871       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1872   }
1873 
1874   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1875       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1876     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1877 
1878   // Memory Tagging Extensions (MTE) Intrinsics
1879   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
1880       BuiltinID == AArch64::BI__builtin_arm_addg ||
1881       BuiltinID == AArch64::BI__builtin_arm_gmi ||
1882       BuiltinID == AArch64::BI__builtin_arm_ldg ||
1883       BuiltinID == AArch64::BI__builtin_arm_stg ||
1884       BuiltinID == AArch64::BI__builtin_arm_subp) {
1885     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
1886   }
1887 
1888   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1889       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1890       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1891       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1892     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1893 
1894   // Only check the valid encoding range. Any constant in this range would be
1895   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1896   // an exception for incorrect registers. This matches MSVC behavior.
1897   if (BuiltinID == AArch64::BI_ReadStatusReg ||
1898       BuiltinID == AArch64::BI_WriteStatusReg)
1899     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1900 
1901   if (BuiltinID == AArch64::BI__getReg)
1902     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1903 
1904   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1905     return true;
1906 
1907   // For intrinsics which take an immediate value as part of the instruction,
1908   // range check them here.
1909   unsigned i = 0, l = 0, u = 0;
1910   switch (BuiltinID) {
1911   default: return false;
1912   case AArch64::BI__builtin_arm_dmb:
1913   case AArch64::BI__builtin_arm_dsb:
1914   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1915   }
1916 
1917   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1918 }
1919 
1920 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1921   struct BuiltinAndString {
1922     unsigned BuiltinID;
1923     const char *Str;
1924   };
1925 
1926   static BuiltinAndString ValidCPU[] = {
1927     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1928     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1929     { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1930     { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1931     { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1932     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1933     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1934     { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1935     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1936     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1937     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
1938     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
1939     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
1940     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
1941     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
1942     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
1943     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
1944     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
1945     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
1946     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
1947     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
1948     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
1949     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
1950   };
1951 
1952   static BuiltinAndString ValidHVX[] = {
1953     { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
1954     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
1955     { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
1956     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
1957     { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
1958     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
1959     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
1960     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
1961     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
1962     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
1963     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
1964     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
1965     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
1966     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
1967     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
1968     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
1969     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
1970     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
1971     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
1972     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
1973     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
1974     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
1975     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
1976     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
1977     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
1978     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
1979     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
1980     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
1981     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
1982     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
1983     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
1984     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
1985     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
1986     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
1987     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
1988     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
1989     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
1990     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
1991     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
1992     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
1993     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
1994     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
1995     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
1996     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
1997     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
1998     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
1999     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
2000     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
2001     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
2002     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
2003     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
2004     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
2005     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
2006     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
2007     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
2008     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
2009     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
2010     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
2011     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
2012     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
2013     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2014     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2015     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2016     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2017     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2018     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2019     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2020     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2021     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2022     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2023     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2024     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2025     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2026     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2027     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2028     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2029     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2030     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2031     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2032     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2033     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2034     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2035     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2036     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2037     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2038     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2039     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2040     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2041     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2042     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2043     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2044     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2045     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2046     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2047     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2048     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2049     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2050     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2051     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2052     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2053     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2054     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2055     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2056     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2057     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2058     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2063     { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2064     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2065     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2066     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2075     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2076     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2077     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2078     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2079     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2080     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2081     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2082     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2083     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2084     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2085     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2086     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2087     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2088     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2089     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2125     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2126     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2127     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2128     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2137     { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2138     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2139     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2140     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2146     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2147     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2148     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2149     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2150     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2151     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2152     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2153     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2154     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2155     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2156     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2157     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2158     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2159     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2160     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2161     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2162     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2163     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2164     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2165     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2166     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2167     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2168     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2169     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2211     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2212     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2213     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2214     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2215     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2216     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2217     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2218     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2219     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2220     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2221     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2222     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2223     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2224     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2225     { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2226     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2227     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2228     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2229     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2230     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2231     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2232     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2233     { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2234     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2235     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2236     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2237     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2238     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2239     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2240     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2241     { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2242     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2243     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2244     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2245     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2246     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2247     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2248     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2249     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2250     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2251     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2252     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2253     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2254     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2255     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2256     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2257     { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2258     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2259     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2260     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2261     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2262     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2287     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2288     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2289     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2290     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2291     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2292     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2293     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2294     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2295     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2296     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2297     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2298     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2299     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2300     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2301     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2302     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2303     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2304     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2305     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2306     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2307     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2308     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2309     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2310     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2311     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2312     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2313     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2314     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2315     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2316     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2317     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2318     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2319     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2320     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2321     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2322     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2515     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2516     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2517     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2518     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2519     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2520     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2521     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2522     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2523     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2524     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2525     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2526     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2527     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2528     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2529     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2530     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2531     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2532     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2533     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2534     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2535     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2536     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2537     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2538     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2539     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2540     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2541     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2542     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2543     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2544     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2545     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2546     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2547     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2548     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2549     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2550     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2551     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2552     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2553     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2554     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2555     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2556     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2557     { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2558     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2559     { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2560     { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2561     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2562     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2563     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2564     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2565     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2566     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2567     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2568     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2569     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2570     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2571     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2572     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2573     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2574     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2575     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2576     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2577     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2578     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2579     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2580     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2581     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2582     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2583     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2584     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2585     { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2586     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2587     { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2588     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2589     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2590     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2591     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2592     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2593     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2594     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2595     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2596     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2597     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2598     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2599     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2600     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2601     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2602     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2603     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2604     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2605     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2606     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2607     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2608     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2609     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2610     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2611     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2612     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2613     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2614     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2615     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2616     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2617     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2618     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2619     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2620     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2621     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2622     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2623     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2624     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2625     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2626     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2627     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2628     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2629     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2630     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2631     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2632     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2633     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2634     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2635     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2636     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2637     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2638     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2639     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2640     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2641     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2642     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2643     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2644     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2645     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2646     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2647     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2648     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2649     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2650     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2651     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2652     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2653     { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2654     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2655     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2656     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2657     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2658     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2659     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2660     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2661     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2662     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2663     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2664     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2665     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2666     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2667     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2668     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2669     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2670     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2671     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2672     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2673     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2674     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2675     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2676     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2677     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2678     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2679     { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2680     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2681     { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2682     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2683     { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2684     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2685   };
2686 
2687   // Sort the tables on first execution so we can binary search them.
2688   auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2689     return LHS.BuiltinID < RHS.BuiltinID;
2690   };
2691   static const bool SortOnce =
2692       (llvm::sort(ValidCPU, SortCmp),
2693        llvm::sort(ValidHVX, SortCmp), true);
2694   (void)SortOnce;
2695   auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2696     return BI.BuiltinID < BuiltinID;
2697   };
2698 
2699   const TargetInfo &TI = Context.getTargetInfo();
2700 
2701   const BuiltinAndString *FC =
2702       std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
2703                        LowerBoundCmp);
2704   if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2705     const TargetOptions &Opts = TI.getTargetOpts();
2706     StringRef CPU = Opts.CPU;
2707     if (!CPU.empty()) {
2708       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2709       CPU.consume_front("hexagon");
2710       SmallVector<StringRef, 3> CPUs;
2711       StringRef(FC->Str).split(CPUs, ',');
2712       if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2713         return Diag(TheCall->getBeginLoc(),
2714                     diag::err_hexagon_builtin_unsupported_cpu);
2715     }
2716   }
2717 
2718   const BuiltinAndString *FH =
2719       std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
2720                        LowerBoundCmp);
2721   if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2722     if (!TI.hasFeature("hvx"))
2723       return Diag(TheCall->getBeginLoc(),
2724                   diag::err_hexagon_builtin_requires_hvx);
2725 
2726     SmallVector<StringRef, 3> HVXs;
2727     StringRef(FH->Str).split(HVXs, ',');
2728     bool IsValid = llvm::any_of(HVXs,
2729                                 [&TI] (StringRef V) {
2730                                   std::string F = "hvx" + V.str();
2731                                   return TI.hasFeature(F);
2732                                 });
2733     if (!IsValid)
2734       return Diag(TheCall->getBeginLoc(),
2735                   diag::err_hexagon_builtin_unsupported_hvx);
2736   }
2737 
2738   return false;
2739 }
2740 
2741 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2742   struct ArgInfo {
2743     uint8_t OpNum;
2744     bool IsSigned;
2745     uint8_t BitWidth;
2746     uint8_t Align;
2747   };
2748   struct BuiltinInfo {
2749     unsigned BuiltinID;
2750     ArgInfo Infos[2];
2751   };
2752 
2753   static BuiltinInfo Infos[] = {
2754     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2755     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2756     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2757     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2758     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2759     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2760     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2761     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2762     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2763     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2764     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2765 
2766     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2769     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2770     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2771     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2772     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2774     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2775     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2776     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2777 
2778     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2808     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2830                                                       {{ 1, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2838                                                       {{ 1, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2845                                                        { 2, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2847                                                        { 2, false, 6,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2849                                                        { 3, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2851                                                        { 3, false, 6,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2868                                                       {{ 2, false, 4,  0 },
2869                                                        { 3, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2871                                                       {{ 2, false, 4,  0 },
2872                                                        { 3, false, 5,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2874                                                       {{ 2, false, 4,  0 },
2875                                                        { 3, false, 5,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2877                                                       {{ 2, false, 4,  0 },
2878                                                        { 3, false, 5,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2890                                                        { 2, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2892                                                        { 2, false, 6,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2902                                                       {{ 1, false, 4,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2905                                                       {{ 1, false, 4,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2926                                                       {{ 3, false, 1,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2931                                                       {{ 3, false, 1,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2936                                                       {{ 3, false, 1,  0 }} },
2937   };
2938 
2939   // Use a dynamically initialized static to sort the table exactly once on
2940   // first run.
2941   static const bool SortOnce =
2942       (llvm::sort(Infos,
2943                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2944                    return LHS.BuiltinID < RHS.BuiltinID;
2945                  }),
2946        true);
2947   (void)SortOnce;
2948 
2949   const BuiltinInfo *F =
2950       std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
2951                        [](const BuiltinInfo &BI, unsigned BuiltinID) {
2952                          return BI.BuiltinID < BuiltinID;
2953                        });
2954   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2955     return false;
2956 
2957   bool Error = false;
2958 
2959   for (const ArgInfo &A : F->Infos) {
2960     // Ignore empty ArgInfo elements.
2961     if (A.BitWidth == 0)
2962       continue;
2963 
2964     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2965     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2966     if (!A.Align) {
2967       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2968     } else {
2969       unsigned M = 1 << A.Align;
2970       Min *= M;
2971       Max *= M;
2972       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2973                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2974     }
2975   }
2976   return Error;
2977 }
2978 
2979 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2980                                            CallExpr *TheCall) {
2981   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2982          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2983 }
2984 
2985 
2986 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
2987 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2988 // ordering for DSP is unspecified. MSA is ordered by the data format used
2989 // by the underlying instruction i.e., df/m, df/n and then by size.
2990 //
2991 // FIXME: The size tests here should instead be tablegen'd along with the
2992 //        definitions from include/clang/Basic/BuiltinsMips.def.
2993 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2994 //        be too.
2995 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2996   unsigned i = 0, l = 0, u = 0, m = 0;
2997   switch (BuiltinID) {
2998   default: return false;
2999   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3000   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3001   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3002   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3003   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3004   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3005   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3006   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3007   // df/m field.
3008   // These intrinsics take an unsigned 3 bit immediate.
3009   case Mips::BI__builtin_msa_bclri_b:
3010   case Mips::BI__builtin_msa_bnegi_b:
3011   case Mips::BI__builtin_msa_bseti_b:
3012   case Mips::BI__builtin_msa_sat_s_b:
3013   case Mips::BI__builtin_msa_sat_u_b:
3014   case Mips::BI__builtin_msa_slli_b:
3015   case Mips::BI__builtin_msa_srai_b:
3016   case Mips::BI__builtin_msa_srari_b:
3017   case Mips::BI__builtin_msa_srli_b:
3018   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3019   case Mips::BI__builtin_msa_binsli_b:
3020   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3021   // These intrinsics take an unsigned 4 bit immediate.
3022   case Mips::BI__builtin_msa_bclri_h:
3023   case Mips::BI__builtin_msa_bnegi_h:
3024   case Mips::BI__builtin_msa_bseti_h:
3025   case Mips::BI__builtin_msa_sat_s_h:
3026   case Mips::BI__builtin_msa_sat_u_h:
3027   case Mips::BI__builtin_msa_slli_h:
3028   case Mips::BI__builtin_msa_srai_h:
3029   case Mips::BI__builtin_msa_srari_h:
3030   case Mips::BI__builtin_msa_srli_h:
3031   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3032   case Mips::BI__builtin_msa_binsli_h:
3033   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3034   // These intrinsics take an unsigned 5 bit immediate.
3035   // The first block of intrinsics actually have an unsigned 5 bit field,
3036   // not a df/n field.
3037   case Mips::BI__builtin_msa_clei_u_b:
3038   case Mips::BI__builtin_msa_clei_u_h:
3039   case Mips::BI__builtin_msa_clei_u_w:
3040   case Mips::BI__builtin_msa_clei_u_d:
3041   case Mips::BI__builtin_msa_clti_u_b:
3042   case Mips::BI__builtin_msa_clti_u_h:
3043   case Mips::BI__builtin_msa_clti_u_w:
3044   case Mips::BI__builtin_msa_clti_u_d:
3045   case Mips::BI__builtin_msa_maxi_u_b:
3046   case Mips::BI__builtin_msa_maxi_u_h:
3047   case Mips::BI__builtin_msa_maxi_u_w:
3048   case Mips::BI__builtin_msa_maxi_u_d:
3049   case Mips::BI__builtin_msa_mini_u_b:
3050   case Mips::BI__builtin_msa_mini_u_h:
3051   case Mips::BI__builtin_msa_mini_u_w:
3052   case Mips::BI__builtin_msa_mini_u_d:
3053   case Mips::BI__builtin_msa_addvi_b:
3054   case Mips::BI__builtin_msa_addvi_h:
3055   case Mips::BI__builtin_msa_addvi_w:
3056   case Mips::BI__builtin_msa_addvi_d:
3057   case Mips::BI__builtin_msa_bclri_w:
3058   case Mips::BI__builtin_msa_bnegi_w:
3059   case Mips::BI__builtin_msa_bseti_w:
3060   case Mips::BI__builtin_msa_sat_s_w:
3061   case Mips::BI__builtin_msa_sat_u_w:
3062   case Mips::BI__builtin_msa_slli_w:
3063   case Mips::BI__builtin_msa_srai_w:
3064   case Mips::BI__builtin_msa_srari_w:
3065   case Mips::BI__builtin_msa_srli_w:
3066   case Mips::BI__builtin_msa_srlri_w:
3067   case Mips::BI__builtin_msa_subvi_b:
3068   case Mips::BI__builtin_msa_subvi_h:
3069   case Mips::BI__builtin_msa_subvi_w:
3070   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3071   case Mips::BI__builtin_msa_binsli_w:
3072   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3073   // These intrinsics take an unsigned 6 bit immediate.
3074   case Mips::BI__builtin_msa_bclri_d:
3075   case Mips::BI__builtin_msa_bnegi_d:
3076   case Mips::BI__builtin_msa_bseti_d:
3077   case Mips::BI__builtin_msa_sat_s_d:
3078   case Mips::BI__builtin_msa_sat_u_d:
3079   case Mips::BI__builtin_msa_slli_d:
3080   case Mips::BI__builtin_msa_srai_d:
3081   case Mips::BI__builtin_msa_srari_d:
3082   case Mips::BI__builtin_msa_srli_d:
3083   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3084   case Mips::BI__builtin_msa_binsli_d:
3085   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3086   // These intrinsics take a signed 5 bit immediate.
3087   case Mips::BI__builtin_msa_ceqi_b:
3088   case Mips::BI__builtin_msa_ceqi_h:
3089   case Mips::BI__builtin_msa_ceqi_w:
3090   case Mips::BI__builtin_msa_ceqi_d:
3091   case Mips::BI__builtin_msa_clti_s_b:
3092   case Mips::BI__builtin_msa_clti_s_h:
3093   case Mips::BI__builtin_msa_clti_s_w:
3094   case Mips::BI__builtin_msa_clti_s_d:
3095   case Mips::BI__builtin_msa_clei_s_b:
3096   case Mips::BI__builtin_msa_clei_s_h:
3097   case Mips::BI__builtin_msa_clei_s_w:
3098   case Mips::BI__builtin_msa_clei_s_d:
3099   case Mips::BI__builtin_msa_maxi_s_b:
3100   case Mips::BI__builtin_msa_maxi_s_h:
3101   case Mips::BI__builtin_msa_maxi_s_w:
3102   case Mips::BI__builtin_msa_maxi_s_d:
3103   case Mips::BI__builtin_msa_mini_s_b:
3104   case Mips::BI__builtin_msa_mini_s_h:
3105   case Mips::BI__builtin_msa_mini_s_w:
3106   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3107   // These intrinsics take an unsigned 8 bit immediate.
3108   case Mips::BI__builtin_msa_andi_b:
3109   case Mips::BI__builtin_msa_nori_b:
3110   case Mips::BI__builtin_msa_ori_b:
3111   case Mips::BI__builtin_msa_shf_b:
3112   case Mips::BI__builtin_msa_shf_h:
3113   case Mips::BI__builtin_msa_shf_w:
3114   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3115   case Mips::BI__builtin_msa_bseli_b:
3116   case Mips::BI__builtin_msa_bmnzi_b:
3117   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3118   // df/n format
3119   // These intrinsics take an unsigned 4 bit immediate.
3120   case Mips::BI__builtin_msa_copy_s_b:
3121   case Mips::BI__builtin_msa_copy_u_b:
3122   case Mips::BI__builtin_msa_insve_b:
3123   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3124   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3125   // These intrinsics take an unsigned 3 bit immediate.
3126   case Mips::BI__builtin_msa_copy_s_h:
3127   case Mips::BI__builtin_msa_copy_u_h:
3128   case Mips::BI__builtin_msa_insve_h:
3129   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3130   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3131   // These intrinsics take an unsigned 2 bit immediate.
3132   case Mips::BI__builtin_msa_copy_s_w:
3133   case Mips::BI__builtin_msa_copy_u_w:
3134   case Mips::BI__builtin_msa_insve_w:
3135   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3136   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3137   // These intrinsics take an unsigned 1 bit immediate.
3138   case Mips::BI__builtin_msa_copy_s_d:
3139   case Mips::BI__builtin_msa_copy_u_d:
3140   case Mips::BI__builtin_msa_insve_d:
3141   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3142   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3143   // Memory offsets and immediate loads.
3144   // These intrinsics take a signed 10 bit immediate.
3145   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3146   case Mips::BI__builtin_msa_ldi_h:
3147   case Mips::BI__builtin_msa_ldi_w:
3148   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3149   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3150   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3151   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3152   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3153   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3154   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3155   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3156   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3157   }
3158 
3159   if (!m)
3160     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3161 
3162   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3163          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3164 }
3165 
3166 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3167   unsigned i = 0, l = 0, u = 0;
3168   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3169                       BuiltinID == PPC::BI__builtin_divdeu ||
3170                       BuiltinID == PPC::BI__builtin_bpermd;
3171   bool IsTarget64Bit = Context.getTargetInfo()
3172                               .getTypeWidth(Context
3173                                             .getTargetInfo()
3174                                             .getIntPtrType()) == 64;
3175   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3176                        BuiltinID == PPC::BI__builtin_divweu ||
3177                        BuiltinID == PPC::BI__builtin_divde ||
3178                        BuiltinID == PPC::BI__builtin_divdeu;
3179 
3180   if (Is64BitBltin && !IsTarget64Bit)
3181     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3182            << TheCall->getSourceRange();
3183 
3184   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3185       (BuiltinID == PPC::BI__builtin_bpermd &&
3186        !Context.getTargetInfo().hasFeature("bpermd")))
3187     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3188            << TheCall->getSourceRange();
3189 
3190   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3191     if (!Context.getTargetInfo().hasFeature("vsx"))
3192       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3193              << TheCall->getSourceRange();
3194     return false;
3195   };
3196 
3197   switch (BuiltinID) {
3198   default: return false;
3199   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3200   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3201     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3202            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3203   case PPC::BI__builtin_tbegin:
3204   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3205   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3206   case PPC::BI__builtin_tabortwc:
3207   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3208   case PPC::BI__builtin_tabortwci:
3209   case PPC::BI__builtin_tabortdci:
3210     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3211            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3212   case PPC::BI__builtin_vsx_xxpermdi:
3213   case PPC::BI__builtin_vsx_xxsldwi:
3214     return SemaBuiltinVSX(TheCall);
3215   case PPC::BI__builtin_unpack_vector_int128:
3216     return SemaVSXCheck(TheCall) ||
3217            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3218   case PPC::BI__builtin_pack_vector_int128:
3219     return SemaVSXCheck(TheCall);
3220   }
3221   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3222 }
3223 
3224 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3225                                            CallExpr *TheCall) {
3226   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3227     Expr *Arg = TheCall->getArg(0);
3228     llvm::APSInt AbortCode(32);
3229     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3230         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3231       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3232              << Arg->getSourceRange();
3233   }
3234 
3235   // For intrinsics which take an immediate value as part of the instruction,
3236   // range check them here.
3237   unsigned i = 0, l = 0, u = 0;
3238   switch (BuiltinID) {
3239   default: return false;
3240   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3241   case SystemZ::BI__builtin_s390_verimb:
3242   case SystemZ::BI__builtin_s390_verimh:
3243   case SystemZ::BI__builtin_s390_verimf:
3244   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3245   case SystemZ::BI__builtin_s390_vfaeb:
3246   case SystemZ::BI__builtin_s390_vfaeh:
3247   case SystemZ::BI__builtin_s390_vfaef:
3248   case SystemZ::BI__builtin_s390_vfaebs:
3249   case SystemZ::BI__builtin_s390_vfaehs:
3250   case SystemZ::BI__builtin_s390_vfaefs:
3251   case SystemZ::BI__builtin_s390_vfaezb:
3252   case SystemZ::BI__builtin_s390_vfaezh:
3253   case SystemZ::BI__builtin_s390_vfaezf:
3254   case SystemZ::BI__builtin_s390_vfaezbs:
3255   case SystemZ::BI__builtin_s390_vfaezhs:
3256   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3257   case SystemZ::BI__builtin_s390_vfisb:
3258   case SystemZ::BI__builtin_s390_vfidb:
3259     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3260            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3261   case SystemZ::BI__builtin_s390_vftcisb:
3262   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3263   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3264   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3265   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3266   case SystemZ::BI__builtin_s390_vstrcb:
3267   case SystemZ::BI__builtin_s390_vstrch:
3268   case SystemZ::BI__builtin_s390_vstrcf:
3269   case SystemZ::BI__builtin_s390_vstrczb:
3270   case SystemZ::BI__builtin_s390_vstrczh:
3271   case SystemZ::BI__builtin_s390_vstrczf:
3272   case SystemZ::BI__builtin_s390_vstrcbs:
3273   case SystemZ::BI__builtin_s390_vstrchs:
3274   case SystemZ::BI__builtin_s390_vstrcfs:
3275   case SystemZ::BI__builtin_s390_vstrczbs:
3276   case SystemZ::BI__builtin_s390_vstrczhs:
3277   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3278   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3279   case SystemZ::BI__builtin_s390_vfminsb:
3280   case SystemZ::BI__builtin_s390_vfmaxsb:
3281   case SystemZ::BI__builtin_s390_vfmindb:
3282   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3283   }
3284   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3285 }
3286 
3287 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3288 /// This checks that the target supports __builtin_cpu_supports and
3289 /// that the string argument is constant and valid.
3290 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3291   Expr *Arg = TheCall->getArg(0);
3292 
3293   // Check if the argument is a string literal.
3294   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3295     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3296            << Arg->getSourceRange();
3297 
3298   // Check the contents of the string.
3299   StringRef Feature =
3300       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3301   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3302     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3303            << Arg->getSourceRange();
3304   return false;
3305 }
3306 
3307 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3308 /// This checks that the target supports __builtin_cpu_is and
3309 /// that the string argument is constant and valid.
3310 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3311   Expr *Arg = TheCall->getArg(0);
3312 
3313   // Check if the argument is a string literal.
3314   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3315     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3316            << Arg->getSourceRange();
3317 
3318   // Check the contents of the string.
3319   StringRef Feature =
3320       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3321   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3322     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3323            << Arg->getSourceRange();
3324   return false;
3325 }
3326 
3327 // Check if the rounding mode is legal.
3328 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3329   // Indicates if this instruction has rounding control or just SAE.
3330   bool HasRC = false;
3331 
3332   unsigned ArgNum = 0;
3333   switch (BuiltinID) {
3334   default:
3335     return false;
3336   case X86::BI__builtin_ia32_vcvttsd2si32:
3337   case X86::BI__builtin_ia32_vcvttsd2si64:
3338   case X86::BI__builtin_ia32_vcvttsd2usi32:
3339   case X86::BI__builtin_ia32_vcvttsd2usi64:
3340   case X86::BI__builtin_ia32_vcvttss2si32:
3341   case X86::BI__builtin_ia32_vcvttss2si64:
3342   case X86::BI__builtin_ia32_vcvttss2usi32:
3343   case X86::BI__builtin_ia32_vcvttss2usi64:
3344     ArgNum = 1;
3345     break;
3346   case X86::BI__builtin_ia32_maxpd512:
3347   case X86::BI__builtin_ia32_maxps512:
3348   case X86::BI__builtin_ia32_minpd512:
3349   case X86::BI__builtin_ia32_minps512:
3350     ArgNum = 2;
3351     break;
3352   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3353   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3354   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3355   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3356   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3357   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3358   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3359   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3360   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3361   case X86::BI__builtin_ia32_exp2pd_mask:
3362   case X86::BI__builtin_ia32_exp2ps_mask:
3363   case X86::BI__builtin_ia32_getexppd512_mask:
3364   case X86::BI__builtin_ia32_getexpps512_mask:
3365   case X86::BI__builtin_ia32_rcp28pd_mask:
3366   case X86::BI__builtin_ia32_rcp28ps_mask:
3367   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3368   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3369   case X86::BI__builtin_ia32_vcomisd:
3370   case X86::BI__builtin_ia32_vcomiss:
3371   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3372     ArgNum = 3;
3373     break;
3374   case X86::BI__builtin_ia32_cmppd512_mask:
3375   case X86::BI__builtin_ia32_cmpps512_mask:
3376   case X86::BI__builtin_ia32_cmpsd_mask:
3377   case X86::BI__builtin_ia32_cmpss_mask:
3378   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3379   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3380   case X86::BI__builtin_ia32_getexpss128_round_mask:
3381   case X86::BI__builtin_ia32_maxsd_round_mask:
3382   case X86::BI__builtin_ia32_maxss_round_mask:
3383   case X86::BI__builtin_ia32_minsd_round_mask:
3384   case X86::BI__builtin_ia32_minss_round_mask:
3385   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3386   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3387   case X86::BI__builtin_ia32_reducepd512_mask:
3388   case X86::BI__builtin_ia32_reduceps512_mask:
3389   case X86::BI__builtin_ia32_rndscalepd_mask:
3390   case X86::BI__builtin_ia32_rndscaleps_mask:
3391   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3392   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3393     ArgNum = 4;
3394     break;
3395   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3396   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3397   case X86::BI__builtin_ia32_fixupimmps512_mask:
3398   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3399   case X86::BI__builtin_ia32_fixupimmsd_mask:
3400   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3401   case X86::BI__builtin_ia32_fixupimmss_mask:
3402   case X86::BI__builtin_ia32_fixupimmss_maskz:
3403   case X86::BI__builtin_ia32_rangepd512_mask:
3404   case X86::BI__builtin_ia32_rangeps512_mask:
3405   case X86::BI__builtin_ia32_rangesd128_round_mask:
3406   case X86::BI__builtin_ia32_rangess128_round_mask:
3407   case X86::BI__builtin_ia32_reducesd_mask:
3408   case X86::BI__builtin_ia32_reducess_mask:
3409   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3410   case X86::BI__builtin_ia32_rndscaless_round_mask:
3411     ArgNum = 5;
3412     break;
3413   case X86::BI__builtin_ia32_vcvtsd2si64:
3414   case X86::BI__builtin_ia32_vcvtsd2si32:
3415   case X86::BI__builtin_ia32_vcvtsd2usi32:
3416   case X86::BI__builtin_ia32_vcvtsd2usi64:
3417   case X86::BI__builtin_ia32_vcvtss2si32:
3418   case X86::BI__builtin_ia32_vcvtss2si64:
3419   case X86::BI__builtin_ia32_vcvtss2usi32:
3420   case X86::BI__builtin_ia32_vcvtss2usi64:
3421   case X86::BI__builtin_ia32_sqrtpd512:
3422   case X86::BI__builtin_ia32_sqrtps512:
3423     ArgNum = 1;
3424     HasRC = true;
3425     break;
3426   case X86::BI__builtin_ia32_addpd512:
3427   case X86::BI__builtin_ia32_addps512:
3428   case X86::BI__builtin_ia32_divpd512:
3429   case X86::BI__builtin_ia32_divps512:
3430   case X86::BI__builtin_ia32_mulpd512:
3431   case X86::BI__builtin_ia32_mulps512:
3432   case X86::BI__builtin_ia32_subpd512:
3433   case X86::BI__builtin_ia32_subps512:
3434   case X86::BI__builtin_ia32_cvtsi2sd64:
3435   case X86::BI__builtin_ia32_cvtsi2ss32:
3436   case X86::BI__builtin_ia32_cvtsi2ss64:
3437   case X86::BI__builtin_ia32_cvtusi2sd64:
3438   case X86::BI__builtin_ia32_cvtusi2ss32:
3439   case X86::BI__builtin_ia32_cvtusi2ss64:
3440     ArgNum = 2;
3441     HasRC = true;
3442     break;
3443   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3444   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3445   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3446   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3447   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3448   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3449   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3450   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3451   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3452   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3453   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3454   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3455   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3456   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3457   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3458     ArgNum = 3;
3459     HasRC = true;
3460     break;
3461   case X86::BI__builtin_ia32_addss_round_mask:
3462   case X86::BI__builtin_ia32_addsd_round_mask:
3463   case X86::BI__builtin_ia32_divss_round_mask:
3464   case X86::BI__builtin_ia32_divsd_round_mask:
3465   case X86::BI__builtin_ia32_mulss_round_mask:
3466   case X86::BI__builtin_ia32_mulsd_round_mask:
3467   case X86::BI__builtin_ia32_subss_round_mask:
3468   case X86::BI__builtin_ia32_subsd_round_mask:
3469   case X86::BI__builtin_ia32_scalefpd512_mask:
3470   case X86::BI__builtin_ia32_scalefps512_mask:
3471   case X86::BI__builtin_ia32_scalefsd_round_mask:
3472   case X86::BI__builtin_ia32_scalefss_round_mask:
3473   case X86::BI__builtin_ia32_getmantpd512_mask:
3474   case X86::BI__builtin_ia32_getmantps512_mask:
3475   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3476   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3477   case X86::BI__builtin_ia32_sqrtss_round_mask:
3478   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3479   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3480   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3481   case X86::BI__builtin_ia32_vfmaddss3_mask:
3482   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3483   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3484   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3485   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3486   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3487   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3488   case X86::BI__builtin_ia32_vfmaddps512_mask:
3489   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3490   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3491   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3492   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3493   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3494   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3495   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3496   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3497   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3498   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3499   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3500     ArgNum = 4;
3501     HasRC = true;
3502     break;
3503   case X86::BI__builtin_ia32_getmantsd_round_mask:
3504   case X86::BI__builtin_ia32_getmantss_round_mask:
3505     ArgNum = 5;
3506     HasRC = true;
3507     break;
3508   }
3509 
3510   llvm::APSInt Result;
3511 
3512   // We can't check the value of a dependent argument.
3513   Expr *Arg = TheCall->getArg(ArgNum);
3514   if (Arg->isTypeDependent() || Arg->isValueDependent())
3515     return false;
3516 
3517   // Check constant-ness first.
3518   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3519     return true;
3520 
3521   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3522   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3523   // combined with ROUND_NO_EXC.
3524   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3525       Result == 8/*ROUND_NO_EXC*/ ||
3526       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3527     return false;
3528 
3529   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3530          << Arg->getSourceRange();
3531 }
3532 
3533 // Check if the gather/scatter scale is legal.
3534 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3535                                              CallExpr *TheCall) {
3536   unsigned ArgNum = 0;
3537   switch (BuiltinID) {
3538   default:
3539     return false;
3540   case X86::BI__builtin_ia32_gatherpfdpd:
3541   case X86::BI__builtin_ia32_gatherpfdps:
3542   case X86::BI__builtin_ia32_gatherpfqpd:
3543   case X86::BI__builtin_ia32_gatherpfqps:
3544   case X86::BI__builtin_ia32_scatterpfdpd:
3545   case X86::BI__builtin_ia32_scatterpfdps:
3546   case X86::BI__builtin_ia32_scatterpfqpd:
3547   case X86::BI__builtin_ia32_scatterpfqps:
3548     ArgNum = 3;
3549     break;
3550   case X86::BI__builtin_ia32_gatherd_pd:
3551   case X86::BI__builtin_ia32_gatherd_pd256:
3552   case X86::BI__builtin_ia32_gatherq_pd:
3553   case X86::BI__builtin_ia32_gatherq_pd256:
3554   case X86::BI__builtin_ia32_gatherd_ps:
3555   case X86::BI__builtin_ia32_gatherd_ps256:
3556   case X86::BI__builtin_ia32_gatherq_ps:
3557   case X86::BI__builtin_ia32_gatherq_ps256:
3558   case X86::BI__builtin_ia32_gatherd_q:
3559   case X86::BI__builtin_ia32_gatherd_q256:
3560   case X86::BI__builtin_ia32_gatherq_q:
3561   case X86::BI__builtin_ia32_gatherq_q256:
3562   case X86::BI__builtin_ia32_gatherd_d:
3563   case X86::BI__builtin_ia32_gatherd_d256:
3564   case X86::BI__builtin_ia32_gatherq_d:
3565   case X86::BI__builtin_ia32_gatherq_d256:
3566   case X86::BI__builtin_ia32_gather3div2df:
3567   case X86::BI__builtin_ia32_gather3div2di:
3568   case X86::BI__builtin_ia32_gather3div4df:
3569   case X86::BI__builtin_ia32_gather3div4di:
3570   case X86::BI__builtin_ia32_gather3div4sf:
3571   case X86::BI__builtin_ia32_gather3div4si:
3572   case X86::BI__builtin_ia32_gather3div8sf:
3573   case X86::BI__builtin_ia32_gather3div8si:
3574   case X86::BI__builtin_ia32_gather3siv2df:
3575   case X86::BI__builtin_ia32_gather3siv2di:
3576   case X86::BI__builtin_ia32_gather3siv4df:
3577   case X86::BI__builtin_ia32_gather3siv4di:
3578   case X86::BI__builtin_ia32_gather3siv4sf:
3579   case X86::BI__builtin_ia32_gather3siv4si:
3580   case X86::BI__builtin_ia32_gather3siv8sf:
3581   case X86::BI__builtin_ia32_gather3siv8si:
3582   case X86::BI__builtin_ia32_gathersiv8df:
3583   case X86::BI__builtin_ia32_gathersiv16sf:
3584   case X86::BI__builtin_ia32_gatherdiv8df:
3585   case X86::BI__builtin_ia32_gatherdiv16sf:
3586   case X86::BI__builtin_ia32_gathersiv8di:
3587   case X86::BI__builtin_ia32_gathersiv16si:
3588   case X86::BI__builtin_ia32_gatherdiv8di:
3589   case X86::BI__builtin_ia32_gatherdiv16si:
3590   case X86::BI__builtin_ia32_scatterdiv2df:
3591   case X86::BI__builtin_ia32_scatterdiv2di:
3592   case X86::BI__builtin_ia32_scatterdiv4df:
3593   case X86::BI__builtin_ia32_scatterdiv4di:
3594   case X86::BI__builtin_ia32_scatterdiv4sf:
3595   case X86::BI__builtin_ia32_scatterdiv4si:
3596   case X86::BI__builtin_ia32_scatterdiv8sf:
3597   case X86::BI__builtin_ia32_scatterdiv8si:
3598   case X86::BI__builtin_ia32_scattersiv2df:
3599   case X86::BI__builtin_ia32_scattersiv2di:
3600   case X86::BI__builtin_ia32_scattersiv4df:
3601   case X86::BI__builtin_ia32_scattersiv4di:
3602   case X86::BI__builtin_ia32_scattersiv4sf:
3603   case X86::BI__builtin_ia32_scattersiv4si:
3604   case X86::BI__builtin_ia32_scattersiv8sf:
3605   case X86::BI__builtin_ia32_scattersiv8si:
3606   case X86::BI__builtin_ia32_scattersiv8df:
3607   case X86::BI__builtin_ia32_scattersiv16sf:
3608   case X86::BI__builtin_ia32_scatterdiv8df:
3609   case X86::BI__builtin_ia32_scatterdiv16sf:
3610   case X86::BI__builtin_ia32_scattersiv8di:
3611   case X86::BI__builtin_ia32_scattersiv16si:
3612   case X86::BI__builtin_ia32_scatterdiv8di:
3613   case X86::BI__builtin_ia32_scatterdiv16si:
3614     ArgNum = 4;
3615     break;
3616   }
3617 
3618   llvm::APSInt Result;
3619 
3620   // We can't check the value of a dependent argument.
3621   Expr *Arg = TheCall->getArg(ArgNum);
3622   if (Arg->isTypeDependent() || Arg->isValueDependent())
3623     return false;
3624 
3625   // Check constant-ness first.
3626   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3627     return true;
3628 
3629   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3630     return false;
3631 
3632   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3633          << Arg->getSourceRange();
3634 }
3635 
3636 static bool isX86_32Builtin(unsigned BuiltinID) {
3637   // These builtins only work on x86-32 targets.
3638   switch (BuiltinID) {
3639   case X86::BI__builtin_ia32_readeflags_u32:
3640   case X86::BI__builtin_ia32_writeeflags_u32:
3641     return true;
3642   }
3643 
3644   return false;
3645 }
3646 
3647 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3648   if (BuiltinID == X86::BI__builtin_cpu_supports)
3649     return SemaBuiltinCpuSupports(*this, TheCall);
3650 
3651   if (BuiltinID == X86::BI__builtin_cpu_is)
3652     return SemaBuiltinCpuIs(*this, TheCall);
3653 
3654   // Check for 32-bit only builtins on a 64-bit target.
3655   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3656   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3657     return Diag(TheCall->getCallee()->getBeginLoc(),
3658                 diag::err_32_bit_builtin_64_bit_tgt);
3659 
3660   // If the intrinsic has rounding or SAE make sure its valid.
3661   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3662     return true;
3663 
3664   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3665   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3666     return true;
3667 
3668   // For intrinsics which take an immediate value as part of the instruction,
3669   // range check them here.
3670   int i = 0, l = 0, u = 0;
3671   switch (BuiltinID) {
3672   default:
3673     return false;
3674   case X86::BI__builtin_ia32_vec_ext_v2si:
3675   case X86::BI__builtin_ia32_vec_ext_v2di:
3676   case X86::BI__builtin_ia32_vextractf128_pd256:
3677   case X86::BI__builtin_ia32_vextractf128_ps256:
3678   case X86::BI__builtin_ia32_vextractf128_si256:
3679   case X86::BI__builtin_ia32_extract128i256:
3680   case X86::BI__builtin_ia32_extractf64x4_mask:
3681   case X86::BI__builtin_ia32_extracti64x4_mask:
3682   case X86::BI__builtin_ia32_extractf32x8_mask:
3683   case X86::BI__builtin_ia32_extracti32x8_mask:
3684   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3685   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3686   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3687   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3688     i = 1; l = 0; u = 1;
3689     break;
3690   case X86::BI__builtin_ia32_vec_set_v2di:
3691   case X86::BI__builtin_ia32_vinsertf128_pd256:
3692   case X86::BI__builtin_ia32_vinsertf128_ps256:
3693   case X86::BI__builtin_ia32_vinsertf128_si256:
3694   case X86::BI__builtin_ia32_insert128i256:
3695   case X86::BI__builtin_ia32_insertf32x8:
3696   case X86::BI__builtin_ia32_inserti32x8:
3697   case X86::BI__builtin_ia32_insertf64x4:
3698   case X86::BI__builtin_ia32_inserti64x4:
3699   case X86::BI__builtin_ia32_insertf64x2_256:
3700   case X86::BI__builtin_ia32_inserti64x2_256:
3701   case X86::BI__builtin_ia32_insertf32x4_256:
3702   case X86::BI__builtin_ia32_inserti32x4_256:
3703     i = 2; l = 0; u = 1;
3704     break;
3705   case X86::BI__builtin_ia32_vpermilpd:
3706   case X86::BI__builtin_ia32_vec_ext_v4hi:
3707   case X86::BI__builtin_ia32_vec_ext_v4si:
3708   case X86::BI__builtin_ia32_vec_ext_v4sf:
3709   case X86::BI__builtin_ia32_vec_ext_v4di:
3710   case X86::BI__builtin_ia32_extractf32x4_mask:
3711   case X86::BI__builtin_ia32_extracti32x4_mask:
3712   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3713   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3714     i = 1; l = 0; u = 3;
3715     break;
3716   case X86::BI_mm_prefetch:
3717   case X86::BI__builtin_ia32_vec_ext_v8hi:
3718   case X86::BI__builtin_ia32_vec_ext_v8si:
3719     i = 1; l = 0; u = 7;
3720     break;
3721   case X86::BI__builtin_ia32_sha1rnds4:
3722   case X86::BI__builtin_ia32_blendpd:
3723   case X86::BI__builtin_ia32_shufpd:
3724   case X86::BI__builtin_ia32_vec_set_v4hi:
3725   case X86::BI__builtin_ia32_vec_set_v4si:
3726   case X86::BI__builtin_ia32_vec_set_v4di:
3727   case X86::BI__builtin_ia32_shuf_f32x4_256:
3728   case X86::BI__builtin_ia32_shuf_f64x2_256:
3729   case X86::BI__builtin_ia32_shuf_i32x4_256:
3730   case X86::BI__builtin_ia32_shuf_i64x2_256:
3731   case X86::BI__builtin_ia32_insertf64x2_512:
3732   case X86::BI__builtin_ia32_inserti64x2_512:
3733   case X86::BI__builtin_ia32_insertf32x4:
3734   case X86::BI__builtin_ia32_inserti32x4:
3735     i = 2; l = 0; u = 3;
3736     break;
3737   case X86::BI__builtin_ia32_vpermil2pd:
3738   case X86::BI__builtin_ia32_vpermil2pd256:
3739   case X86::BI__builtin_ia32_vpermil2ps:
3740   case X86::BI__builtin_ia32_vpermil2ps256:
3741     i = 3; l = 0; u = 3;
3742     break;
3743   case X86::BI__builtin_ia32_cmpb128_mask:
3744   case X86::BI__builtin_ia32_cmpw128_mask:
3745   case X86::BI__builtin_ia32_cmpd128_mask:
3746   case X86::BI__builtin_ia32_cmpq128_mask:
3747   case X86::BI__builtin_ia32_cmpb256_mask:
3748   case X86::BI__builtin_ia32_cmpw256_mask:
3749   case X86::BI__builtin_ia32_cmpd256_mask:
3750   case X86::BI__builtin_ia32_cmpq256_mask:
3751   case X86::BI__builtin_ia32_cmpb512_mask:
3752   case X86::BI__builtin_ia32_cmpw512_mask:
3753   case X86::BI__builtin_ia32_cmpd512_mask:
3754   case X86::BI__builtin_ia32_cmpq512_mask:
3755   case X86::BI__builtin_ia32_ucmpb128_mask:
3756   case X86::BI__builtin_ia32_ucmpw128_mask:
3757   case X86::BI__builtin_ia32_ucmpd128_mask:
3758   case X86::BI__builtin_ia32_ucmpq128_mask:
3759   case X86::BI__builtin_ia32_ucmpb256_mask:
3760   case X86::BI__builtin_ia32_ucmpw256_mask:
3761   case X86::BI__builtin_ia32_ucmpd256_mask:
3762   case X86::BI__builtin_ia32_ucmpq256_mask:
3763   case X86::BI__builtin_ia32_ucmpb512_mask:
3764   case X86::BI__builtin_ia32_ucmpw512_mask:
3765   case X86::BI__builtin_ia32_ucmpd512_mask:
3766   case X86::BI__builtin_ia32_ucmpq512_mask:
3767   case X86::BI__builtin_ia32_vpcomub:
3768   case X86::BI__builtin_ia32_vpcomuw:
3769   case X86::BI__builtin_ia32_vpcomud:
3770   case X86::BI__builtin_ia32_vpcomuq:
3771   case X86::BI__builtin_ia32_vpcomb:
3772   case X86::BI__builtin_ia32_vpcomw:
3773   case X86::BI__builtin_ia32_vpcomd:
3774   case X86::BI__builtin_ia32_vpcomq:
3775   case X86::BI__builtin_ia32_vec_set_v8hi:
3776   case X86::BI__builtin_ia32_vec_set_v8si:
3777     i = 2; l = 0; u = 7;
3778     break;
3779   case X86::BI__builtin_ia32_vpermilpd256:
3780   case X86::BI__builtin_ia32_roundps:
3781   case X86::BI__builtin_ia32_roundpd:
3782   case X86::BI__builtin_ia32_roundps256:
3783   case X86::BI__builtin_ia32_roundpd256:
3784   case X86::BI__builtin_ia32_getmantpd128_mask:
3785   case X86::BI__builtin_ia32_getmantpd256_mask:
3786   case X86::BI__builtin_ia32_getmantps128_mask:
3787   case X86::BI__builtin_ia32_getmantps256_mask:
3788   case X86::BI__builtin_ia32_getmantpd512_mask:
3789   case X86::BI__builtin_ia32_getmantps512_mask:
3790   case X86::BI__builtin_ia32_vec_ext_v16qi:
3791   case X86::BI__builtin_ia32_vec_ext_v16hi:
3792     i = 1; l = 0; u = 15;
3793     break;
3794   case X86::BI__builtin_ia32_pblendd128:
3795   case X86::BI__builtin_ia32_blendps:
3796   case X86::BI__builtin_ia32_blendpd256:
3797   case X86::BI__builtin_ia32_shufpd256:
3798   case X86::BI__builtin_ia32_roundss:
3799   case X86::BI__builtin_ia32_roundsd:
3800   case X86::BI__builtin_ia32_rangepd128_mask:
3801   case X86::BI__builtin_ia32_rangepd256_mask:
3802   case X86::BI__builtin_ia32_rangepd512_mask:
3803   case X86::BI__builtin_ia32_rangeps128_mask:
3804   case X86::BI__builtin_ia32_rangeps256_mask:
3805   case X86::BI__builtin_ia32_rangeps512_mask:
3806   case X86::BI__builtin_ia32_getmantsd_round_mask:
3807   case X86::BI__builtin_ia32_getmantss_round_mask:
3808   case X86::BI__builtin_ia32_vec_set_v16qi:
3809   case X86::BI__builtin_ia32_vec_set_v16hi:
3810     i = 2; l = 0; u = 15;
3811     break;
3812   case X86::BI__builtin_ia32_vec_ext_v32qi:
3813     i = 1; l = 0; u = 31;
3814     break;
3815   case X86::BI__builtin_ia32_cmpps:
3816   case X86::BI__builtin_ia32_cmpss:
3817   case X86::BI__builtin_ia32_cmppd:
3818   case X86::BI__builtin_ia32_cmpsd:
3819   case X86::BI__builtin_ia32_cmpps256:
3820   case X86::BI__builtin_ia32_cmppd256:
3821   case X86::BI__builtin_ia32_cmpps128_mask:
3822   case X86::BI__builtin_ia32_cmppd128_mask:
3823   case X86::BI__builtin_ia32_cmpps256_mask:
3824   case X86::BI__builtin_ia32_cmppd256_mask:
3825   case X86::BI__builtin_ia32_cmpps512_mask:
3826   case X86::BI__builtin_ia32_cmppd512_mask:
3827   case X86::BI__builtin_ia32_cmpsd_mask:
3828   case X86::BI__builtin_ia32_cmpss_mask:
3829   case X86::BI__builtin_ia32_vec_set_v32qi:
3830     i = 2; l = 0; u = 31;
3831     break;
3832   case X86::BI__builtin_ia32_permdf256:
3833   case X86::BI__builtin_ia32_permdi256:
3834   case X86::BI__builtin_ia32_permdf512:
3835   case X86::BI__builtin_ia32_permdi512:
3836   case X86::BI__builtin_ia32_vpermilps:
3837   case X86::BI__builtin_ia32_vpermilps256:
3838   case X86::BI__builtin_ia32_vpermilpd512:
3839   case X86::BI__builtin_ia32_vpermilps512:
3840   case X86::BI__builtin_ia32_pshufd:
3841   case X86::BI__builtin_ia32_pshufd256:
3842   case X86::BI__builtin_ia32_pshufd512:
3843   case X86::BI__builtin_ia32_pshufhw:
3844   case X86::BI__builtin_ia32_pshufhw256:
3845   case X86::BI__builtin_ia32_pshufhw512:
3846   case X86::BI__builtin_ia32_pshuflw:
3847   case X86::BI__builtin_ia32_pshuflw256:
3848   case X86::BI__builtin_ia32_pshuflw512:
3849   case X86::BI__builtin_ia32_vcvtps2ph:
3850   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3851   case X86::BI__builtin_ia32_vcvtps2ph256:
3852   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3853   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3854   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3855   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3856   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3857   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3858   case X86::BI__builtin_ia32_rndscaleps_mask:
3859   case X86::BI__builtin_ia32_rndscalepd_mask:
3860   case X86::BI__builtin_ia32_reducepd128_mask:
3861   case X86::BI__builtin_ia32_reducepd256_mask:
3862   case X86::BI__builtin_ia32_reducepd512_mask:
3863   case X86::BI__builtin_ia32_reduceps128_mask:
3864   case X86::BI__builtin_ia32_reduceps256_mask:
3865   case X86::BI__builtin_ia32_reduceps512_mask:
3866   case X86::BI__builtin_ia32_prold512:
3867   case X86::BI__builtin_ia32_prolq512:
3868   case X86::BI__builtin_ia32_prold128:
3869   case X86::BI__builtin_ia32_prold256:
3870   case X86::BI__builtin_ia32_prolq128:
3871   case X86::BI__builtin_ia32_prolq256:
3872   case X86::BI__builtin_ia32_prord512:
3873   case X86::BI__builtin_ia32_prorq512:
3874   case X86::BI__builtin_ia32_prord128:
3875   case X86::BI__builtin_ia32_prord256:
3876   case X86::BI__builtin_ia32_prorq128:
3877   case X86::BI__builtin_ia32_prorq256:
3878   case X86::BI__builtin_ia32_fpclasspd128_mask:
3879   case X86::BI__builtin_ia32_fpclasspd256_mask:
3880   case X86::BI__builtin_ia32_fpclassps128_mask:
3881   case X86::BI__builtin_ia32_fpclassps256_mask:
3882   case X86::BI__builtin_ia32_fpclassps512_mask:
3883   case X86::BI__builtin_ia32_fpclasspd512_mask:
3884   case X86::BI__builtin_ia32_fpclasssd_mask:
3885   case X86::BI__builtin_ia32_fpclassss_mask:
3886   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3887   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3888   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3889   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3890   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3891   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3892   case X86::BI__builtin_ia32_kshiftliqi:
3893   case X86::BI__builtin_ia32_kshiftlihi:
3894   case X86::BI__builtin_ia32_kshiftlisi:
3895   case X86::BI__builtin_ia32_kshiftlidi:
3896   case X86::BI__builtin_ia32_kshiftriqi:
3897   case X86::BI__builtin_ia32_kshiftrihi:
3898   case X86::BI__builtin_ia32_kshiftrisi:
3899   case X86::BI__builtin_ia32_kshiftridi:
3900     i = 1; l = 0; u = 255;
3901     break;
3902   case X86::BI__builtin_ia32_vperm2f128_pd256:
3903   case X86::BI__builtin_ia32_vperm2f128_ps256:
3904   case X86::BI__builtin_ia32_vperm2f128_si256:
3905   case X86::BI__builtin_ia32_permti256:
3906   case X86::BI__builtin_ia32_pblendw128:
3907   case X86::BI__builtin_ia32_pblendw256:
3908   case X86::BI__builtin_ia32_blendps256:
3909   case X86::BI__builtin_ia32_pblendd256:
3910   case X86::BI__builtin_ia32_palignr128:
3911   case X86::BI__builtin_ia32_palignr256:
3912   case X86::BI__builtin_ia32_palignr512:
3913   case X86::BI__builtin_ia32_alignq512:
3914   case X86::BI__builtin_ia32_alignd512:
3915   case X86::BI__builtin_ia32_alignd128:
3916   case X86::BI__builtin_ia32_alignd256:
3917   case X86::BI__builtin_ia32_alignq128:
3918   case X86::BI__builtin_ia32_alignq256:
3919   case X86::BI__builtin_ia32_vcomisd:
3920   case X86::BI__builtin_ia32_vcomiss:
3921   case X86::BI__builtin_ia32_shuf_f32x4:
3922   case X86::BI__builtin_ia32_shuf_f64x2:
3923   case X86::BI__builtin_ia32_shuf_i32x4:
3924   case X86::BI__builtin_ia32_shuf_i64x2:
3925   case X86::BI__builtin_ia32_shufpd512:
3926   case X86::BI__builtin_ia32_shufps:
3927   case X86::BI__builtin_ia32_shufps256:
3928   case X86::BI__builtin_ia32_shufps512:
3929   case X86::BI__builtin_ia32_dbpsadbw128:
3930   case X86::BI__builtin_ia32_dbpsadbw256:
3931   case X86::BI__builtin_ia32_dbpsadbw512:
3932   case X86::BI__builtin_ia32_vpshldd128:
3933   case X86::BI__builtin_ia32_vpshldd256:
3934   case X86::BI__builtin_ia32_vpshldd512:
3935   case X86::BI__builtin_ia32_vpshldq128:
3936   case X86::BI__builtin_ia32_vpshldq256:
3937   case X86::BI__builtin_ia32_vpshldq512:
3938   case X86::BI__builtin_ia32_vpshldw128:
3939   case X86::BI__builtin_ia32_vpshldw256:
3940   case X86::BI__builtin_ia32_vpshldw512:
3941   case X86::BI__builtin_ia32_vpshrdd128:
3942   case X86::BI__builtin_ia32_vpshrdd256:
3943   case X86::BI__builtin_ia32_vpshrdd512:
3944   case X86::BI__builtin_ia32_vpshrdq128:
3945   case X86::BI__builtin_ia32_vpshrdq256:
3946   case X86::BI__builtin_ia32_vpshrdq512:
3947   case X86::BI__builtin_ia32_vpshrdw128:
3948   case X86::BI__builtin_ia32_vpshrdw256:
3949   case X86::BI__builtin_ia32_vpshrdw512:
3950     i = 2; l = 0; u = 255;
3951     break;
3952   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3953   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3954   case X86::BI__builtin_ia32_fixupimmps512_mask:
3955   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3956   case X86::BI__builtin_ia32_fixupimmsd_mask:
3957   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3958   case X86::BI__builtin_ia32_fixupimmss_mask:
3959   case X86::BI__builtin_ia32_fixupimmss_maskz:
3960   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3961   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3962   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3963   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3964   case X86::BI__builtin_ia32_fixupimmps128_mask:
3965   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3966   case X86::BI__builtin_ia32_fixupimmps256_mask:
3967   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3968   case X86::BI__builtin_ia32_pternlogd512_mask:
3969   case X86::BI__builtin_ia32_pternlogd512_maskz:
3970   case X86::BI__builtin_ia32_pternlogq512_mask:
3971   case X86::BI__builtin_ia32_pternlogq512_maskz:
3972   case X86::BI__builtin_ia32_pternlogd128_mask:
3973   case X86::BI__builtin_ia32_pternlogd128_maskz:
3974   case X86::BI__builtin_ia32_pternlogd256_mask:
3975   case X86::BI__builtin_ia32_pternlogd256_maskz:
3976   case X86::BI__builtin_ia32_pternlogq128_mask:
3977   case X86::BI__builtin_ia32_pternlogq128_maskz:
3978   case X86::BI__builtin_ia32_pternlogq256_mask:
3979   case X86::BI__builtin_ia32_pternlogq256_maskz:
3980     i = 3; l = 0; u = 255;
3981     break;
3982   case X86::BI__builtin_ia32_gatherpfdpd:
3983   case X86::BI__builtin_ia32_gatherpfdps:
3984   case X86::BI__builtin_ia32_gatherpfqpd:
3985   case X86::BI__builtin_ia32_gatherpfqps:
3986   case X86::BI__builtin_ia32_scatterpfdpd:
3987   case X86::BI__builtin_ia32_scatterpfdps:
3988   case X86::BI__builtin_ia32_scatterpfqpd:
3989   case X86::BI__builtin_ia32_scatterpfqps:
3990     i = 4; l = 2; u = 3;
3991     break;
3992   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3993   case X86::BI__builtin_ia32_rndscaless_round_mask:
3994     i = 4; l = 0; u = 255;
3995     break;
3996   }
3997 
3998   // Note that we don't force a hard error on the range check here, allowing
3999   // template-generated or macro-generated dead code to potentially have out-of-
4000   // range values. These need to code generate, but don't need to necessarily
4001   // make any sense. We use a warning that defaults to an error.
4002   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4003 }
4004 
4005 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4006 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4007 /// Returns true when the format fits the function and the FormatStringInfo has
4008 /// been populated.
4009 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4010                                FormatStringInfo *FSI) {
4011   FSI->HasVAListArg = Format->getFirstArg() == 0;
4012   FSI->FormatIdx = Format->getFormatIdx() - 1;
4013   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4014 
4015   // The way the format attribute works in GCC, the implicit this argument
4016   // of member functions is counted. However, it doesn't appear in our own
4017   // lists, so decrement format_idx in that case.
4018   if (IsCXXMember) {
4019     if(FSI->FormatIdx == 0)
4020       return false;
4021     --FSI->FormatIdx;
4022     if (FSI->FirstDataArg != 0)
4023       --FSI->FirstDataArg;
4024   }
4025   return true;
4026 }
4027 
4028 /// Checks if a the given expression evaluates to null.
4029 ///
4030 /// Returns true if the value evaluates to null.
4031 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4032   // If the expression has non-null type, it doesn't evaluate to null.
4033   if (auto nullability
4034         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4035     if (*nullability == NullabilityKind::NonNull)
4036       return false;
4037   }
4038 
4039   // As a special case, transparent unions initialized with zero are
4040   // considered null for the purposes of the nonnull attribute.
4041   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4042     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4043       if (const CompoundLiteralExpr *CLE =
4044           dyn_cast<CompoundLiteralExpr>(Expr))
4045         if (const InitListExpr *ILE =
4046             dyn_cast<InitListExpr>(CLE->getInitializer()))
4047           Expr = ILE->getInit(0);
4048   }
4049 
4050   bool Result;
4051   return (!Expr->isValueDependent() &&
4052           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4053           !Result);
4054 }
4055 
4056 static void CheckNonNullArgument(Sema &S,
4057                                  const Expr *ArgExpr,
4058                                  SourceLocation CallSiteLoc) {
4059   if (CheckNonNullExpr(S, ArgExpr))
4060     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4061            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
4062 }
4063 
4064 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4065   FormatStringInfo FSI;
4066   if ((GetFormatStringType(Format) == FST_NSString) &&
4067       getFormatStringInfo(Format, false, &FSI)) {
4068     Idx = FSI.FormatIdx;
4069     return true;
4070   }
4071   return false;
4072 }
4073 
4074 /// Diagnose use of %s directive in an NSString which is being passed
4075 /// as formatting string to formatting method.
4076 static void
4077 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4078                                         const NamedDecl *FDecl,
4079                                         Expr **Args,
4080                                         unsigned NumArgs) {
4081   unsigned Idx = 0;
4082   bool Format = false;
4083   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4084   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4085     Idx = 2;
4086     Format = true;
4087   }
4088   else
4089     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4090       if (S.GetFormatNSStringIdx(I, Idx)) {
4091         Format = true;
4092         break;
4093       }
4094     }
4095   if (!Format || NumArgs <= Idx)
4096     return;
4097   const Expr *FormatExpr = Args[Idx];
4098   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4099     FormatExpr = CSCE->getSubExpr();
4100   const StringLiteral *FormatString;
4101   if (const ObjCStringLiteral *OSL =
4102       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4103     FormatString = OSL->getString();
4104   else
4105     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4106   if (!FormatString)
4107     return;
4108   if (S.FormatStringHasSArg(FormatString)) {
4109     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4110       << "%s" << 1 << 1;
4111     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4112       << FDecl->getDeclName();
4113   }
4114 }
4115 
4116 /// Determine whether the given type has a non-null nullability annotation.
4117 static bool isNonNullType(ASTContext &ctx, QualType type) {
4118   if (auto nullability = type->getNullability(ctx))
4119     return *nullability == NullabilityKind::NonNull;
4120 
4121   return false;
4122 }
4123 
4124 static void CheckNonNullArguments(Sema &S,
4125                                   const NamedDecl *FDecl,
4126                                   const FunctionProtoType *Proto,
4127                                   ArrayRef<const Expr *> Args,
4128                                   SourceLocation CallSiteLoc) {
4129   assert((FDecl || Proto) && "Need a function declaration or prototype");
4130 
4131   // Check the attributes attached to the method/function itself.
4132   llvm::SmallBitVector NonNullArgs;
4133   if (FDecl) {
4134     // Handle the nonnull attribute on the function/method declaration itself.
4135     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4136       if (!NonNull->args_size()) {
4137         // Easy case: all pointer arguments are nonnull.
4138         for (const auto *Arg : Args)
4139           if (S.isValidPointerAttrType(Arg->getType()))
4140             CheckNonNullArgument(S, Arg, CallSiteLoc);
4141         return;
4142       }
4143 
4144       for (const ParamIdx &Idx : NonNull->args()) {
4145         unsigned IdxAST = Idx.getASTIndex();
4146         if (IdxAST >= Args.size())
4147           continue;
4148         if (NonNullArgs.empty())
4149           NonNullArgs.resize(Args.size());
4150         NonNullArgs.set(IdxAST);
4151       }
4152     }
4153   }
4154 
4155   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4156     // Handle the nonnull attribute on the parameters of the
4157     // function/method.
4158     ArrayRef<ParmVarDecl*> parms;
4159     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4160       parms = FD->parameters();
4161     else
4162       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4163 
4164     unsigned ParamIndex = 0;
4165     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4166          I != E; ++I, ++ParamIndex) {
4167       const ParmVarDecl *PVD = *I;
4168       if (PVD->hasAttr<NonNullAttr>() ||
4169           isNonNullType(S.Context, PVD->getType())) {
4170         if (NonNullArgs.empty())
4171           NonNullArgs.resize(Args.size());
4172 
4173         NonNullArgs.set(ParamIndex);
4174       }
4175     }
4176   } else {
4177     // If we have a non-function, non-method declaration but no
4178     // function prototype, try to dig out the function prototype.
4179     if (!Proto) {
4180       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4181         QualType type = VD->getType().getNonReferenceType();
4182         if (auto pointerType = type->getAs<PointerType>())
4183           type = pointerType->getPointeeType();
4184         else if (auto blockType = type->getAs<BlockPointerType>())
4185           type = blockType->getPointeeType();
4186         // FIXME: data member pointers?
4187 
4188         // Dig out the function prototype, if there is one.
4189         Proto = type->getAs<FunctionProtoType>();
4190       }
4191     }
4192 
4193     // Fill in non-null argument information from the nullability
4194     // information on the parameter types (if we have them).
4195     if (Proto) {
4196       unsigned Index = 0;
4197       for (auto paramType : Proto->getParamTypes()) {
4198         if (isNonNullType(S.Context, paramType)) {
4199           if (NonNullArgs.empty())
4200             NonNullArgs.resize(Args.size());
4201 
4202           NonNullArgs.set(Index);
4203         }
4204 
4205         ++Index;
4206       }
4207     }
4208   }
4209 
4210   // Check for non-null arguments.
4211   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4212        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4213     if (NonNullArgs[ArgIndex])
4214       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4215   }
4216 }
4217 
4218 /// Handles the checks for format strings, non-POD arguments to vararg
4219 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4220 /// attributes.
4221 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4222                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4223                      bool IsMemberFunction, SourceLocation Loc,
4224                      SourceRange Range, VariadicCallType CallType) {
4225   // FIXME: We should check as much as we can in the template definition.
4226   if (CurContext->isDependentContext())
4227     return;
4228 
4229   // Printf and scanf checking.
4230   llvm::SmallBitVector CheckedVarArgs;
4231   if (FDecl) {
4232     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4233       // Only create vector if there are format attributes.
4234       CheckedVarArgs.resize(Args.size());
4235 
4236       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4237                            CheckedVarArgs);
4238     }
4239   }
4240 
4241   // Refuse POD arguments that weren't caught by the format string
4242   // checks above.
4243   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4244   if (CallType != VariadicDoesNotApply &&
4245       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4246     unsigned NumParams = Proto ? Proto->getNumParams()
4247                        : FDecl && isa<FunctionDecl>(FDecl)
4248                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4249                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4250                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4251                        : 0;
4252 
4253     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4254       // Args[ArgIdx] can be null in malformed code.
4255       if (const Expr *Arg = Args[ArgIdx]) {
4256         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4257           checkVariadicArgument(Arg, CallType);
4258       }
4259     }
4260   }
4261 
4262   if (FDecl || Proto) {
4263     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4264 
4265     // Type safety checking.
4266     if (FDecl) {
4267       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4268         CheckArgumentWithTypeTag(I, Args, Loc);
4269     }
4270   }
4271 
4272   if (FD)
4273     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4274 }
4275 
4276 /// CheckConstructorCall - Check a constructor call for correctness and safety
4277 /// properties not enforced by the C type system.
4278 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4279                                 ArrayRef<const Expr *> Args,
4280                                 const FunctionProtoType *Proto,
4281                                 SourceLocation Loc) {
4282   VariadicCallType CallType =
4283     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4284   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4285             Loc, SourceRange(), CallType);
4286 }
4287 
4288 /// CheckFunctionCall - Check a direct function call for various correctness
4289 /// and safety properties not strictly enforced by the C type system.
4290 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4291                              const FunctionProtoType *Proto) {
4292   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4293                               isa<CXXMethodDecl>(FDecl);
4294   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4295                           IsMemberOperatorCall;
4296   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4297                                                   TheCall->getCallee());
4298   Expr** Args = TheCall->getArgs();
4299   unsigned NumArgs = TheCall->getNumArgs();
4300 
4301   Expr *ImplicitThis = nullptr;
4302   if (IsMemberOperatorCall) {
4303     // If this is a call to a member operator, hide the first argument
4304     // from checkCall.
4305     // FIXME: Our choice of AST representation here is less than ideal.
4306     ImplicitThis = Args[0];
4307     ++Args;
4308     --NumArgs;
4309   } else if (IsMemberFunction)
4310     ImplicitThis =
4311         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4312 
4313   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4314             IsMemberFunction, TheCall->getRParenLoc(),
4315             TheCall->getCallee()->getSourceRange(), CallType);
4316 
4317   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4318   // None of the checks below are needed for functions that don't have
4319   // simple names (e.g., C++ conversion functions).
4320   if (!FnInfo)
4321     return false;
4322 
4323   CheckAbsoluteValueFunction(TheCall, FDecl);
4324   CheckMaxUnsignedZero(TheCall, FDecl);
4325 
4326   if (getLangOpts().ObjC)
4327     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4328 
4329   unsigned CMId = FDecl->getMemoryFunctionKind();
4330   if (CMId == 0)
4331     return false;
4332 
4333   // Handle memory setting and copying functions.
4334   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4335     CheckStrlcpycatArguments(TheCall, FnInfo);
4336   else if (CMId == Builtin::BIstrncat)
4337     CheckStrncatArguments(TheCall, FnInfo);
4338   else
4339     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4340 
4341   return false;
4342 }
4343 
4344 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4345                                ArrayRef<const Expr *> Args) {
4346   VariadicCallType CallType =
4347       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4348 
4349   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4350             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4351             CallType);
4352 
4353   return false;
4354 }
4355 
4356 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4357                             const FunctionProtoType *Proto) {
4358   QualType Ty;
4359   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4360     Ty = V->getType().getNonReferenceType();
4361   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4362     Ty = F->getType().getNonReferenceType();
4363   else
4364     return false;
4365 
4366   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4367       !Ty->isFunctionProtoType())
4368     return false;
4369 
4370   VariadicCallType CallType;
4371   if (!Proto || !Proto->isVariadic()) {
4372     CallType = VariadicDoesNotApply;
4373   } else if (Ty->isBlockPointerType()) {
4374     CallType = VariadicBlock;
4375   } else { // Ty->isFunctionPointerType()
4376     CallType = VariadicFunction;
4377   }
4378 
4379   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4380             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4381             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4382             TheCall->getCallee()->getSourceRange(), CallType);
4383 
4384   return false;
4385 }
4386 
4387 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4388 /// such as function pointers returned from functions.
4389 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4390   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4391                                                   TheCall->getCallee());
4392   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4393             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4394             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4395             TheCall->getCallee()->getSourceRange(), CallType);
4396 
4397   return false;
4398 }
4399 
4400 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4401   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4402     return false;
4403 
4404   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4405   switch (Op) {
4406   case AtomicExpr::AO__c11_atomic_init:
4407   case AtomicExpr::AO__opencl_atomic_init:
4408     llvm_unreachable("There is no ordering argument for an init");
4409 
4410   case AtomicExpr::AO__c11_atomic_load:
4411   case AtomicExpr::AO__opencl_atomic_load:
4412   case AtomicExpr::AO__atomic_load_n:
4413   case AtomicExpr::AO__atomic_load:
4414     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4415            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4416 
4417   case AtomicExpr::AO__c11_atomic_store:
4418   case AtomicExpr::AO__opencl_atomic_store:
4419   case AtomicExpr::AO__atomic_store:
4420   case AtomicExpr::AO__atomic_store_n:
4421     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4422            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4423            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4424 
4425   default:
4426     return true;
4427   }
4428 }
4429 
4430 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4431                                          AtomicExpr::AtomicOp Op) {
4432   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4433   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4434 
4435   // All the non-OpenCL operations take one of the following forms.
4436   // The OpenCL operations take the __c11 forms with one extra argument for
4437   // synchronization scope.
4438   enum {
4439     // C    __c11_atomic_init(A *, C)
4440     Init,
4441 
4442     // C    __c11_atomic_load(A *, int)
4443     Load,
4444 
4445     // void __atomic_load(A *, CP, int)
4446     LoadCopy,
4447 
4448     // void __atomic_store(A *, CP, int)
4449     Copy,
4450 
4451     // C    __c11_atomic_add(A *, M, int)
4452     Arithmetic,
4453 
4454     // C    __atomic_exchange_n(A *, CP, int)
4455     Xchg,
4456 
4457     // void __atomic_exchange(A *, C *, CP, int)
4458     GNUXchg,
4459 
4460     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4461     C11CmpXchg,
4462 
4463     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4464     GNUCmpXchg
4465   } Form = Init;
4466 
4467   const unsigned NumForm = GNUCmpXchg + 1;
4468   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4469   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4470   // where:
4471   //   C is an appropriate type,
4472   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4473   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4474   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4475   //   the int parameters are for orderings.
4476 
4477   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4478       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4479       "need to update code for modified forms");
4480   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4481                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4482                         AtomicExpr::AO__atomic_load,
4483                 "need to update code for modified C11 atomics");
4484   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4485                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4486   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4487                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4488                IsOpenCL;
4489   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4490              Op == AtomicExpr::AO__atomic_store_n ||
4491              Op == AtomicExpr::AO__atomic_exchange_n ||
4492              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4493   bool IsAddSub = false;
4494   bool IsMinMax = false;
4495 
4496   switch (Op) {
4497   case AtomicExpr::AO__c11_atomic_init:
4498   case AtomicExpr::AO__opencl_atomic_init:
4499     Form = Init;
4500     break;
4501 
4502   case AtomicExpr::AO__c11_atomic_load:
4503   case AtomicExpr::AO__opencl_atomic_load:
4504   case AtomicExpr::AO__atomic_load_n:
4505     Form = Load;
4506     break;
4507 
4508   case AtomicExpr::AO__atomic_load:
4509     Form = LoadCopy;
4510     break;
4511 
4512   case AtomicExpr::AO__c11_atomic_store:
4513   case AtomicExpr::AO__opencl_atomic_store:
4514   case AtomicExpr::AO__atomic_store:
4515   case AtomicExpr::AO__atomic_store_n:
4516     Form = Copy;
4517     break;
4518 
4519   case AtomicExpr::AO__c11_atomic_fetch_add:
4520   case AtomicExpr::AO__c11_atomic_fetch_sub:
4521   case AtomicExpr::AO__opencl_atomic_fetch_add:
4522   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4523   case AtomicExpr::AO__opencl_atomic_fetch_min:
4524   case AtomicExpr::AO__opencl_atomic_fetch_max:
4525   case AtomicExpr::AO__atomic_fetch_add:
4526   case AtomicExpr::AO__atomic_fetch_sub:
4527   case AtomicExpr::AO__atomic_add_fetch:
4528   case AtomicExpr::AO__atomic_sub_fetch:
4529     IsAddSub = true;
4530     LLVM_FALLTHROUGH;
4531   case AtomicExpr::AO__c11_atomic_fetch_and:
4532   case AtomicExpr::AO__c11_atomic_fetch_or:
4533   case AtomicExpr::AO__c11_atomic_fetch_xor:
4534   case AtomicExpr::AO__opencl_atomic_fetch_and:
4535   case AtomicExpr::AO__opencl_atomic_fetch_or:
4536   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4537   case AtomicExpr::AO__atomic_fetch_and:
4538   case AtomicExpr::AO__atomic_fetch_or:
4539   case AtomicExpr::AO__atomic_fetch_xor:
4540   case AtomicExpr::AO__atomic_fetch_nand:
4541   case AtomicExpr::AO__atomic_and_fetch:
4542   case AtomicExpr::AO__atomic_or_fetch:
4543   case AtomicExpr::AO__atomic_xor_fetch:
4544   case AtomicExpr::AO__atomic_nand_fetch:
4545     Form = Arithmetic;
4546     break;
4547 
4548   case AtomicExpr::AO__atomic_fetch_min:
4549   case AtomicExpr::AO__atomic_fetch_max:
4550     IsMinMax = true;
4551     Form = Arithmetic;
4552     break;
4553 
4554   case AtomicExpr::AO__c11_atomic_exchange:
4555   case AtomicExpr::AO__opencl_atomic_exchange:
4556   case AtomicExpr::AO__atomic_exchange_n:
4557     Form = Xchg;
4558     break;
4559 
4560   case AtomicExpr::AO__atomic_exchange:
4561     Form = GNUXchg;
4562     break;
4563 
4564   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4565   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4566   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4567   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4568     Form = C11CmpXchg;
4569     break;
4570 
4571   case AtomicExpr::AO__atomic_compare_exchange:
4572   case AtomicExpr::AO__atomic_compare_exchange_n:
4573     Form = GNUCmpXchg;
4574     break;
4575   }
4576 
4577   unsigned AdjustedNumArgs = NumArgs[Form];
4578   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4579     ++AdjustedNumArgs;
4580   // Check we have the right number of arguments.
4581   if (TheCall->getNumArgs() < AdjustedNumArgs) {
4582     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4583         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4584         << TheCall->getCallee()->getSourceRange();
4585     return ExprError();
4586   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
4587     Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
4588          diag::err_typecheck_call_too_many_args)
4589         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4590         << TheCall->getCallee()->getSourceRange();
4591     return ExprError();
4592   }
4593 
4594   // Inspect the first argument of the atomic operation.
4595   Expr *Ptr = TheCall->getArg(0);
4596   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4597   if (ConvertedPtr.isInvalid())
4598     return ExprError();
4599 
4600   Ptr = ConvertedPtr.get();
4601   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4602   if (!pointerType) {
4603     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4604         << Ptr->getType() << Ptr->getSourceRange();
4605     return ExprError();
4606   }
4607 
4608   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4609   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4610   QualType ValType = AtomTy; // 'C'
4611   if (IsC11) {
4612     if (!AtomTy->isAtomicType()) {
4613       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4614           << Ptr->getType() << Ptr->getSourceRange();
4615       return ExprError();
4616     }
4617     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4618         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4619       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
4620           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4621           << Ptr->getSourceRange();
4622       return ExprError();
4623     }
4624     ValType = AtomTy->getAs<AtomicType>()->getValueType();
4625   } else if (Form != Load && Form != LoadCopy) {
4626     if (ValType.isConstQualified()) {
4627       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4628           << Ptr->getType() << Ptr->getSourceRange();
4629       return ExprError();
4630     }
4631   }
4632 
4633   // For an arithmetic operation, the implied arithmetic must be well-formed.
4634   if (Form == Arithmetic) {
4635     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4636     if (IsAddSub && !ValType->isIntegerType()
4637         && !ValType->isPointerType()) {
4638       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4639           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4640       return ExprError();
4641     }
4642     if (IsMinMax) {
4643       const BuiltinType *BT = ValType->getAs<BuiltinType>();
4644       if (!BT || (BT->getKind() != BuiltinType::Int &&
4645                   BT->getKind() != BuiltinType::UInt)) {
4646         Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
4647         return ExprError();
4648       }
4649     }
4650     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4651       Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4652           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4653       return ExprError();
4654     }
4655     if (IsC11 && ValType->isPointerType() &&
4656         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4657                             diag::err_incomplete_type)) {
4658       return ExprError();
4659     }
4660   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4661     // For __atomic_*_n operations, the value type must be a scalar integral or
4662     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4663     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4664         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4665     return ExprError();
4666   }
4667 
4668   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4669       !AtomTy->isScalarType()) {
4670     // For GNU atomics, require a trivially-copyable type. This is not part of
4671     // the GNU atomics specification, but we enforce it for sanity.
4672     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4673         << Ptr->getType() << Ptr->getSourceRange();
4674     return ExprError();
4675   }
4676 
4677   switch (ValType.getObjCLifetime()) {
4678   case Qualifiers::OCL_None:
4679   case Qualifiers::OCL_ExplicitNone:
4680     // okay
4681     break;
4682 
4683   case Qualifiers::OCL_Weak:
4684   case Qualifiers::OCL_Strong:
4685   case Qualifiers::OCL_Autoreleasing:
4686     // FIXME: Can this happen? By this point, ValType should be known
4687     // to be trivially copyable.
4688     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4689         << ValType << Ptr->getSourceRange();
4690     return ExprError();
4691   }
4692 
4693   // All atomic operations have an overload which takes a pointer to a volatile
4694   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4695   // into the result or the other operands. Similarly atomic_load takes a
4696   // pointer to a const 'A'.
4697   ValType.removeLocalVolatile();
4698   ValType.removeLocalConst();
4699   QualType ResultType = ValType;
4700   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4701       Form == Init)
4702     ResultType = Context.VoidTy;
4703   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4704     ResultType = Context.BoolTy;
4705 
4706   // The type of a parameter passed 'by value'. In the GNU atomics, such
4707   // arguments are actually passed as pointers.
4708   QualType ByValType = ValType; // 'CP'
4709   bool IsPassedByAddress = false;
4710   if (!IsC11 && !IsN) {
4711     ByValType = Ptr->getType();
4712     IsPassedByAddress = true;
4713   }
4714 
4715   // The first argument's non-CV pointer type is used to deduce the type of
4716   // subsequent arguments, except for:
4717   //  - weak flag (always converted to bool)
4718   //  - memory order (always converted to int)
4719   //  - scope  (always converted to int)
4720   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4721     QualType Ty;
4722     if (i < NumVals[Form] + 1) {
4723       switch (i) {
4724       case 0:
4725         // The first argument is always a pointer. It has a fixed type.
4726         // It is always dereferenced, a nullptr is undefined.
4727         CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4728         // Nothing else to do: we already know all we want about this pointer.
4729         continue;
4730       case 1:
4731         // The second argument is the non-atomic operand. For arithmetic, this
4732         // is always passed by value, and for a compare_exchange it is always
4733         // passed by address. For the rest, GNU uses by-address and C11 uses
4734         // by-value.
4735         assert(Form != Load);
4736         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4737           Ty = ValType;
4738         else if (Form == Copy || Form == Xchg) {
4739           if (IsPassedByAddress)
4740             // The value pointer is always dereferenced, a nullptr is undefined.
4741             CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4742           Ty = ByValType;
4743         } else if (Form == Arithmetic)
4744           Ty = Context.getPointerDiffType();
4745         else {
4746           Expr *ValArg = TheCall->getArg(i);
4747           // The value pointer is always dereferenced, a nullptr is undefined.
4748           CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
4749           LangAS AS = LangAS::Default;
4750           // Keep address space of non-atomic pointer type.
4751           if (const PointerType *PtrTy =
4752                   ValArg->getType()->getAs<PointerType>()) {
4753             AS = PtrTy->getPointeeType().getAddressSpace();
4754           }
4755           Ty = Context.getPointerType(
4756               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4757         }
4758         break;
4759       case 2:
4760         // The third argument to compare_exchange / GNU exchange is the desired
4761         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4762         if (IsPassedByAddress)
4763           CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4764         Ty = ByValType;
4765         break;
4766       case 3:
4767         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4768         Ty = Context.BoolTy;
4769         break;
4770       }
4771     } else {
4772       // The order(s) and scope are always converted to int.
4773       Ty = Context.IntTy;
4774     }
4775 
4776     InitializedEntity Entity =
4777         InitializedEntity::InitializeParameter(Context, Ty, false);
4778     ExprResult Arg = TheCall->getArg(i);
4779     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4780     if (Arg.isInvalid())
4781       return true;
4782     TheCall->setArg(i, Arg.get());
4783   }
4784 
4785   // Permute the arguments into a 'consistent' order.
4786   SmallVector<Expr*, 5> SubExprs;
4787   SubExprs.push_back(Ptr);
4788   switch (Form) {
4789   case Init:
4790     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4791     SubExprs.push_back(TheCall->getArg(1)); // Val1
4792     break;
4793   case Load:
4794     SubExprs.push_back(TheCall->getArg(1)); // Order
4795     break;
4796   case LoadCopy:
4797   case Copy:
4798   case Arithmetic:
4799   case Xchg:
4800     SubExprs.push_back(TheCall->getArg(2)); // Order
4801     SubExprs.push_back(TheCall->getArg(1)); // Val1
4802     break;
4803   case GNUXchg:
4804     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4805     SubExprs.push_back(TheCall->getArg(3)); // Order
4806     SubExprs.push_back(TheCall->getArg(1)); // Val1
4807     SubExprs.push_back(TheCall->getArg(2)); // Val2
4808     break;
4809   case C11CmpXchg:
4810     SubExprs.push_back(TheCall->getArg(3)); // Order
4811     SubExprs.push_back(TheCall->getArg(1)); // Val1
4812     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
4813     SubExprs.push_back(TheCall->getArg(2)); // Val2
4814     break;
4815   case GNUCmpXchg:
4816     SubExprs.push_back(TheCall->getArg(4)); // Order
4817     SubExprs.push_back(TheCall->getArg(1)); // Val1
4818     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4819     SubExprs.push_back(TheCall->getArg(2)); // Val2
4820     SubExprs.push_back(TheCall->getArg(3)); // Weak
4821     break;
4822   }
4823 
4824   if (SubExprs.size() >= 2 && Form != Init) {
4825     llvm::APSInt Result(32);
4826     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4827         !isValidOrderingForOp(Result.getSExtValue(), Op))
4828       Diag(SubExprs[1]->getBeginLoc(),
4829            diag::warn_atomic_op_has_invalid_memory_order)
4830           << SubExprs[1]->getSourceRange();
4831   }
4832 
4833   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4834     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4835     llvm::APSInt Result(32);
4836     if (Scope->isIntegerConstantExpr(Result, Context) &&
4837         !ScopeModel->isValid(Result.getZExtValue())) {
4838       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4839           << Scope->getSourceRange();
4840     }
4841     SubExprs.push_back(Scope);
4842   }
4843 
4844   AtomicExpr *AE =
4845       new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4846                                ResultType, Op, TheCall->getRParenLoc());
4847 
4848   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4849        Op == AtomicExpr::AO__c11_atomic_store ||
4850        Op == AtomicExpr::AO__opencl_atomic_load ||
4851        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4852       Context.AtomicUsesUnsupportedLibcall(AE))
4853     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4854         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4855              Op == AtomicExpr::AO__opencl_atomic_load)
4856                 ? 0
4857                 : 1);
4858 
4859   return AE;
4860 }
4861 
4862 /// checkBuiltinArgument - Given a call to a builtin function, perform
4863 /// normal type-checking on the given argument, updating the call in
4864 /// place.  This is useful when a builtin function requires custom
4865 /// type-checking for some of its arguments but not necessarily all of
4866 /// them.
4867 ///
4868 /// Returns true on error.
4869 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4870   FunctionDecl *Fn = E->getDirectCallee();
4871   assert(Fn && "builtin call without direct callee!");
4872 
4873   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4874   InitializedEntity Entity =
4875     InitializedEntity::InitializeParameter(S.Context, Param);
4876 
4877   ExprResult Arg = E->getArg(0);
4878   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4879   if (Arg.isInvalid())
4880     return true;
4881 
4882   E->setArg(ArgIndex, Arg.get());
4883   return false;
4884 }
4885 
4886 /// We have a call to a function like __sync_fetch_and_add, which is an
4887 /// overloaded function based on the pointer type of its first argument.
4888 /// The main BuildCallExpr routines have already promoted the types of
4889 /// arguments because all of these calls are prototyped as void(...).
4890 ///
4891 /// This function goes through and does final semantic checking for these
4892 /// builtins, as well as generating any warnings.
4893 ExprResult
4894 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4895   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4896   Expr *Callee = TheCall->getCallee();
4897   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4898   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4899 
4900   // Ensure that we have at least one argument to do type inference from.
4901   if (TheCall->getNumArgs() < 1) {
4902     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4903         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4904     return ExprError();
4905   }
4906 
4907   // Inspect the first argument of the atomic builtin.  This should always be
4908   // a pointer type, whose element is an integral scalar or pointer type.
4909   // Because it is a pointer type, we don't have to worry about any implicit
4910   // casts here.
4911   // FIXME: We don't allow floating point scalars as input.
4912   Expr *FirstArg = TheCall->getArg(0);
4913   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4914   if (FirstArgResult.isInvalid())
4915     return ExprError();
4916   FirstArg = FirstArgResult.get();
4917   TheCall->setArg(0, FirstArg);
4918 
4919   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4920   if (!pointerType) {
4921     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4922         << FirstArg->getType() << FirstArg->getSourceRange();
4923     return ExprError();
4924   }
4925 
4926   QualType ValType = pointerType->getPointeeType();
4927   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4928       !ValType->isBlockPointerType()) {
4929     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4930         << FirstArg->getType() << FirstArg->getSourceRange();
4931     return ExprError();
4932   }
4933 
4934   if (ValType.isConstQualified()) {
4935     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4936         << FirstArg->getType() << FirstArg->getSourceRange();
4937     return ExprError();
4938   }
4939 
4940   switch (ValType.getObjCLifetime()) {
4941   case Qualifiers::OCL_None:
4942   case Qualifiers::OCL_ExplicitNone:
4943     // okay
4944     break;
4945 
4946   case Qualifiers::OCL_Weak:
4947   case Qualifiers::OCL_Strong:
4948   case Qualifiers::OCL_Autoreleasing:
4949     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4950         << ValType << FirstArg->getSourceRange();
4951     return ExprError();
4952   }
4953 
4954   // Strip any qualifiers off ValType.
4955   ValType = ValType.getUnqualifiedType();
4956 
4957   // The majority of builtins return a value, but a few have special return
4958   // types, so allow them to override appropriately below.
4959   QualType ResultType = ValType;
4960 
4961   // We need to figure out which concrete builtin this maps onto.  For example,
4962   // __sync_fetch_and_add with a 2 byte object turns into
4963   // __sync_fetch_and_add_2.
4964 #define BUILTIN_ROW(x) \
4965   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4966     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4967 
4968   static const unsigned BuiltinIndices[][5] = {
4969     BUILTIN_ROW(__sync_fetch_and_add),
4970     BUILTIN_ROW(__sync_fetch_and_sub),
4971     BUILTIN_ROW(__sync_fetch_and_or),
4972     BUILTIN_ROW(__sync_fetch_and_and),
4973     BUILTIN_ROW(__sync_fetch_and_xor),
4974     BUILTIN_ROW(__sync_fetch_and_nand),
4975 
4976     BUILTIN_ROW(__sync_add_and_fetch),
4977     BUILTIN_ROW(__sync_sub_and_fetch),
4978     BUILTIN_ROW(__sync_and_and_fetch),
4979     BUILTIN_ROW(__sync_or_and_fetch),
4980     BUILTIN_ROW(__sync_xor_and_fetch),
4981     BUILTIN_ROW(__sync_nand_and_fetch),
4982 
4983     BUILTIN_ROW(__sync_val_compare_and_swap),
4984     BUILTIN_ROW(__sync_bool_compare_and_swap),
4985     BUILTIN_ROW(__sync_lock_test_and_set),
4986     BUILTIN_ROW(__sync_lock_release),
4987     BUILTIN_ROW(__sync_swap)
4988   };
4989 #undef BUILTIN_ROW
4990 
4991   // Determine the index of the size.
4992   unsigned SizeIndex;
4993   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4994   case 1: SizeIndex = 0; break;
4995   case 2: SizeIndex = 1; break;
4996   case 4: SizeIndex = 2; break;
4997   case 8: SizeIndex = 3; break;
4998   case 16: SizeIndex = 4; break;
4999   default:
5000     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5001         << FirstArg->getType() << FirstArg->getSourceRange();
5002     return ExprError();
5003   }
5004 
5005   // Each of these builtins has one pointer argument, followed by some number of
5006   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5007   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5008   // as the number of fixed args.
5009   unsigned BuiltinID = FDecl->getBuiltinID();
5010   unsigned BuiltinIndex, NumFixed = 1;
5011   bool WarnAboutSemanticsChange = false;
5012   switch (BuiltinID) {
5013   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5014   case Builtin::BI__sync_fetch_and_add:
5015   case Builtin::BI__sync_fetch_and_add_1:
5016   case Builtin::BI__sync_fetch_and_add_2:
5017   case Builtin::BI__sync_fetch_and_add_4:
5018   case Builtin::BI__sync_fetch_and_add_8:
5019   case Builtin::BI__sync_fetch_and_add_16:
5020     BuiltinIndex = 0;
5021     break;
5022 
5023   case Builtin::BI__sync_fetch_and_sub:
5024   case Builtin::BI__sync_fetch_and_sub_1:
5025   case Builtin::BI__sync_fetch_and_sub_2:
5026   case Builtin::BI__sync_fetch_and_sub_4:
5027   case Builtin::BI__sync_fetch_and_sub_8:
5028   case Builtin::BI__sync_fetch_and_sub_16:
5029     BuiltinIndex = 1;
5030     break;
5031 
5032   case Builtin::BI__sync_fetch_and_or:
5033   case Builtin::BI__sync_fetch_and_or_1:
5034   case Builtin::BI__sync_fetch_and_or_2:
5035   case Builtin::BI__sync_fetch_and_or_4:
5036   case Builtin::BI__sync_fetch_and_or_8:
5037   case Builtin::BI__sync_fetch_and_or_16:
5038     BuiltinIndex = 2;
5039     break;
5040 
5041   case Builtin::BI__sync_fetch_and_and:
5042   case Builtin::BI__sync_fetch_and_and_1:
5043   case Builtin::BI__sync_fetch_and_and_2:
5044   case Builtin::BI__sync_fetch_and_and_4:
5045   case Builtin::BI__sync_fetch_and_and_8:
5046   case Builtin::BI__sync_fetch_and_and_16:
5047     BuiltinIndex = 3;
5048     break;
5049 
5050   case Builtin::BI__sync_fetch_and_xor:
5051   case Builtin::BI__sync_fetch_and_xor_1:
5052   case Builtin::BI__sync_fetch_and_xor_2:
5053   case Builtin::BI__sync_fetch_and_xor_4:
5054   case Builtin::BI__sync_fetch_and_xor_8:
5055   case Builtin::BI__sync_fetch_and_xor_16:
5056     BuiltinIndex = 4;
5057     break;
5058 
5059   case Builtin::BI__sync_fetch_and_nand:
5060   case Builtin::BI__sync_fetch_and_nand_1:
5061   case Builtin::BI__sync_fetch_and_nand_2:
5062   case Builtin::BI__sync_fetch_and_nand_4:
5063   case Builtin::BI__sync_fetch_and_nand_8:
5064   case Builtin::BI__sync_fetch_and_nand_16:
5065     BuiltinIndex = 5;
5066     WarnAboutSemanticsChange = true;
5067     break;
5068 
5069   case Builtin::BI__sync_add_and_fetch:
5070   case Builtin::BI__sync_add_and_fetch_1:
5071   case Builtin::BI__sync_add_and_fetch_2:
5072   case Builtin::BI__sync_add_and_fetch_4:
5073   case Builtin::BI__sync_add_and_fetch_8:
5074   case Builtin::BI__sync_add_and_fetch_16:
5075     BuiltinIndex = 6;
5076     break;
5077 
5078   case Builtin::BI__sync_sub_and_fetch:
5079   case Builtin::BI__sync_sub_and_fetch_1:
5080   case Builtin::BI__sync_sub_and_fetch_2:
5081   case Builtin::BI__sync_sub_and_fetch_4:
5082   case Builtin::BI__sync_sub_and_fetch_8:
5083   case Builtin::BI__sync_sub_and_fetch_16:
5084     BuiltinIndex = 7;
5085     break;
5086 
5087   case Builtin::BI__sync_and_and_fetch:
5088   case Builtin::BI__sync_and_and_fetch_1:
5089   case Builtin::BI__sync_and_and_fetch_2:
5090   case Builtin::BI__sync_and_and_fetch_4:
5091   case Builtin::BI__sync_and_and_fetch_8:
5092   case Builtin::BI__sync_and_and_fetch_16:
5093     BuiltinIndex = 8;
5094     break;
5095 
5096   case Builtin::BI__sync_or_and_fetch:
5097   case Builtin::BI__sync_or_and_fetch_1:
5098   case Builtin::BI__sync_or_and_fetch_2:
5099   case Builtin::BI__sync_or_and_fetch_4:
5100   case Builtin::BI__sync_or_and_fetch_8:
5101   case Builtin::BI__sync_or_and_fetch_16:
5102     BuiltinIndex = 9;
5103     break;
5104 
5105   case Builtin::BI__sync_xor_and_fetch:
5106   case Builtin::BI__sync_xor_and_fetch_1:
5107   case Builtin::BI__sync_xor_and_fetch_2:
5108   case Builtin::BI__sync_xor_and_fetch_4:
5109   case Builtin::BI__sync_xor_and_fetch_8:
5110   case Builtin::BI__sync_xor_and_fetch_16:
5111     BuiltinIndex = 10;
5112     break;
5113 
5114   case Builtin::BI__sync_nand_and_fetch:
5115   case Builtin::BI__sync_nand_and_fetch_1:
5116   case Builtin::BI__sync_nand_and_fetch_2:
5117   case Builtin::BI__sync_nand_and_fetch_4:
5118   case Builtin::BI__sync_nand_and_fetch_8:
5119   case Builtin::BI__sync_nand_and_fetch_16:
5120     BuiltinIndex = 11;
5121     WarnAboutSemanticsChange = true;
5122     break;
5123 
5124   case Builtin::BI__sync_val_compare_and_swap:
5125   case Builtin::BI__sync_val_compare_and_swap_1:
5126   case Builtin::BI__sync_val_compare_and_swap_2:
5127   case Builtin::BI__sync_val_compare_and_swap_4:
5128   case Builtin::BI__sync_val_compare_and_swap_8:
5129   case Builtin::BI__sync_val_compare_and_swap_16:
5130     BuiltinIndex = 12;
5131     NumFixed = 2;
5132     break;
5133 
5134   case Builtin::BI__sync_bool_compare_and_swap:
5135   case Builtin::BI__sync_bool_compare_and_swap_1:
5136   case Builtin::BI__sync_bool_compare_and_swap_2:
5137   case Builtin::BI__sync_bool_compare_and_swap_4:
5138   case Builtin::BI__sync_bool_compare_and_swap_8:
5139   case Builtin::BI__sync_bool_compare_and_swap_16:
5140     BuiltinIndex = 13;
5141     NumFixed = 2;
5142     ResultType = Context.BoolTy;
5143     break;
5144 
5145   case Builtin::BI__sync_lock_test_and_set:
5146   case Builtin::BI__sync_lock_test_and_set_1:
5147   case Builtin::BI__sync_lock_test_and_set_2:
5148   case Builtin::BI__sync_lock_test_and_set_4:
5149   case Builtin::BI__sync_lock_test_and_set_8:
5150   case Builtin::BI__sync_lock_test_and_set_16:
5151     BuiltinIndex = 14;
5152     break;
5153 
5154   case Builtin::BI__sync_lock_release:
5155   case Builtin::BI__sync_lock_release_1:
5156   case Builtin::BI__sync_lock_release_2:
5157   case Builtin::BI__sync_lock_release_4:
5158   case Builtin::BI__sync_lock_release_8:
5159   case Builtin::BI__sync_lock_release_16:
5160     BuiltinIndex = 15;
5161     NumFixed = 0;
5162     ResultType = Context.VoidTy;
5163     break;
5164 
5165   case Builtin::BI__sync_swap:
5166   case Builtin::BI__sync_swap_1:
5167   case Builtin::BI__sync_swap_2:
5168   case Builtin::BI__sync_swap_4:
5169   case Builtin::BI__sync_swap_8:
5170   case Builtin::BI__sync_swap_16:
5171     BuiltinIndex = 16;
5172     break;
5173   }
5174 
5175   // Now that we know how many fixed arguments we expect, first check that we
5176   // have at least that many.
5177   if (TheCall->getNumArgs() < 1+NumFixed) {
5178     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5179         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5180         << Callee->getSourceRange();
5181     return ExprError();
5182   }
5183 
5184   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5185       << Callee->getSourceRange();
5186 
5187   if (WarnAboutSemanticsChange) {
5188     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5189         << Callee->getSourceRange();
5190   }
5191 
5192   // Get the decl for the concrete builtin from this, we can tell what the
5193   // concrete integer type we should convert to is.
5194   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5195   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5196   FunctionDecl *NewBuiltinDecl;
5197   if (NewBuiltinID == BuiltinID)
5198     NewBuiltinDecl = FDecl;
5199   else {
5200     // Perform builtin lookup to avoid redeclaring it.
5201     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5202     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5203     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5204     assert(Res.getFoundDecl());
5205     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5206     if (!NewBuiltinDecl)
5207       return ExprError();
5208   }
5209 
5210   // The first argument --- the pointer --- has a fixed type; we
5211   // deduce the types of the rest of the arguments accordingly.  Walk
5212   // the remaining arguments, converting them to the deduced value type.
5213   for (unsigned i = 0; i != NumFixed; ++i) {
5214     ExprResult Arg = TheCall->getArg(i+1);
5215 
5216     // GCC does an implicit conversion to the pointer or integer ValType.  This
5217     // can fail in some cases (1i -> int**), check for this error case now.
5218     // Initialize the argument.
5219     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5220                                                    ValType, /*consume*/ false);
5221     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5222     if (Arg.isInvalid())
5223       return ExprError();
5224 
5225     // Okay, we have something that *can* be converted to the right type.  Check
5226     // to see if there is a potentially weird extension going on here.  This can
5227     // happen when you do an atomic operation on something like an char* and
5228     // pass in 42.  The 42 gets converted to char.  This is even more strange
5229     // for things like 45.123 -> char, etc.
5230     // FIXME: Do this check.
5231     TheCall->setArg(i+1, Arg.get());
5232   }
5233 
5234   // Create a new DeclRefExpr to refer to the new decl.
5235   DeclRefExpr* NewDRE = DeclRefExpr::Create(
5236       Context,
5237       DRE->getQualifierLoc(),
5238       SourceLocation(),
5239       NewBuiltinDecl,
5240       /*enclosing*/ false,
5241       DRE->getLocation(),
5242       Context.BuiltinFnTy,
5243       DRE->getValueKind());
5244 
5245   // Set the callee in the CallExpr.
5246   // FIXME: This loses syntactic information.
5247   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5248   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5249                                               CK_BuiltinFnToFnPtr);
5250   TheCall->setCallee(PromotedCall.get());
5251 
5252   // Change the result type of the call to match the original value type. This
5253   // is arbitrary, but the codegen for these builtins ins design to handle it
5254   // gracefully.
5255   TheCall->setType(ResultType);
5256 
5257   return TheCallResult;
5258 }
5259 
5260 /// SemaBuiltinNontemporalOverloaded - We have a call to
5261 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5262 /// overloaded function based on the pointer type of its last argument.
5263 ///
5264 /// This function goes through and does final semantic checking for these
5265 /// builtins.
5266 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5267   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5268   DeclRefExpr *DRE =
5269       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5270   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5271   unsigned BuiltinID = FDecl->getBuiltinID();
5272   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5273           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5274          "Unexpected nontemporal load/store builtin!");
5275   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5276   unsigned numArgs = isStore ? 2 : 1;
5277 
5278   // Ensure that we have the proper number of arguments.
5279   if (checkArgCount(*this, TheCall, numArgs))
5280     return ExprError();
5281 
5282   // Inspect the last argument of the nontemporal builtin.  This should always
5283   // be a pointer type, from which we imply the type of the memory access.
5284   // Because it is a pointer type, we don't have to worry about any implicit
5285   // casts here.
5286   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5287   ExprResult PointerArgResult =
5288       DefaultFunctionArrayLvalueConversion(PointerArg);
5289 
5290   if (PointerArgResult.isInvalid())
5291     return ExprError();
5292   PointerArg = PointerArgResult.get();
5293   TheCall->setArg(numArgs - 1, PointerArg);
5294 
5295   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5296   if (!pointerType) {
5297     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5298         << PointerArg->getType() << PointerArg->getSourceRange();
5299     return ExprError();
5300   }
5301 
5302   QualType ValType = pointerType->getPointeeType();
5303 
5304   // Strip any qualifiers off ValType.
5305   ValType = ValType.getUnqualifiedType();
5306   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5307       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5308       !ValType->isVectorType()) {
5309     Diag(DRE->getBeginLoc(),
5310          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5311         << PointerArg->getType() << PointerArg->getSourceRange();
5312     return ExprError();
5313   }
5314 
5315   if (!isStore) {
5316     TheCall->setType(ValType);
5317     return TheCallResult;
5318   }
5319 
5320   ExprResult ValArg = TheCall->getArg(0);
5321   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5322       Context, ValType, /*consume*/ false);
5323   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5324   if (ValArg.isInvalid())
5325     return ExprError();
5326 
5327   TheCall->setArg(0, ValArg.get());
5328   TheCall->setType(Context.VoidTy);
5329   return TheCallResult;
5330 }
5331 
5332 /// CheckObjCString - Checks that the argument to the builtin
5333 /// CFString constructor is correct
5334 /// Note: It might also make sense to do the UTF-16 conversion here (would
5335 /// simplify the backend).
5336 bool Sema::CheckObjCString(Expr *Arg) {
5337   Arg = Arg->IgnoreParenCasts();
5338   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5339 
5340   if (!Literal || !Literal->isAscii()) {
5341     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5342         << Arg->getSourceRange();
5343     return true;
5344   }
5345 
5346   if (Literal->containsNonAsciiOrNull()) {
5347     StringRef String = Literal->getString();
5348     unsigned NumBytes = String.size();
5349     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5350     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5351     llvm::UTF16 *ToPtr = &ToBuf[0];
5352 
5353     llvm::ConversionResult Result =
5354         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5355                                  ToPtr + NumBytes, llvm::strictConversion);
5356     // Check for conversion failure.
5357     if (Result != llvm::conversionOK)
5358       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5359           << Arg->getSourceRange();
5360   }
5361   return false;
5362 }
5363 
5364 /// CheckObjCString - Checks that the format string argument to the os_log()
5365 /// and os_trace() functions is correct, and converts it to const char *.
5366 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5367   Arg = Arg->IgnoreParenCasts();
5368   auto *Literal = dyn_cast<StringLiteral>(Arg);
5369   if (!Literal) {
5370     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5371       Literal = ObjcLiteral->getString();
5372     }
5373   }
5374 
5375   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5376     return ExprError(
5377         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5378         << Arg->getSourceRange());
5379   }
5380 
5381   ExprResult Result(Literal);
5382   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5383   InitializedEntity Entity =
5384       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5385   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5386   return Result;
5387 }
5388 
5389 /// Check that the user is calling the appropriate va_start builtin for the
5390 /// target and calling convention.
5391 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5392   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5393   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5394   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5395   bool IsWindows = TT.isOSWindows();
5396   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5397   if (IsX64 || IsAArch64) {
5398     CallingConv CC = CC_C;
5399     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5400       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5401     if (IsMSVAStart) {
5402       // Don't allow this in System V ABI functions.
5403       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5404         return S.Diag(Fn->getBeginLoc(),
5405                       diag::err_ms_va_start_used_in_sysv_function);
5406     } else {
5407       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5408       // On x64 Windows, don't allow this in System V ABI functions.
5409       // (Yes, that means there's no corresponding way to support variadic
5410       // System V ABI functions on Windows.)
5411       if ((IsWindows && CC == CC_X86_64SysV) ||
5412           (!IsWindows && CC == CC_Win64))
5413         return S.Diag(Fn->getBeginLoc(),
5414                       diag::err_va_start_used_in_wrong_abi_function)
5415                << !IsWindows;
5416     }
5417     return false;
5418   }
5419 
5420   if (IsMSVAStart)
5421     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5422   return false;
5423 }
5424 
5425 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5426                                              ParmVarDecl **LastParam = nullptr) {
5427   // Determine whether the current function, block, or obj-c method is variadic
5428   // and get its parameter list.
5429   bool IsVariadic = false;
5430   ArrayRef<ParmVarDecl *> Params;
5431   DeclContext *Caller = S.CurContext;
5432   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5433     IsVariadic = Block->isVariadic();
5434     Params = Block->parameters();
5435   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5436     IsVariadic = FD->isVariadic();
5437     Params = FD->parameters();
5438   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5439     IsVariadic = MD->isVariadic();
5440     // FIXME: This isn't correct for methods (results in bogus warning).
5441     Params = MD->parameters();
5442   } else if (isa<CapturedDecl>(Caller)) {
5443     // We don't support va_start in a CapturedDecl.
5444     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5445     return true;
5446   } else {
5447     // This must be some other declcontext that parses exprs.
5448     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5449     return true;
5450   }
5451 
5452   if (!IsVariadic) {
5453     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5454     return true;
5455   }
5456 
5457   if (LastParam)
5458     *LastParam = Params.empty() ? nullptr : Params.back();
5459 
5460   return false;
5461 }
5462 
5463 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5464 /// for validity.  Emit an error and return true on failure; return false
5465 /// on success.
5466 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5467   Expr *Fn = TheCall->getCallee();
5468 
5469   if (checkVAStartABI(*this, BuiltinID, Fn))
5470     return true;
5471 
5472   if (TheCall->getNumArgs() > 2) {
5473     Diag(TheCall->getArg(2)->getBeginLoc(),
5474          diag::err_typecheck_call_too_many_args)
5475         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5476         << Fn->getSourceRange()
5477         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5478                        (*(TheCall->arg_end() - 1))->getEndLoc());
5479     return true;
5480   }
5481 
5482   if (TheCall->getNumArgs() < 2) {
5483     return Diag(TheCall->getEndLoc(),
5484                 diag::err_typecheck_call_too_few_args_at_least)
5485            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5486   }
5487 
5488   // Type-check the first argument normally.
5489   if (checkBuiltinArgument(*this, TheCall, 0))
5490     return true;
5491 
5492   // Check that the current function is variadic, and get its last parameter.
5493   ParmVarDecl *LastParam;
5494   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5495     return true;
5496 
5497   // Verify that the second argument to the builtin is the last argument of the
5498   // current function or method.
5499   bool SecondArgIsLastNamedArgument = false;
5500   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5501 
5502   // These are valid if SecondArgIsLastNamedArgument is false after the next
5503   // block.
5504   QualType Type;
5505   SourceLocation ParamLoc;
5506   bool IsCRegister = false;
5507 
5508   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5509     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5510       SecondArgIsLastNamedArgument = PV == LastParam;
5511 
5512       Type = PV->getType();
5513       ParamLoc = PV->getLocation();
5514       IsCRegister =
5515           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5516     }
5517   }
5518 
5519   if (!SecondArgIsLastNamedArgument)
5520     Diag(TheCall->getArg(1)->getBeginLoc(),
5521          diag::warn_second_arg_of_va_start_not_last_named_param);
5522   else if (IsCRegister || Type->isReferenceType() ||
5523            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5524              // Promotable integers are UB, but enumerations need a bit of
5525              // extra checking to see what their promotable type actually is.
5526              if (!Type->isPromotableIntegerType())
5527                return false;
5528              if (!Type->isEnumeralType())
5529                return true;
5530              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5531              return !(ED &&
5532                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5533            }()) {
5534     unsigned Reason = 0;
5535     if (Type->isReferenceType())  Reason = 1;
5536     else if (IsCRegister)         Reason = 2;
5537     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5538     Diag(ParamLoc, diag::note_parameter_type) << Type;
5539   }
5540 
5541   TheCall->setType(Context.VoidTy);
5542   return false;
5543 }
5544 
5545 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5546   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5547   //                 const char *named_addr);
5548 
5549   Expr *Func = Call->getCallee();
5550 
5551   if (Call->getNumArgs() < 3)
5552     return Diag(Call->getEndLoc(),
5553                 diag::err_typecheck_call_too_few_args_at_least)
5554            << 0 /*function call*/ << 3 << Call->getNumArgs();
5555 
5556   // Type-check the first argument normally.
5557   if (checkBuiltinArgument(*this, Call, 0))
5558     return true;
5559 
5560   // Check that the current function is variadic.
5561   if (checkVAStartIsInVariadicFunction(*this, Func))
5562     return true;
5563 
5564   // __va_start on Windows does not validate the parameter qualifiers
5565 
5566   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5567   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5568 
5569   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5570   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5571 
5572   const QualType &ConstCharPtrTy =
5573       Context.getPointerType(Context.CharTy.withConst());
5574   if (!Arg1Ty->isPointerType() ||
5575       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5576     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5577         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5578         << 0                                      /* qualifier difference */
5579         << 3                                      /* parameter mismatch */
5580         << 2 << Arg1->getType() << ConstCharPtrTy;
5581 
5582   const QualType SizeTy = Context.getSizeType();
5583   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5584     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5585         << Arg2->getType() << SizeTy << 1 /* different class */
5586         << 0                              /* qualifier difference */
5587         << 3                              /* parameter mismatch */
5588         << 3 << Arg2->getType() << SizeTy;
5589 
5590   return false;
5591 }
5592 
5593 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5594 /// friends.  This is declared to take (...), so we have to check everything.
5595 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5596   if (TheCall->getNumArgs() < 2)
5597     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5598            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5599   if (TheCall->getNumArgs() > 2)
5600     return Diag(TheCall->getArg(2)->getBeginLoc(),
5601                 diag::err_typecheck_call_too_many_args)
5602            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5603            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5604                           (*(TheCall->arg_end() - 1))->getEndLoc());
5605 
5606   ExprResult OrigArg0 = TheCall->getArg(0);
5607   ExprResult OrigArg1 = TheCall->getArg(1);
5608 
5609   // Do standard promotions between the two arguments, returning their common
5610   // type.
5611   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5612   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5613     return true;
5614 
5615   // Make sure any conversions are pushed back into the call; this is
5616   // type safe since unordered compare builtins are declared as "_Bool
5617   // foo(...)".
5618   TheCall->setArg(0, OrigArg0.get());
5619   TheCall->setArg(1, OrigArg1.get());
5620 
5621   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5622     return false;
5623 
5624   // If the common type isn't a real floating type, then the arguments were
5625   // invalid for this operation.
5626   if (Res.isNull() || !Res->isRealFloatingType())
5627     return Diag(OrigArg0.get()->getBeginLoc(),
5628                 diag::err_typecheck_call_invalid_ordered_compare)
5629            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5630            << SourceRange(OrigArg0.get()->getBeginLoc(),
5631                           OrigArg1.get()->getEndLoc());
5632 
5633   return false;
5634 }
5635 
5636 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5637 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5638 /// to check everything. We expect the last argument to be a floating point
5639 /// value.
5640 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5641   if (TheCall->getNumArgs() < NumArgs)
5642     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5643            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5644   if (TheCall->getNumArgs() > NumArgs)
5645     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5646                 diag::err_typecheck_call_too_many_args)
5647            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5648            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5649                           (*(TheCall->arg_end() - 1))->getEndLoc());
5650 
5651   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5652 
5653   if (OrigArg->isTypeDependent())
5654     return false;
5655 
5656   // This operation requires a non-_Complex floating-point number.
5657   if (!OrigArg->getType()->isRealFloatingType())
5658     return Diag(OrigArg->getBeginLoc(),
5659                 diag::err_typecheck_call_invalid_unary_fp)
5660            << OrigArg->getType() << OrigArg->getSourceRange();
5661 
5662   // If this is an implicit conversion from float -> float, double, or
5663   // long double, remove it.
5664   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5665     // Only remove standard FloatCasts, leaving other casts inplace
5666     if (Cast->getCastKind() == CK_FloatingCast) {
5667       Expr *CastArg = Cast->getSubExpr();
5668       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5669         assert(
5670             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5671              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5672              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5673             "promotion from float to either float, double, or long double is "
5674             "the only expected cast here");
5675         Cast->setSubExpr(nullptr);
5676         TheCall->setArg(NumArgs-1, CastArg);
5677       }
5678     }
5679   }
5680 
5681   return false;
5682 }
5683 
5684 // Customized Sema Checking for VSX builtins that have the following signature:
5685 // vector [...] builtinName(vector [...], vector [...], const int);
5686 // Which takes the same type of vectors (any legal vector type) for the first
5687 // two arguments and takes compile time constant for the third argument.
5688 // Example builtins are :
5689 // vector double vec_xxpermdi(vector double, vector double, int);
5690 // vector short vec_xxsldwi(vector short, vector short, int);
5691 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5692   unsigned ExpectedNumArgs = 3;
5693   if (TheCall->getNumArgs() < ExpectedNumArgs)
5694     return Diag(TheCall->getEndLoc(),
5695                 diag::err_typecheck_call_too_few_args_at_least)
5696            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5697            << TheCall->getSourceRange();
5698 
5699   if (TheCall->getNumArgs() > ExpectedNumArgs)
5700     return Diag(TheCall->getEndLoc(),
5701                 diag::err_typecheck_call_too_many_args_at_most)
5702            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5703            << TheCall->getSourceRange();
5704 
5705   // Check the third argument is a compile time constant
5706   llvm::APSInt Value;
5707   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5708     return Diag(TheCall->getBeginLoc(),
5709                 diag::err_vsx_builtin_nonconstant_argument)
5710            << 3 /* argument index */ << TheCall->getDirectCallee()
5711            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5712                           TheCall->getArg(2)->getEndLoc());
5713 
5714   QualType Arg1Ty = TheCall->getArg(0)->getType();
5715   QualType Arg2Ty = TheCall->getArg(1)->getType();
5716 
5717   // Check the type of argument 1 and argument 2 are vectors.
5718   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5719   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5720       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5721     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5722            << TheCall->getDirectCallee()
5723            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5724                           TheCall->getArg(1)->getEndLoc());
5725   }
5726 
5727   // Check the first two arguments are the same type.
5728   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5729     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5730            << TheCall->getDirectCallee()
5731            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5732                           TheCall->getArg(1)->getEndLoc());
5733   }
5734 
5735   // When default clang type checking is turned off and the customized type
5736   // checking is used, the returning type of the function must be explicitly
5737   // set. Otherwise it is _Bool by default.
5738   TheCall->setType(Arg1Ty);
5739 
5740   return false;
5741 }
5742 
5743 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5744 // This is declared to take (...), so we have to check everything.
5745 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5746   if (TheCall->getNumArgs() < 2)
5747     return ExprError(Diag(TheCall->getEndLoc(),
5748                           diag::err_typecheck_call_too_few_args_at_least)
5749                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5750                      << TheCall->getSourceRange());
5751 
5752   // Determine which of the following types of shufflevector we're checking:
5753   // 1) unary, vector mask: (lhs, mask)
5754   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5755   QualType resType = TheCall->getArg(0)->getType();
5756   unsigned numElements = 0;
5757 
5758   if (!TheCall->getArg(0)->isTypeDependent() &&
5759       !TheCall->getArg(1)->isTypeDependent()) {
5760     QualType LHSType = TheCall->getArg(0)->getType();
5761     QualType RHSType = TheCall->getArg(1)->getType();
5762 
5763     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5764       return ExprError(
5765           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5766           << TheCall->getDirectCallee()
5767           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5768                          TheCall->getArg(1)->getEndLoc()));
5769 
5770     numElements = LHSType->getAs<VectorType>()->getNumElements();
5771     unsigned numResElements = TheCall->getNumArgs() - 2;
5772 
5773     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5774     // with mask.  If so, verify that RHS is an integer vector type with the
5775     // same number of elts as lhs.
5776     if (TheCall->getNumArgs() == 2) {
5777       if (!RHSType->hasIntegerRepresentation() ||
5778           RHSType->getAs<VectorType>()->getNumElements() != numElements)
5779         return ExprError(Diag(TheCall->getBeginLoc(),
5780                               diag::err_vec_builtin_incompatible_vector)
5781                          << TheCall->getDirectCallee()
5782                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5783                                         TheCall->getArg(1)->getEndLoc()));
5784     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5785       return ExprError(Diag(TheCall->getBeginLoc(),
5786                             diag::err_vec_builtin_incompatible_vector)
5787                        << TheCall->getDirectCallee()
5788                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5789                                       TheCall->getArg(1)->getEndLoc()));
5790     } else if (numElements != numResElements) {
5791       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5792       resType = Context.getVectorType(eltType, numResElements,
5793                                       VectorType::GenericVector);
5794     }
5795   }
5796 
5797   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5798     if (TheCall->getArg(i)->isTypeDependent() ||
5799         TheCall->getArg(i)->isValueDependent())
5800       continue;
5801 
5802     llvm::APSInt Result(32);
5803     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5804       return ExprError(Diag(TheCall->getBeginLoc(),
5805                             diag::err_shufflevector_nonconstant_argument)
5806                        << TheCall->getArg(i)->getSourceRange());
5807 
5808     // Allow -1 which will be translated to undef in the IR.
5809     if (Result.isSigned() && Result.isAllOnesValue())
5810       continue;
5811 
5812     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5813       return ExprError(Diag(TheCall->getBeginLoc(),
5814                             diag::err_shufflevector_argument_too_large)
5815                        << TheCall->getArg(i)->getSourceRange());
5816   }
5817 
5818   SmallVector<Expr*, 32> exprs;
5819 
5820   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5821     exprs.push_back(TheCall->getArg(i));
5822     TheCall->setArg(i, nullptr);
5823   }
5824 
5825   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5826                                          TheCall->getCallee()->getBeginLoc(),
5827                                          TheCall->getRParenLoc());
5828 }
5829 
5830 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5831 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5832                                        SourceLocation BuiltinLoc,
5833                                        SourceLocation RParenLoc) {
5834   ExprValueKind VK = VK_RValue;
5835   ExprObjectKind OK = OK_Ordinary;
5836   QualType DstTy = TInfo->getType();
5837   QualType SrcTy = E->getType();
5838 
5839   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5840     return ExprError(Diag(BuiltinLoc,
5841                           diag::err_convertvector_non_vector)
5842                      << E->getSourceRange());
5843   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5844     return ExprError(Diag(BuiltinLoc,
5845                           diag::err_convertvector_non_vector_type));
5846 
5847   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5848     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5849     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5850     if (SrcElts != DstElts)
5851       return ExprError(Diag(BuiltinLoc,
5852                             diag::err_convertvector_incompatible_vector)
5853                        << E->getSourceRange());
5854   }
5855 
5856   return new (Context)
5857       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5858 }
5859 
5860 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5861 // This is declared to take (const void*, ...) and can take two
5862 // optional constant int args.
5863 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5864   unsigned NumArgs = TheCall->getNumArgs();
5865 
5866   if (NumArgs > 3)
5867     return Diag(TheCall->getEndLoc(),
5868                 diag::err_typecheck_call_too_many_args_at_most)
5869            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5870 
5871   // Argument 0 is checked for us and the remaining arguments must be
5872   // constant integers.
5873   for (unsigned i = 1; i != NumArgs; ++i)
5874     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5875       return true;
5876 
5877   return false;
5878 }
5879 
5880 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5881 // __assume does not evaluate its arguments, and should warn if its argument
5882 // has side effects.
5883 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5884   Expr *Arg = TheCall->getArg(0);
5885   if (Arg->isInstantiationDependent()) return false;
5886 
5887   if (Arg->HasSideEffects(Context))
5888     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5889         << Arg->getSourceRange()
5890         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5891 
5892   return false;
5893 }
5894 
5895 /// Handle __builtin_alloca_with_align. This is declared
5896 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5897 /// than 8.
5898 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5899   // The alignment must be a constant integer.
5900   Expr *Arg = TheCall->getArg(1);
5901 
5902   // We can't check the value of a dependent argument.
5903   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5904     if (const auto *UE =
5905             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5906       if (UE->getKind() == UETT_AlignOf ||
5907           UE->getKind() == UETT_PreferredAlignOf)
5908         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5909             << Arg->getSourceRange();
5910 
5911     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5912 
5913     if (!Result.isPowerOf2())
5914       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5915              << Arg->getSourceRange();
5916 
5917     if (Result < Context.getCharWidth())
5918       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5919              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5920 
5921     if (Result > std::numeric_limits<int32_t>::max())
5922       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5923              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5924   }
5925 
5926   return false;
5927 }
5928 
5929 /// Handle __builtin_assume_aligned. This is declared
5930 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5931 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5932   unsigned NumArgs = TheCall->getNumArgs();
5933 
5934   if (NumArgs > 3)
5935     return Diag(TheCall->getEndLoc(),
5936                 diag::err_typecheck_call_too_many_args_at_most)
5937            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5938 
5939   // The alignment must be a constant integer.
5940   Expr *Arg = TheCall->getArg(1);
5941 
5942   // We can't check the value of a dependent argument.
5943   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5944     llvm::APSInt Result;
5945     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5946       return true;
5947 
5948     if (!Result.isPowerOf2())
5949       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5950              << Arg->getSourceRange();
5951   }
5952 
5953   if (NumArgs > 2) {
5954     ExprResult Arg(TheCall->getArg(2));
5955     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5956       Context.getSizeType(), false);
5957     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5958     if (Arg.isInvalid()) return true;
5959     TheCall->setArg(2, Arg.get());
5960   }
5961 
5962   return false;
5963 }
5964 
5965 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5966   unsigned BuiltinID =
5967       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5968   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5969 
5970   unsigned NumArgs = TheCall->getNumArgs();
5971   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5972   if (NumArgs < NumRequiredArgs) {
5973     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5974            << 0 /* function call */ << NumRequiredArgs << NumArgs
5975            << TheCall->getSourceRange();
5976   }
5977   if (NumArgs >= NumRequiredArgs + 0x100) {
5978     return Diag(TheCall->getEndLoc(),
5979                 diag::err_typecheck_call_too_many_args_at_most)
5980            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5981            << TheCall->getSourceRange();
5982   }
5983   unsigned i = 0;
5984 
5985   // For formatting call, check buffer arg.
5986   if (!IsSizeCall) {
5987     ExprResult Arg(TheCall->getArg(i));
5988     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5989         Context, Context.VoidPtrTy, false);
5990     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5991     if (Arg.isInvalid())
5992       return true;
5993     TheCall->setArg(i, Arg.get());
5994     i++;
5995   }
5996 
5997   // Check string literal arg.
5998   unsigned FormatIdx = i;
5999   {
6000     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6001     if (Arg.isInvalid())
6002       return true;
6003     TheCall->setArg(i, Arg.get());
6004     i++;
6005   }
6006 
6007   // Make sure variadic args are scalar.
6008   unsigned FirstDataArg = i;
6009   while (i < NumArgs) {
6010     ExprResult Arg = DefaultVariadicArgumentPromotion(
6011         TheCall->getArg(i), VariadicFunction, nullptr);
6012     if (Arg.isInvalid())
6013       return true;
6014     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6015     if (ArgSize.getQuantity() >= 0x100) {
6016       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6017              << i << (int)ArgSize.getQuantity() << 0xff
6018              << TheCall->getSourceRange();
6019     }
6020     TheCall->setArg(i, Arg.get());
6021     i++;
6022   }
6023 
6024   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6025   // call to avoid duplicate diagnostics.
6026   if (!IsSizeCall) {
6027     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6028     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6029     bool Success = CheckFormatArguments(
6030         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6031         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6032         CheckedVarArgs);
6033     if (!Success)
6034       return true;
6035   }
6036 
6037   if (IsSizeCall) {
6038     TheCall->setType(Context.getSizeType());
6039   } else {
6040     TheCall->setType(Context.VoidPtrTy);
6041   }
6042   return false;
6043 }
6044 
6045 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6046 /// TheCall is a constant expression.
6047 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6048                                   llvm::APSInt &Result) {
6049   Expr *Arg = TheCall->getArg(ArgNum);
6050   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6051   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6052 
6053   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6054 
6055   if (!Arg->isIntegerConstantExpr(Result, Context))
6056     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6057            << FDecl->getDeclName() << Arg->getSourceRange();
6058 
6059   return false;
6060 }
6061 
6062 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6063 /// TheCall is a constant expression in the range [Low, High].
6064 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6065                                        int Low, int High, bool RangeIsError) {
6066   llvm::APSInt Result;
6067 
6068   // We can't check the value of a dependent argument.
6069   Expr *Arg = TheCall->getArg(ArgNum);
6070   if (Arg->isTypeDependent() || Arg->isValueDependent())
6071     return false;
6072 
6073   // Check constant-ness first.
6074   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6075     return true;
6076 
6077   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6078     if (RangeIsError)
6079       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6080              << Result.toString(10) << Low << High << Arg->getSourceRange();
6081     else
6082       // Defer the warning until we know if the code will be emitted so that
6083       // dead code can ignore this.
6084       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6085                           PDiag(diag::warn_argument_invalid_range)
6086                               << Result.toString(10) << Low << High
6087                               << Arg->getSourceRange());
6088   }
6089 
6090   return false;
6091 }
6092 
6093 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6094 /// TheCall is a constant expression is a multiple of Num..
6095 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6096                                           unsigned Num) {
6097   llvm::APSInt Result;
6098 
6099   // We can't check the value of a dependent argument.
6100   Expr *Arg = TheCall->getArg(ArgNum);
6101   if (Arg->isTypeDependent() || Arg->isValueDependent())
6102     return false;
6103 
6104   // Check constant-ness first.
6105   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6106     return true;
6107 
6108   if (Result.getSExtValue() % Num != 0)
6109     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6110            << Num << Arg->getSourceRange();
6111 
6112   return false;
6113 }
6114 
6115 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6116 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6117   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6118     if (checkArgCount(*this, TheCall, 2))
6119       return true;
6120     Expr *Arg0 = TheCall->getArg(0);
6121     Expr *Arg1 = TheCall->getArg(1);
6122 
6123     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6124     if (FirstArg.isInvalid())
6125       return true;
6126     QualType FirstArgType = FirstArg.get()->getType();
6127     if (!FirstArgType->isAnyPointerType())
6128       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6129                << "first" << FirstArgType << Arg0->getSourceRange();
6130     TheCall->setArg(0, FirstArg.get());
6131 
6132     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6133     if (SecArg.isInvalid())
6134       return true;
6135     QualType SecArgType = SecArg.get()->getType();
6136     if (!SecArgType->isIntegerType())
6137       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6138                << "second" << SecArgType << Arg1->getSourceRange();
6139 
6140     // Derive the return type from the pointer argument.
6141     TheCall->setType(FirstArgType);
6142     return false;
6143   }
6144 
6145   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6146     if (checkArgCount(*this, TheCall, 2))
6147       return true;
6148 
6149     Expr *Arg0 = TheCall->getArg(0);
6150     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6151     if (FirstArg.isInvalid())
6152       return true;
6153     QualType FirstArgType = FirstArg.get()->getType();
6154     if (!FirstArgType->isAnyPointerType())
6155       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6156                << "first" << FirstArgType << Arg0->getSourceRange();
6157     TheCall->setArg(0, FirstArg.get());
6158 
6159     // Derive the return type from the pointer argument.
6160     TheCall->setType(FirstArgType);
6161 
6162     // Second arg must be an constant in range [0,15]
6163     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6164   }
6165 
6166   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6167     if (checkArgCount(*this, TheCall, 2))
6168       return true;
6169     Expr *Arg0 = TheCall->getArg(0);
6170     Expr *Arg1 = TheCall->getArg(1);
6171 
6172     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6173     if (FirstArg.isInvalid())
6174       return true;
6175     QualType FirstArgType = FirstArg.get()->getType();
6176     if (!FirstArgType->isAnyPointerType())
6177       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6178                << "first" << FirstArgType << Arg0->getSourceRange();
6179 
6180     QualType SecArgType = Arg1->getType();
6181     if (!SecArgType->isIntegerType())
6182       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6183                << "second" << SecArgType << Arg1->getSourceRange();
6184     TheCall->setType(Context.IntTy);
6185     return false;
6186   }
6187 
6188   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6189       BuiltinID == AArch64::BI__builtin_arm_stg) {
6190     if (checkArgCount(*this, TheCall, 1))
6191       return true;
6192     Expr *Arg0 = TheCall->getArg(0);
6193     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6194     if (FirstArg.isInvalid())
6195       return true;
6196 
6197     QualType FirstArgType = FirstArg.get()->getType();
6198     if (!FirstArgType->isAnyPointerType())
6199       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6200                << "first" << FirstArgType << Arg0->getSourceRange();
6201     TheCall->setArg(0, FirstArg.get());
6202 
6203     // Derive the return type from the pointer argument.
6204     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6205       TheCall->setType(FirstArgType);
6206     return false;
6207   }
6208 
6209   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6210     Expr *ArgA = TheCall->getArg(0);
6211     Expr *ArgB = TheCall->getArg(1);
6212 
6213     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6214     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6215 
6216     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6217       return true;
6218 
6219     QualType ArgTypeA = ArgExprA.get()->getType();
6220     QualType ArgTypeB = ArgExprB.get()->getType();
6221 
6222     auto isNull = [&] (Expr *E) -> bool {
6223       return E->isNullPointerConstant(
6224                         Context, Expr::NPC_ValueDependentIsNotNull); };
6225 
6226     // argument should be either a pointer or null
6227     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6228       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6229         << "first" << ArgTypeA << ArgA->getSourceRange();
6230 
6231     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6232       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6233         << "second" << ArgTypeB << ArgB->getSourceRange();
6234 
6235     // Ensure Pointee types are compatible
6236     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6237         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6238       QualType pointeeA = ArgTypeA->getPointeeType();
6239       QualType pointeeB = ArgTypeB->getPointeeType();
6240       if (!Context.typesAreCompatible(
6241              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6242              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6243         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6244           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6245           << ArgB->getSourceRange();
6246       }
6247     }
6248 
6249     // at least one argument should be pointer type
6250     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6251       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6252         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6253 
6254     if (isNull(ArgA)) // adopt type of the other pointer
6255       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6256 
6257     if (isNull(ArgB))
6258       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6259 
6260     TheCall->setArg(0, ArgExprA.get());
6261     TheCall->setArg(1, ArgExprB.get());
6262     TheCall->setType(Context.LongLongTy);
6263     return false;
6264   }
6265   assert(false && "Unhandled ARM MTE intrinsic");
6266   return true;
6267 }
6268 
6269 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6270 /// TheCall is an ARM/AArch64 special register string literal.
6271 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6272                                     int ArgNum, unsigned ExpectedFieldNum,
6273                                     bool AllowName) {
6274   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6275                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6276                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6277                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6278                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6279                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6280   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6281                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6282                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6283                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6284                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6285                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6286   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6287 
6288   // We can't check the value of a dependent argument.
6289   Expr *Arg = TheCall->getArg(ArgNum);
6290   if (Arg->isTypeDependent() || Arg->isValueDependent())
6291     return false;
6292 
6293   // Check if the argument is a string literal.
6294   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6295     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6296            << Arg->getSourceRange();
6297 
6298   // Check the type of special register given.
6299   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6300   SmallVector<StringRef, 6> Fields;
6301   Reg.split(Fields, ":");
6302 
6303   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6304     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6305            << Arg->getSourceRange();
6306 
6307   // If the string is the name of a register then we cannot check that it is
6308   // valid here but if the string is of one the forms described in ACLE then we
6309   // can check that the supplied fields are integers and within the valid
6310   // ranges.
6311   if (Fields.size() > 1) {
6312     bool FiveFields = Fields.size() == 5;
6313 
6314     bool ValidString = true;
6315     if (IsARMBuiltin) {
6316       ValidString &= Fields[0].startswith_lower("cp") ||
6317                      Fields[0].startswith_lower("p");
6318       if (ValidString)
6319         Fields[0] =
6320           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6321 
6322       ValidString &= Fields[2].startswith_lower("c");
6323       if (ValidString)
6324         Fields[2] = Fields[2].drop_front(1);
6325 
6326       if (FiveFields) {
6327         ValidString &= Fields[3].startswith_lower("c");
6328         if (ValidString)
6329           Fields[3] = Fields[3].drop_front(1);
6330       }
6331     }
6332 
6333     SmallVector<int, 5> Ranges;
6334     if (FiveFields)
6335       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6336     else
6337       Ranges.append({15, 7, 15});
6338 
6339     for (unsigned i=0; i<Fields.size(); ++i) {
6340       int IntField;
6341       ValidString &= !Fields[i].getAsInteger(10, IntField);
6342       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6343     }
6344 
6345     if (!ValidString)
6346       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6347              << Arg->getSourceRange();
6348   } else if (IsAArch64Builtin && Fields.size() == 1) {
6349     // If the register name is one of those that appear in the condition below
6350     // and the special register builtin being used is one of the write builtins,
6351     // then we require that the argument provided for writing to the register
6352     // is an integer constant expression. This is because it will be lowered to
6353     // an MSR (immediate) instruction, so we need to know the immediate at
6354     // compile time.
6355     if (TheCall->getNumArgs() != 2)
6356       return false;
6357 
6358     std::string RegLower = Reg.lower();
6359     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6360         RegLower != "pan" && RegLower != "uao")
6361       return false;
6362 
6363     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6364   }
6365 
6366   return false;
6367 }
6368 
6369 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6370 /// This checks that the target supports __builtin_longjmp and
6371 /// that val is a constant 1.
6372 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6373   if (!Context.getTargetInfo().hasSjLjLowering())
6374     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6375            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6376 
6377   Expr *Arg = TheCall->getArg(1);
6378   llvm::APSInt Result;
6379 
6380   // TODO: This is less than ideal. Overload this to take a value.
6381   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6382     return true;
6383 
6384   if (Result != 1)
6385     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6386            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6387 
6388   return false;
6389 }
6390 
6391 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6392 /// This checks that the target supports __builtin_setjmp.
6393 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6394   if (!Context.getTargetInfo().hasSjLjLowering())
6395     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6396            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6397   return false;
6398 }
6399 
6400 namespace {
6401 
6402 class UncoveredArgHandler {
6403   enum { Unknown = -1, AllCovered = -2 };
6404 
6405   signed FirstUncoveredArg = Unknown;
6406   SmallVector<const Expr *, 4> DiagnosticExprs;
6407 
6408 public:
6409   UncoveredArgHandler() = default;
6410 
6411   bool hasUncoveredArg() const {
6412     return (FirstUncoveredArg >= 0);
6413   }
6414 
6415   unsigned getUncoveredArg() const {
6416     assert(hasUncoveredArg() && "no uncovered argument");
6417     return FirstUncoveredArg;
6418   }
6419 
6420   void setAllCovered() {
6421     // A string has been found with all arguments covered, so clear out
6422     // the diagnostics.
6423     DiagnosticExprs.clear();
6424     FirstUncoveredArg = AllCovered;
6425   }
6426 
6427   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6428     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6429 
6430     // Don't update if a previous string covers all arguments.
6431     if (FirstUncoveredArg == AllCovered)
6432       return;
6433 
6434     // UncoveredArgHandler tracks the highest uncovered argument index
6435     // and with it all the strings that match this index.
6436     if (NewFirstUncoveredArg == FirstUncoveredArg)
6437       DiagnosticExprs.push_back(StrExpr);
6438     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6439       DiagnosticExprs.clear();
6440       DiagnosticExprs.push_back(StrExpr);
6441       FirstUncoveredArg = NewFirstUncoveredArg;
6442     }
6443   }
6444 
6445   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6446 };
6447 
6448 enum StringLiteralCheckType {
6449   SLCT_NotALiteral,
6450   SLCT_UncheckedLiteral,
6451   SLCT_CheckedLiteral
6452 };
6453 
6454 } // namespace
6455 
6456 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6457                                      BinaryOperatorKind BinOpKind,
6458                                      bool AddendIsRight) {
6459   unsigned BitWidth = Offset.getBitWidth();
6460   unsigned AddendBitWidth = Addend.getBitWidth();
6461   // There might be negative interim results.
6462   if (Addend.isUnsigned()) {
6463     Addend = Addend.zext(++AddendBitWidth);
6464     Addend.setIsSigned(true);
6465   }
6466   // Adjust the bit width of the APSInts.
6467   if (AddendBitWidth > BitWidth) {
6468     Offset = Offset.sext(AddendBitWidth);
6469     BitWidth = AddendBitWidth;
6470   } else if (BitWidth > AddendBitWidth) {
6471     Addend = Addend.sext(BitWidth);
6472   }
6473 
6474   bool Ov = false;
6475   llvm::APSInt ResOffset = Offset;
6476   if (BinOpKind == BO_Add)
6477     ResOffset = Offset.sadd_ov(Addend, Ov);
6478   else {
6479     assert(AddendIsRight && BinOpKind == BO_Sub &&
6480            "operator must be add or sub with addend on the right");
6481     ResOffset = Offset.ssub_ov(Addend, Ov);
6482   }
6483 
6484   // We add an offset to a pointer here so we should support an offset as big as
6485   // possible.
6486   if (Ov) {
6487     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6488            "index (intermediate) result too big");
6489     Offset = Offset.sext(2 * BitWidth);
6490     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6491     return;
6492   }
6493 
6494   Offset = ResOffset;
6495 }
6496 
6497 namespace {
6498 
6499 // This is a wrapper class around StringLiteral to support offsetted string
6500 // literals as format strings. It takes the offset into account when returning
6501 // the string and its length or the source locations to display notes correctly.
6502 class FormatStringLiteral {
6503   const StringLiteral *FExpr;
6504   int64_t Offset;
6505 
6506  public:
6507   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6508       : FExpr(fexpr), Offset(Offset) {}
6509 
6510   StringRef getString() const {
6511     return FExpr->getString().drop_front(Offset);
6512   }
6513 
6514   unsigned getByteLength() const {
6515     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6516   }
6517 
6518   unsigned getLength() const { return FExpr->getLength() - Offset; }
6519   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6520 
6521   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6522 
6523   QualType getType() const { return FExpr->getType(); }
6524 
6525   bool isAscii() const { return FExpr->isAscii(); }
6526   bool isWide() const { return FExpr->isWide(); }
6527   bool isUTF8() const { return FExpr->isUTF8(); }
6528   bool isUTF16() const { return FExpr->isUTF16(); }
6529   bool isUTF32() const { return FExpr->isUTF32(); }
6530   bool isPascal() const { return FExpr->isPascal(); }
6531 
6532   SourceLocation getLocationOfByte(
6533       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6534       const TargetInfo &Target, unsigned *StartToken = nullptr,
6535       unsigned *StartTokenByteOffset = nullptr) const {
6536     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6537                                     StartToken, StartTokenByteOffset);
6538   }
6539 
6540   SourceLocation getBeginLoc() const LLVM_READONLY {
6541     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6542   }
6543 
6544   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6545 };
6546 
6547 }  // namespace
6548 
6549 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6550                               const Expr *OrigFormatExpr,
6551                               ArrayRef<const Expr *> Args,
6552                               bool HasVAListArg, unsigned format_idx,
6553                               unsigned firstDataArg,
6554                               Sema::FormatStringType Type,
6555                               bool inFunctionCall,
6556                               Sema::VariadicCallType CallType,
6557                               llvm::SmallBitVector &CheckedVarArgs,
6558                               UncoveredArgHandler &UncoveredArg);
6559 
6560 // Determine if an expression is a string literal or constant string.
6561 // If this function returns false on the arguments to a function expecting a
6562 // format string, we will usually need to emit a warning.
6563 // True string literals are then checked by CheckFormatString.
6564 static StringLiteralCheckType
6565 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6566                       bool HasVAListArg, unsigned format_idx,
6567                       unsigned firstDataArg, Sema::FormatStringType Type,
6568                       Sema::VariadicCallType CallType, bool InFunctionCall,
6569                       llvm::SmallBitVector &CheckedVarArgs,
6570                       UncoveredArgHandler &UncoveredArg,
6571                       llvm::APSInt Offset) {
6572  tryAgain:
6573   assert(Offset.isSigned() && "invalid offset");
6574 
6575   if (E->isTypeDependent() || E->isValueDependent())
6576     return SLCT_NotALiteral;
6577 
6578   E = E->IgnoreParenCasts();
6579 
6580   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6581     // Technically -Wformat-nonliteral does not warn about this case.
6582     // The behavior of printf and friends in this case is implementation
6583     // dependent.  Ideally if the format string cannot be null then
6584     // it should have a 'nonnull' attribute in the function prototype.
6585     return SLCT_UncheckedLiteral;
6586 
6587   switch (E->getStmtClass()) {
6588   case Stmt::BinaryConditionalOperatorClass:
6589   case Stmt::ConditionalOperatorClass: {
6590     // The expression is a literal if both sub-expressions were, and it was
6591     // completely checked only if both sub-expressions were checked.
6592     const AbstractConditionalOperator *C =
6593         cast<AbstractConditionalOperator>(E);
6594 
6595     // Determine whether it is necessary to check both sub-expressions, for
6596     // example, because the condition expression is a constant that can be
6597     // evaluated at compile time.
6598     bool CheckLeft = true, CheckRight = true;
6599 
6600     bool Cond;
6601     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
6602       if (Cond)
6603         CheckRight = false;
6604       else
6605         CheckLeft = false;
6606     }
6607 
6608     // We need to maintain the offsets for the right and the left hand side
6609     // separately to check if every possible indexed expression is a valid
6610     // string literal. They might have different offsets for different string
6611     // literals in the end.
6612     StringLiteralCheckType Left;
6613     if (!CheckLeft)
6614       Left = SLCT_UncheckedLiteral;
6615     else {
6616       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6617                                    HasVAListArg, format_idx, firstDataArg,
6618                                    Type, CallType, InFunctionCall,
6619                                    CheckedVarArgs, UncoveredArg, Offset);
6620       if (Left == SLCT_NotALiteral || !CheckRight) {
6621         return Left;
6622       }
6623     }
6624 
6625     StringLiteralCheckType Right =
6626         checkFormatStringExpr(S, C->getFalseExpr(), Args,
6627                               HasVAListArg, format_idx, firstDataArg,
6628                               Type, CallType, InFunctionCall, CheckedVarArgs,
6629                               UncoveredArg, Offset);
6630 
6631     return (CheckLeft && Left < Right) ? Left : Right;
6632   }
6633 
6634   case Stmt::ImplicitCastExprClass:
6635     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6636     goto tryAgain;
6637 
6638   case Stmt::OpaqueValueExprClass:
6639     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6640       E = src;
6641       goto tryAgain;
6642     }
6643     return SLCT_NotALiteral;
6644 
6645   case Stmt::PredefinedExprClass:
6646     // While __func__, etc., are technically not string literals, they
6647     // cannot contain format specifiers and thus are not a security
6648     // liability.
6649     return SLCT_UncheckedLiteral;
6650 
6651   case Stmt::DeclRefExprClass: {
6652     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6653 
6654     // As an exception, do not flag errors for variables binding to
6655     // const string literals.
6656     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6657       bool isConstant = false;
6658       QualType T = DR->getType();
6659 
6660       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6661         isConstant = AT->getElementType().isConstant(S.Context);
6662       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6663         isConstant = T.isConstant(S.Context) &&
6664                      PT->getPointeeType().isConstant(S.Context);
6665       } else if (T->isObjCObjectPointerType()) {
6666         // In ObjC, there is usually no "const ObjectPointer" type,
6667         // so don't check if the pointee type is constant.
6668         isConstant = T.isConstant(S.Context);
6669       }
6670 
6671       if (isConstant) {
6672         if (const Expr *Init = VD->getAnyInitializer()) {
6673           // Look through initializers like const char c[] = { "foo" }
6674           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6675             if (InitList->isStringLiteralInit())
6676               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6677           }
6678           return checkFormatStringExpr(S, Init, Args,
6679                                        HasVAListArg, format_idx,
6680                                        firstDataArg, Type, CallType,
6681                                        /*InFunctionCall*/ false, CheckedVarArgs,
6682                                        UncoveredArg, Offset);
6683         }
6684       }
6685 
6686       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6687       // special check to see if the format string is a function parameter
6688       // of the function calling the printf function.  If the function
6689       // has an attribute indicating it is a printf-like function, then we
6690       // should suppress warnings concerning non-literals being used in a call
6691       // to a vprintf function.  For example:
6692       //
6693       // void
6694       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6695       //      va_list ap;
6696       //      va_start(ap, fmt);
6697       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6698       //      ...
6699       // }
6700       if (HasVAListArg) {
6701         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6702           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6703             int PVIndex = PV->getFunctionScopeIndex() + 1;
6704             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6705               // adjust for implicit parameter
6706               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6707                 if (MD->isInstance())
6708                   ++PVIndex;
6709               // We also check if the formats are compatible.
6710               // We can't pass a 'scanf' string to a 'printf' function.
6711               if (PVIndex == PVFormat->getFormatIdx() &&
6712                   Type == S.GetFormatStringType(PVFormat))
6713                 return SLCT_UncheckedLiteral;
6714             }
6715           }
6716         }
6717       }
6718     }
6719 
6720     return SLCT_NotALiteral;
6721   }
6722 
6723   case Stmt::CallExprClass:
6724   case Stmt::CXXMemberCallExprClass: {
6725     const CallExpr *CE = cast<CallExpr>(E);
6726     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6727       bool IsFirst = true;
6728       StringLiteralCheckType CommonResult;
6729       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6730         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6731         StringLiteralCheckType Result = checkFormatStringExpr(
6732             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6733             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6734         if (IsFirst) {
6735           CommonResult = Result;
6736           IsFirst = false;
6737         }
6738       }
6739       if (!IsFirst)
6740         return CommonResult;
6741 
6742       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6743         unsigned BuiltinID = FD->getBuiltinID();
6744         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6745             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6746           const Expr *Arg = CE->getArg(0);
6747           return checkFormatStringExpr(S, Arg, Args,
6748                                        HasVAListArg, format_idx,
6749                                        firstDataArg, Type, CallType,
6750                                        InFunctionCall, CheckedVarArgs,
6751                                        UncoveredArg, Offset);
6752         }
6753       }
6754     }
6755 
6756     return SLCT_NotALiteral;
6757   }
6758   case Stmt::ObjCMessageExprClass: {
6759     const auto *ME = cast<ObjCMessageExpr>(E);
6760     if (const auto *ND = ME->getMethodDecl()) {
6761       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
6762         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6763         return checkFormatStringExpr(
6764             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6765             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6766       }
6767     }
6768 
6769     return SLCT_NotALiteral;
6770   }
6771   case Stmt::ObjCStringLiteralClass:
6772   case Stmt::StringLiteralClass: {
6773     const StringLiteral *StrE = nullptr;
6774 
6775     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6776       StrE = ObjCFExpr->getString();
6777     else
6778       StrE = cast<StringLiteral>(E);
6779 
6780     if (StrE) {
6781       if (Offset.isNegative() || Offset > StrE->getLength()) {
6782         // TODO: It would be better to have an explicit warning for out of
6783         // bounds literals.
6784         return SLCT_NotALiteral;
6785       }
6786       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6787       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6788                         firstDataArg, Type, InFunctionCall, CallType,
6789                         CheckedVarArgs, UncoveredArg);
6790       return SLCT_CheckedLiteral;
6791     }
6792 
6793     return SLCT_NotALiteral;
6794   }
6795   case Stmt::BinaryOperatorClass: {
6796     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6797 
6798     // A string literal + an int offset is still a string literal.
6799     if (BinOp->isAdditiveOp()) {
6800       Expr::EvalResult LResult, RResult;
6801 
6802       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
6803       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
6804 
6805       if (LIsInt != RIsInt) {
6806         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6807 
6808         if (LIsInt) {
6809           if (BinOpKind == BO_Add) {
6810             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6811             E = BinOp->getRHS();
6812             goto tryAgain;
6813           }
6814         } else {
6815           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6816           E = BinOp->getLHS();
6817           goto tryAgain;
6818         }
6819       }
6820     }
6821 
6822     return SLCT_NotALiteral;
6823   }
6824   case Stmt::UnaryOperatorClass: {
6825     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6826     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6827     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6828       Expr::EvalResult IndexResult;
6829       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
6830         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6831                    /*RHS is int*/ true);
6832         E = ASE->getBase();
6833         goto tryAgain;
6834       }
6835     }
6836 
6837     return SLCT_NotALiteral;
6838   }
6839 
6840   default:
6841     return SLCT_NotALiteral;
6842   }
6843 }
6844 
6845 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6846   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6847       .Case("scanf", FST_Scanf)
6848       .Cases("printf", "printf0", FST_Printf)
6849       .Cases("NSString", "CFString", FST_NSString)
6850       .Case("strftime", FST_Strftime)
6851       .Case("strfmon", FST_Strfmon)
6852       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6853       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6854       .Case("os_trace", FST_OSLog)
6855       .Case("os_log", FST_OSLog)
6856       .Default(FST_Unknown);
6857 }
6858 
6859 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6860 /// functions) for correct use of format strings.
6861 /// Returns true if a format string has been fully checked.
6862 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6863                                 ArrayRef<const Expr *> Args,
6864                                 bool IsCXXMember,
6865                                 VariadicCallType CallType,
6866                                 SourceLocation Loc, SourceRange Range,
6867                                 llvm::SmallBitVector &CheckedVarArgs) {
6868   FormatStringInfo FSI;
6869   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6870     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6871                                 FSI.FirstDataArg, GetFormatStringType(Format),
6872                                 CallType, Loc, Range, CheckedVarArgs);
6873   return false;
6874 }
6875 
6876 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6877                                 bool HasVAListArg, unsigned format_idx,
6878                                 unsigned firstDataArg, FormatStringType Type,
6879                                 VariadicCallType CallType,
6880                                 SourceLocation Loc, SourceRange Range,
6881                                 llvm::SmallBitVector &CheckedVarArgs) {
6882   // CHECK: printf/scanf-like function is called with no format string.
6883   if (format_idx >= Args.size()) {
6884     Diag(Loc, diag::warn_missing_format_string) << Range;
6885     return false;
6886   }
6887 
6888   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6889 
6890   // CHECK: format string is not a string literal.
6891   //
6892   // Dynamically generated format strings are difficult to
6893   // automatically vet at compile time.  Requiring that format strings
6894   // are string literals: (1) permits the checking of format strings by
6895   // the compiler and thereby (2) can practically remove the source of
6896   // many format string exploits.
6897 
6898   // Format string can be either ObjC string (e.g. @"%d") or
6899   // C string (e.g. "%d")
6900   // ObjC string uses the same format specifiers as C string, so we can use
6901   // the same format string checking logic for both ObjC and C strings.
6902   UncoveredArgHandler UncoveredArg;
6903   StringLiteralCheckType CT =
6904       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6905                             format_idx, firstDataArg, Type, CallType,
6906                             /*IsFunctionCall*/ true, CheckedVarArgs,
6907                             UncoveredArg,
6908                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6909 
6910   // Generate a diagnostic where an uncovered argument is detected.
6911   if (UncoveredArg.hasUncoveredArg()) {
6912     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6913     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6914     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6915   }
6916 
6917   if (CT != SLCT_NotALiteral)
6918     // Literal format string found, check done!
6919     return CT == SLCT_CheckedLiteral;
6920 
6921   // Strftime is particular as it always uses a single 'time' argument,
6922   // so it is safe to pass a non-literal string.
6923   if (Type == FST_Strftime)
6924     return false;
6925 
6926   // Do not emit diag when the string param is a macro expansion and the
6927   // format is either NSString or CFString. This is a hack to prevent
6928   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6929   // which are usually used in place of NS and CF string literals.
6930   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6931   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6932     return false;
6933 
6934   // If there are no arguments specified, warn with -Wformat-security, otherwise
6935   // warn only with -Wformat-nonliteral.
6936   if (Args.size() == firstDataArg) {
6937     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6938       << OrigFormatExpr->getSourceRange();
6939     switch (Type) {
6940     default:
6941       break;
6942     case FST_Kprintf:
6943     case FST_FreeBSDKPrintf:
6944     case FST_Printf:
6945       Diag(FormatLoc, diag::note_format_security_fixit)
6946         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6947       break;
6948     case FST_NSString:
6949       Diag(FormatLoc, diag::note_format_security_fixit)
6950         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6951       break;
6952     }
6953   } else {
6954     Diag(FormatLoc, diag::warn_format_nonliteral)
6955       << OrigFormatExpr->getSourceRange();
6956   }
6957   return false;
6958 }
6959 
6960 namespace {
6961 
6962 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6963 protected:
6964   Sema &S;
6965   const FormatStringLiteral *FExpr;
6966   const Expr *OrigFormatExpr;
6967   const Sema::FormatStringType FSType;
6968   const unsigned FirstDataArg;
6969   const unsigned NumDataArgs;
6970   const char *Beg; // Start of format string.
6971   const bool HasVAListArg;
6972   ArrayRef<const Expr *> Args;
6973   unsigned FormatIdx;
6974   llvm::SmallBitVector CoveredArgs;
6975   bool usesPositionalArgs = false;
6976   bool atFirstArg = true;
6977   bool inFunctionCall;
6978   Sema::VariadicCallType CallType;
6979   llvm::SmallBitVector &CheckedVarArgs;
6980   UncoveredArgHandler &UncoveredArg;
6981 
6982 public:
6983   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6984                      const Expr *origFormatExpr,
6985                      const Sema::FormatStringType type, unsigned firstDataArg,
6986                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
6987                      ArrayRef<const Expr *> Args, unsigned formatIdx,
6988                      bool inFunctionCall, Sema::VariadicCallType callType,
6989                      llvm::SmallBitVector &CheckedVarArgs,
6990                      UncoveredArgHandler &UncoveredArg)
6991       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6992         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6993         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
6994         inFunctionCall(inFunctionCall), CallType(callType),
6995         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6996     CoveredArgs.resize(numDataArgs);
6997     CoveredArgs.reset();
6998   }
6999 
7000   void DoneProcessing();
7001 
7002   void HandleIncompleteSpecifier(const char *startSpecifier,
7003                                  unsigned specifierLen) override;
7004 
7005   void HandleInvalidLengthModifier(
7006                            const analyze_format_string::FormatSpecifier &FS,
7007                            const analyze_format_string::ConversionSpecifier &CS,
7008                            const char *startSpecifier, unsigned specifierLen,
7009                            unsigned DiagID);
7010 
7011   void HandleNonStandardLengthModifier(
7012                     const analyze_format_string::FormatSpecifier &FS,
7013                     const char *startSpecifier, unsigned specifierLen);
7014 
7015   void HandleNonStandardConversionSpecifier(
7016                     const analyze_format_string::ConversionSpecifier &CS,
7017                     const char *startSpecifier, unsigned specifierLen);
7018 
7019   void HandlePosition(const char *startPos, unsigned posLen) override;
7020 
7021   void HandleInvalidPosition(const char *startSpecifier,
7022                              unsigned specifierLen,
7023                              analyze_format_string::PositionContext p) override;
7024 
7025   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7026 
7027   void HandleNullChar(const char *nullCharacter) override;
7028 
7029   template <typename Range>
7030   static void
7031   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7032                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7033                        bool IsStringLocation, Range StringRange,
7034                        ArrayRef<FixItHint> Fixit = None);
7035 
7036 protected:
7037   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7038                                         const char *startSpec,
7039                                         unsigned specifierLen,
7040                                         const char *csStart, unsigned csLen);
7041 
7042   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7043                                          const char *startSpec,
7044                                          unsigned specifierLen);
7045 
7046   SourceRange getFormatStringRange();
7047   CharSourceRange getSpecifierRange(const char *startSpecifier,
7048                                     unsigned specifierLen);
7049   SourceLocation getLocationOfByte(const char *x);
7050 
7051   const Expr *getDataArg(unsigned i) const;
7052 
7053   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7054                     const analyze_format_string::ConversionSpecifier &CS,
7055                     const char *startSpecifier, unsigned specifierLen,
7056                     unsigned argIndex);
7057 
7058   template <typename Range>
7059   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7060                             bool IsStringLocation, Range StringRange,
7061                             ArrayRef<FixItHint> Fixit = None);
7062 };
7063 
7064 } // namespace
7065 
7066 SourceRange CheckFormatHandler::getFormatStringRange() {
7067   return OrigFormatExpr->getSourceRange();
7068 }
7069 
7070 CharSourceRange CheckFormatHandler::
7071 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7072   SourceLocation Start = getLocationOfByte(startSpecifier);
7073   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7074 
7075   // Advance the end SourceLocation by one due to half-open ranges.
7076   End = End.getLocWithOffset(1);
7077 
7078   return CharSourceRange::getCharRange(Start, End);
7079 }
7080 
7081 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7082   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7083                                   S.getLangOpts(), S.Context.getTargetInfo());
7084 }
7085 
7086 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7087                                                    unsigned specifierLen){
7088   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7089                        getLocationOfByte(startSpecifier),
7090                        /*IsStringLocation*/true,
7091                        getSpecifierRange(startSpecifier, specifierLen));
7092 }
7093 
7094 void CheckFormatHandler::HandleInvalidLengthModifier(
7095     const analyze_format_string::FormatSpecifier &FS,
7096     const analyze_format_string::ConversionSpecifier &CS,
7097     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7098   using namespace analyze_format_string;
7099 
7100   const LengthModifier &LM = FS.getLengthModifier();
7101   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7102 
7103   // See if we know how to fix this length modifier.
7104   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7105   if (FixedLM) {
7106     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7107                          getLocationOfByte(LM.getStart()),
7108                          /*IsStringLocation*/true,
7109                          getSpecifierRange(startSpecifier, specifierLen));
7110 
7111     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7112       << FixedLM->toString()
7113       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7114 
7115   } else {
7116     FixItHint Hint;
7117     if (DiagID == diag::warn_format_nonsensical_length)
7118       Hint = FixItHint::CreateRemoval(LMRange);
7119 
7120     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7121                          getLocationOfByte(LM.getStart()),
7122                          /*IsStringLocation*/true,
7123                          getSpecifierRange(startSpecifier, specifierLen),
7124                          Hint);
7125   }
7126 }
7127 
7128 void CheckFormatHandler::HandleNonStandardLengthModifier(
7129     const analyze_format_string::FormatSpecifier &FS,
7130     const char *startSpecifier, unsigned specifierLen) {
7131   using namespace analyze_format_string;
7132 
7133   const LengthModifier &LM = FS.getLengthModifier();
7134   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7135 
7136   // See if we know how to fix this length modifier.
7137   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7138   if (FixedLM) {
7139     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7140                            << LM.toString() << 0,
7141                          getLocationOfByte(LM.getStart()),
7142                          /*IsStringLocation*/true,
7143                          getSpecifierRange(startSpecifier, specifierLen));
7144 
7145     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7146       << FixedLM->toString()
7147       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7148 
7149   } else {
7150     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7151                            << LM.toString() << 0,
7152                          getLocationOfByte(LM.getStart()),
7153                          /*IsStringLocation*/true,
7154                          getSpecifierRange(startSpecifier, specifierLen));
7155   }
7156 }
7157 
7158 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7159     const analyze_format_string::ConversionSpecifier &CS,
7160     const char *startSpecifier, unsigned specifierLen) {
7161   using namespace analyze_format_string;
7162 
7163   // See if we know how to fix this conversion specifier.
7164   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7165   if (FixedCS) {
7166     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7167                           << CS.toString() << /*conversion specifier*/1,
7168                          getLocationOfByte(CS.getStart()),
7169                          /*IsStringLocation*/true,
7170                          getSpecifierRange(startSpecifier, specifierLen));
7171 
7172     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7173     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7174       << FixedCS->toString()
7175       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7176   } else {
7177     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7178                           << CS.toString() << /*conversion specifier*/1,
7179                          getLocationOfByte(CS.getStart()),
7180                          /*IsStringLocation*/true,
7181                          getSpecifierRange(startSpecifier, specifierLen));
7182   }
7183 }
7184 
7185 void CheckFormatHandler::HandlePosition(const char *startPos,
7186                                         unsigned posLen) {
7187   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7188                                getLocationOfByte(startPos),
7189                                /*IsStringLocation*/true,
7190                                getSpecifierRange(startPos, posLen));
7191 }
7192 
7193 void
7194 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7195                                      analyze_format_string::PositionContext p) {
7196   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7197                          << (unsigned) p,
7198                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7199                        getSpecifierRange(startPos, posLen));
7200 }
7201 
7202 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7203                                             unsigned posLen) {
7204   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7205                                getLocationOfByte(startPos),
7206                                /*IsStringLocation*/true,
7207                                getSpecifierRange(startPos, posLen));
7208 }
7209 
7210 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7211   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7212     // The presence of a null character is likely an error.
7213     EmitFormatDiagnostic(
7214       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7215       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7216       getFormatStringRange());
7217   }
7218 }
7219 
7220 // Note that this may return NULL if there was an error parsing or building
7221 // one of the argument expressions.
7222 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7223   return Args[FirstDataArg + i];
7224 }
7225 
7226 void CheckFormatHandler::DoneProcessing() {
7227   // Does the number of data arguments exceed the number of
7228   // format conversions in the format string?
7229   if (!HasVAListArg) {
7230       // Find any arguments that weren't covered.
7231     CoveredArgs.flip();
7232     signed notCoveredArg = CoveredArgs.find_first();
7233     if (notCoveredArg >= 0) {
7234       assert((unsigned)notCoveredArg < NumDataArgs);
7235       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7236     } else {
7237       UncoveredArg.setAllCovered();
7238     }
7239   }
7240 }
7241 
7242 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7243                                    const Expr *ArgExpr) {
7244   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7245          "Invalid state");
7246 
7247   if (!ArgExpr)
7248     return;
7249 
7250   SourceLocation Loc = ArgExpr->getBeginLoc();
7251 
7252   if (S.getSourceManager().isInSystemMacro(Loc))
7253     return;
7254 
7255   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7256   for (auto E : DiagnosticExprs)
7257     PDiag << E->getSourceRange();
7258 
7259   CheckFormatHandler::EmitFormatDiagnostic(
7260                                   S, IsFunctionCall, DiagnosticExprs[0],
7261                                   PDiag, Loc, /*IsStringLocation*/false,
7262                                   DiagnosticExprs[0]->getSourceRange());
7263 }
7264 
7265 bool
7266 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7267                                                      SourceLocation Loc,
7268                                                      const char *startSpec,
7269                                                      unsigned specifierLen,
7270                                                      const char *csStart,
7271                                                      unsigned csLen) {
7272   bool keepGoing = true;
7273   if (argIndex < NumDataArgs) {
7274     // Consider the argument coverered, even though the specifier doesn't
7275     // make sense.
7276     CoveredArgs.set(argIndex);
7277   }
7278   else {
7279     // If argIndex exceeds the number of data arguments we
7280     // don't issue a warning because that is just a cascade of warnings (and
7281     // they may have intended '%%' anyway). We don't want to continue processing
7282     // the format string after this point, however, as we will like just get
7283     // gibberish when trying to match arguments.
7284     keepGoing = false;
7285   }
7286 
7287   StringRef Specifier(csStart, csLen);
7288 
7289   // If the specifier in non-printable, it could be the first byte of a UTF-8
7290   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7291   // hex value.
7292   std::string CodePointStr;
7293   if (!llvm::sys::locale::isPrint(*csStart)) {
7294     llvm::UTF32 CodePoint;
7295     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7296     const llvm::UTF8 *E =
7297         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7298     llvm::ConversionResult Result =
7299         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7300 
7301     if (Result != llvm::conversionOK) {
7302       unsigned char FirstChar = *csStart;
7303       CodePoint = (llvm::UTF32)FirstChar;
7304     }
7305 
7306     llvm::raw_string_ostream OS(CodePointStr);
7307     if (CodePoint < 256)
7308       OS << "\\x" << llvm::format("%02x", CodePoint);
7309     else if (CodePoint <= 0xFFFF)
7310       OS << "\\u" << llvm::format("%04x", CodePoint);
7311     else
7312       OS << "\\U" << llvm::format("%08x", CodePoint);
7313     OS.flush();
7314     Specifier = CodePointStr;
7315   }
7316 
7317   EmitFormatDiagnostic(
7318       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7319       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7320 
7321   return keepGoing;
7322 }
7323 
7324 void
7325 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7326                                                       const char *startSpec,
7327                                                       unsigned specifierLen) {
7328   EmitFormatDiagnostic(
7329     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7330     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7331 }
7332 
7333 bool
7334 CheckFormatHandler::CheckNumArgs(
7335   const analyze_format_string::FormatSpecifier &FS,
7336   const analyze_format_string::ConversionSpecifier &CS,
7337   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7338 
7339   if (argIndex >= NumDataArgs) {
7340     PartialDiagnostic PDiag = FS.usesPositionalArg()
7341       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7342            << (argIndex+1) << NumDataArgs)
7343       : S.PDiag(diag::warn_printf_insufficient_data_args);
7344     EmitFormatDiagnostic(
7345       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7346       getSpecifierRange(startSpecifier, specifierLen));
7347 
7348     // Since more arguments than conversion tokens are given, by extension
7349     // all arguments are covered, so mark this as so.
7350     UncoveredArg.setAllCovered();
7351     return false;
7352   }
7353   return true;
7354 }
7355 
7356 template<typename Range>
7357 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7358                                               SourceLocation Loc,
7359                                               bool IsStringLocation,
7360                                               Range StringRange,
7361                                               ArrayRef<FixItHint> FixIt) {
7362   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7363                        Loc, IsStringLocation, StringRange, FixIt);
7364 }
7365 
7366 /// If the format string is not within the function call, emit a note
7367 /// so that the function call and string are in diagnostic messages.
7368 ///
7369 /// \param InFunctionCall if true, the format string is within the function
7370 /// call and only one diagnostic message will be produced.  Otherwise, an
7371 /// extra note will be emitted pointing to location of the format string.
7372 ///
7373 /// \param ArgumentExpr the expression that is passed as the format string
7374 /// argument in the function call.  Used for getting locations when two
7375 /// diagnostics are emitted.
7376 ///
7377 /// \param PDiag the callee should already have provided any strings for the
7378 /// diagnostic message.  This function only adds locations and fixits
7379 /// to diagnostics.
7380 ///
7381 /// \param Loc primary location for diagnostic.  If two diagnostics are
7382 /// required, one will be at Loc and a new SourceLocation will be created for
7383 /// the other one.
7384 ///
7385 /// \param IsStringLocation if true, Loc points to the format string should be
7386 /// used for the note.  Otherwise, Loc points to the argument list and will
7387 /// be used with PDiag.
7388 ///
7389 /// \param StringRange some or all of the string to highlight.  This is
7390 /// templated so it can accept either a CharSourceRange or a SourceRange.
7391 ///
7392 /// \param FixIt optional fix it hint for the format string.
7393 template <typename Range>
7394 void CheckFormatHandler::EmitFormatDiagnostic(
7395     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7396     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7397     Range StringRange, ArrayRef<FixItHint> FixIt) {
7398   if (InFunctionCall) {
7399     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7400     D << StringRange;
7401     D << FixIt;
7402   } else {
7403     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7404       << ArgumentExpr->getSourceRange();
7405 
7406     const Sema::SemaDiagnosticBuilder &Note =
7407       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7408              diag::note_format_string_defined);
7409 
7410     Note << StringRange;
7411     Note << FixIt;
7412   }
7413 }
7414 
7415 //===--- CHECK: Printf format string checking ------------------------------===//
7416 
7417 namespace {
7418 
7419 class CheckPrintfHandler : public CheckFormatHandler {
7420 public:
7421   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7422                      const Expr *origFormatExpr,
7423                      const Sema::FormatStringType type, unsigned firstDataArg,
7424                      unsigned numDataArgs, bool isObjC, const char *beg,
7425                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7426                      unsigned formatIdx, bool inFunctionCall,
7427                      Sema::VariadicCallType CallType,
7428                      llvm::SmallBitVector &CheckedVarArgs,
7429                      UncoveredArgHandler &UncoveredArg)
7430       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7431                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7432                            inFunctionCall, CallType, CheckedVarArgs,
7433                            UncoveredArg) {}
7434 
7435   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7436 
7437   /// Returns true if '%@' specifiers are allowed in the format string.
7438   bool allowsObjCArg() const {
7439     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7440            FSType == Sema::FST_OSTrace;
7441   }
7442 
7443   bool HandleInvalidPrintfConversionSpecifier(
7444                                       const analyze_printf::PrintfSpecifier &FS,
7445                                       const char *startSpecifier,
7446                                       unsigned specifierLen) override;
7447 
7448   void handleInvalidMaskType(StringRef MaskType) override;
7449 
7450   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7451                              const char *startSpecifier,
7452                              unsigned specifierLen) override;
7453   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7454                        const char *StartSpecifier,
7455                        unsigned SpecifierLen,
7456                        const Expr *E);
7457 
7458   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7459                     const char *startSpecifier, unsigned specifierLen);
7460   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7461                            const analyze_printf::OptionalAmount &Amt,
7462                            unsigned type,
7463                            const char *startSpecifier, unsigned specifierLen);
7464   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7465                   const analyze_printf::OptionalFlag &flag,
7466                   const char *startSpecifier, unsigned specifierLen);
7467   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7468                          const analyze_printf::OptionalFlag &ignoredFlag,
7469                          const analyze_printf::OptionalFlag &flag,
7470                          const char *startSpecifier, unsigned specifierLen);
7471   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7472                            const Expr *E);
7473 
7474   void HandleEmptyObjCModifierFlag(const char *startFlag,
7475                                    unsigned flagLen) override;
7476 
7477   void HandleInvalidObjCModifierFlag(const char *startFlag,
7478                                             unsigned flagLen) override;
7479 
7480   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7481                                            const char *flagsEnd,
7482                                            const char *conversionPosition)
7483                                              override;
7484 };
7485 
7486 } // namespace
7487 
7488 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7489                                       const analyze_printf::PrintfSpecifier &FS,
7490                                       const char *startSpecifier,
7491                                       unsigned specifierLen) {
7492   const analyze_printf::PrintfConversionSpecifier &CS =
7493     FS.getConversionSpecifier();
7494 
7495   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7496                                           getLocationOfByte(CS.getStart()),
7497                                           startSpecifier, specifierLen,
7498                                           CS.getStart(), CS.getLength());
7499 }
7500 
7501 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7502   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7503 }
7504 
7505 bool CheckPrintfHandler::HandleAmount(
7506                                const analyze_format_string::OptionalAmount &Amt,
7507                                unsigned k, const char *startSpecifier,
7508                                unsigned specifierLen) {
7509   if (Amt.hasDataArgument()) {
7510     if (!HasVAListArg) {
7511       unsigned argIndex = Amt.getArgIndex();
7512       if (argIndex >= NumDataArgs) {
7513         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7514                                << k,
7515                              getLocationOfByte(Amt.getStart()),
7516                              /*IsStringLocation*/true,
7517                              getSpecifierRange(startSpecifier, specifierLen));
7518         // Don't do any more checking.  We will just emit
7519         // spurious errors.
7520         return false;
7521       }
7522 
7523       // Type check the data argument.  It should be an 'int'.
7524       // Although not in conformance with C99, we also allow the argument to be
7525       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7526       // doesn't emit a warning for that case.
7527       CoveredArgs.set(argIndex);
7528       const Expr *Arg = getDataArg(argIndex);
7529       if (!Arg)
7530         return false;
7531 
7532       QualType T = Arg->getType();
7533 
7534       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7535       assert(AT.isValid());
7536 
7537       if (!AT.matchesType(S.Context, T)) {
7538         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7539                                << k << AT.getRepresentativeTypeName(S.Context)
7540                                << T << Arg->getSourceRange(),
7541                              getLocationOfByte(Amt.getStart()),
7542                              /*IsStringLocation*/true,
7543                              getSpecifierRange(startSpecifier, specifierLen));
7544         // Don't do any more checking.  We will just emit
7545         // spurious errors.
7546         return false;
7547       }
7548     }
7549   }
7550   return true;
7551 }
7552 
7553 void CheckPrintfHandler::HandleInvalidAmount(
7554                                       const analyze_printf::PrintfSpecifier &FS,
7555                                       const analyze_printf::OptionalAmount &Amt,
7556                                       unsigned type,
7557                                       const char *startSpecifier,
7558                                       unsigned specifierLen) {
7559   const analyze_printf::PrintfConversionSpecifier &CS =
7560     FS.getConversionSpecifier();
7561 
7562   FixItHint fixit =
7563     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7564       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7565                                  Amt.getConstantLength()))
7566       : FixItHint();
7567 
7568   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7569                          << type << CS.toString(),
7570                        getLocationOfByte(Amt.getStart()),
7571                        /*IsStringLocation*/true,
7572                        getSpecifierRange(startSpecifier, specifierLen),
7573                        fixit);
7574 }
7575 
7576 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7577                                     const analyze_printf::OptionalFlag &flag,
7578                                     const char *startSpecifier,
7579                                     unsigned specifierLen) {
7580   // Warn about pointless flag with a fixit removal.
7581   const analyze_printf::PrintfConversionSpecifier &CS =
7582     FS.getConversionSpecifier();
7583   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7584                          << flag.toString() << CS.toString(),
7585                        getLocationOfByte(flag.getPosition()),
7586                        /*IsStringLocation*/true,
7587                        getSpecifierRange(startSpecifier, specifierLen),
7588                        FixItHint::CreateRemoval(
7589                          getSpecifierRange(flag.getPosition(), 1)));
7590 }
7591 
7592 void CheckPrintfHandler::HandleIgnoredFlag(
7593                                 const analyze_printf::PrintfSpecifier &FS,
7594                                 const analyze_printf::OptionalFlag &ignoredFlag,
7595                                 const analyze_printf::OptionalFlag &flag,
7596                                 const char *startSpecifier,
7597                                 unsigned specifierLen) {
7598   // Warn about ignored flag with a fixit removal.
7599   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7600                          << ignoredFlag.toString() << flag.toString(),
7601                        getLocationOfByte(ignoredFlag.getPosition()),
7602                        /*IsStringLocation*/true,
7603                        getSpecifierRange(startSpecifier, specifierLen),
7604                        FixItHint::CreateRemoval(
7605                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7606 }
7607 
7608 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7609                                                      unsigned flagLen) {
7610   // Warn about an empty flag.
7611   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7612                        getLocationOfByte(startFlag),
7613                        /*IsStringLocation*/true,
7614                        getSpecifierRange(startFlag, flagLen));
7615 }
7616 
7617 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7618                                                        unsigned flagLen) {
7619   // Warn about an invalid flag.
7620   auto Range = getSpecifierRange(startFlag, flagLen);
7621   StringRef flag(startFlag, flagLen);
7622   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7623                       getLocationOfByte(startFlag),
7624                       /*IsStringLocation*/true,
7625                       Range, FixItHint::CreateRemoval(Range));
7626 }
7627 
7628 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7629     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7630     // Warn about using '[...]' without a '@' conversion.
7631     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7632     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7633     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7634                          getLocationOfByte(conversionPosition),
7635                          /*IsStringLocation*/true,
7636                          Range, FixItHint::CreateRemoval(Range));
7637 }
7638 
7639 // Determines if the specified is a C++ class or struct containing
7640 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7641 // "c_str()").
7642 template<typename MemberKind>
7643 static llvm::SmallPtrSet<MemberKind*, 1>
7644 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7645   const RecordType *RT = Ty->getAs<RecordType>();
7646   llvm::SmallPtrSet<MemberKind*, 1> Results;
7647 
7648   if (!RT)
7649     return Results;
7650   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7651   if (!RD || !RD->getDefinition())
7652     return Results;
7653 
7654   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7655                  Sema::LookupMemberName);
7656   R.suppressDiagnostics();
7657 
7658   // We just need to include all members of the right kind turned up by the
7659   // filter, at this point.
7660   if (S.LookupQualifiedName(R, RT->getDecl()))
7661     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7662       NamedDecl *decl = (*I)->getUnderlyingDecl();
7663       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7664         Results.insert(FK);
7665     }
7666   return Results;
7667 }
7668 
7669 /// Check if we could call '.c_str()' on an object.
7670 ///
7671 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7672 /// allow the call, or if it would be ambiguous).
7673 bool Sema::hasCStrMethod(const Expr *E) {
7674   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7675 
7676   MethodSet Results =
7677       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7678   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7679        MI != ME; ++MI)
7680     if ((*MI)->getMinRequiredArguments() == 0)
7681       return true;
7682   return false;
7683 }
7684 
7685 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7686 // better diagnostic if so. AT is assumed to be valid.
7687 // Returns true when a c_str() conversion method is found.
7688 bool CheckPrintfHandler::checkForCStrMembers(
7689     const analyze_printf::ArgType &AT, const Expr *E) {
7690   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7691 
7692   MethodSet Results =
7693       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7694 
7695   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7696        MI != ME; ++MI) {
7697     const CXXMethodDecl *Method = *MI;
7698     if (Method->getMinRequiredArguments() == 0 &&
7699         AT.matchesType(S.Context, Method->getReturnType())) {
7700       // FIXME: Suggest parens if the expression needs them.
7701       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7702       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7703           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7704       return true;
7705     }
7706   }
7707 
7708   return false;
7709 }
7710 
7711 bool
7712 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7713                                             &FS,
7714                                           const char *startSpecifier,
7715                                           unsigned specifierLen) {
7716   using namespace analyze_format_string;
7717   using namespace analyze_printf;
7718 
7719   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7720 
7721   if (FS.consumesDataArgument()) {
7722     if (atFirstArg) {
7723         atFirstArg = false;
7724         usesPositionalArgs = FS.usesPositionalArg();
7725     }
7726     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7727       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7728                                         startSpecifier, specifierLen);
7729       return false;
7730     }
7731   }
7732 
7733   // First check if the field width, precision, and conversion specifier
7734   // have matching data arguments.
7735   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7736                     startSpecifier, specifierLen)) {
7737     return false;
7738   }
7739 
7740   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7741                     startSpecifier, specifierLen)) {
7742     return false;
7743   }
7744 
7745   if (!CS.consumesDataArgument()) {
7746     // FIXME: Technically specifying a precision or field width here
7747     // makes no sense.  Worth issuing a warning at some point.
7748     return true;
7749   }
7750 
7751   // Consume the argument.
7752   unsigned argIndex = FS.getArgIndex();
7753   if (argIndex < NumDataArgs) {
7754     // The check to see if the argIndex is valid will come later.
7755     // We set the bit here because we may exit early from this
7756     // function if we encounter some other error.
7757     CoveredArgs.set(argIndex);
7758   }
7759 
7760   // FreeBSD kernel extensions.
7761   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7762       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7763     // We need at least two arguments.
7764     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7765       return false;
7766 
7767     // Claim the second argument.
7768     CoveredArgs.set(argIndex + 1);
7769 
7770     // Type check the first argument (int for %b, pointer for %D)
7771     const Expr *Ex = getDataArg(argIndex);
7772     const analyze_printf::ArgType &AT =
7773       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7774         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7775     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7776       EmitFormatDiagnostic(
7777           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7778               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7779               << false << Ex->getSourceRange(),
7780           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7781           getSpecifierRange(startSpecifier, specifierLen));
7782 
7783     // Type check the second argument (char * for both %b and %D)
7784     Ex = getDataArg(argIndex + 1);
7785     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7786     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7787       EmitFormatDiagnostic(
7788           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7789               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7790               << false << Ex->getSourceRange(),
7791           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7792           getSpecifierRange(startSpecifier, specifierLen));
7793 
7794      return true;
7795   }
7796 
7797   // Check for using an Objective-C specific conversion specifier
7798   // in a non-ObjC literal.
7799   if (!allowsObjCArg() && CS.isObjCArg()) {
7800     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7801                                                   specifierLen);
7802   }
7803 
7804   // %P can only be used with os_log.
7805   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7806     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7807                                                   specifierLen);
7808   }
7809 
7810   // %n is not allowed with os_log.
7811   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7812     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7813                          getLocationOfByte(CS.getStart()),
7814                          /*IsStringLocation*/ false,
7815                          getSpecifierRange(startSpecifier, specifierLen));
7816 
7817     return true;
7818   }
7819 
7820   // Only scalars are allowed for os_trace.
7821   if (FSType == Sema::FST_OSTrace &&
7822       (CS.getKind() == ConversionSpecifier::PArg ||
7823        CS.getKind() == ConversionSpecifier::sArg ||
7824        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7825     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7826                                                   specifierLen);
7827   }
7828 
7829   // Check for use of public/private annotation outside of os_log().
7830   if (FSType != Sema::FST_OSLog) {
7831     if (FS.isPublic().isSet()) {
7832       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7833                                << "public",
7834                            getLocationOfByte(FS.isPublic().getPosition()),
7835                            /*IsStringLocation*/ false,
7836                            getSpecifierRange(startSpecifier, specifierLen));
7837     }
7838     if (FS.isPrivate().isSet()) {
7839       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7840                                << "private",
7841                            getLocationOfByte(FS.isPrivate().getPosition()),
7842                            /*IsStringLocation*/ false,
7843                            getSpecifierRange(startSpecifier, specifierLen));
7844     }
7845   }
7846 
7847   // Check for invalid use of field width
7848   if (!FS.hasValidFieldWidth()) {
7849     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7850         startSpecifier, specifierLen);
7851   }
7852 
7853   // Check for invalid use of precision
7854   if (!FS.hasValidPrecision()) {
7855     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7856         startSpecifier, specifierLen);
7857   }
7858 
7859   // Precision is mandatory for %P specifier.
7860   if (CS.getKind() == ConversionSpecifier::PArg &&
7861       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7862     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7863                          getLocationOfByte(startSpecifier),
7864                          /*IsStringLocation*/ false,
7865                          getSpecifierRange(startSpecifier, specifierLen));
7866   }
7867 
7868   // Check each flag does not conflict with any other component.
7869   if (!FS.hasValidThousandsGroupingPrefix())
7870     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7871   if (!FS.hasValidLeadingZeros())
7872     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7873   if (!FS.hasValidPlusPrefix())
7874     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7875   if (!FS.hasValidSpacePrefix())
7876     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7877   if (!FS.hasValidAlternativeForm())
7878     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7879   if (!FS.hasValidLeftJustified())
7880     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7881 
7882   // Check that flags are not ignored by another flag
7883   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7884     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7885         startSpecifier, specifierLen);
7886   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7887     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7888             startSpecifier, specifierLen);
7889 
7890   // Check the length modifier is valid with the given conversion specifier.
7891   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7892                                  S.getLangOpts()))
7893     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7894                                 diag::warn_format_nonsensical_length);
7895   else if (!FS.hasStandardLengthModifier())
7896     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7897   else if (!FS.hasStandardLengthConversionCombination())
7898     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7899                                 diag::warn_format_non_standard_conversion_spec);
7900 
7901   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7902     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7903 
7904   // The remaining checks depend on the data arguments.
7905   if (HasVAListArg)
7906     return true;
7907 
7908   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7909     return false;
7910 
7911   const Expr *Arg = getDataArg(argIndex);
7912   if (!Arg)
7913     return true;
7914 
7915   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7916 }
7917 
7918 static bool requiresParensToAddCast(const Expr *E) {
7919   // FIXME: We should have a general way to reason about operator
7920   // precedence and whether parens are actually needed here.
7921   // Take care of a few common cases where they aren't.
7922   const Expr *Inside = E->IgnoreImpCasts();
7923   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7924     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7925 
7926   switch (Inside->getStmtClass()) {
7927   case Stmt::ArraySubscriptExprClass:
7928   case Stmt::CallExprClass:
7929   case Stmt::CharacterLiteralClass:
7930   case Stmt::CXXBoolLiteralExprClass:
7931   case Stmt::DeclRefExprClass:
7932   case Stmt::FloatingLiteralClass:
7933   case Stmt::IntegerLiteralClass:
7934   case Stmt::MemberExprClass:
7935   case Stmt::ObjCArrayLiteralClass:
7936   case Stmt::ObjCBoolLiteralExprClass:
7937   case Stmt::ObjCBoxedExprClass:
7938   case Stmt::ObjCDictionaryLiteralClass:
7939   case Stmt::ObjCEncodeExprClass:
7940   case Stmt::ObjCIvarRefExprClass:
7941   case Stmt::ObjCMessageExprClass:
7942   case Stmt::ObjCPropertyRefExprClass:
7943   case Stmt::ObjCStringLiteralClass:
7944   case Stmt::ObjCSubscriptRefExprClass:
7945   case Stmt::ParenExprClass:
7946   case Stmt::StringLiteralClass:
7947   case Stmt::UnaryOperatorClass:
7948     return false;
7949   default:
7950     return true;
7951   }
7952 }
7953 
7954 static std::pair<QualType, StringRef>
7955 shouldNotPrintDirectly(const ASTContext &Context,
7956                        QualType IntendedTy,
7957                        const Expr *E) {
7958   // Use a 'while' to peel off layers of typedefs.
7959   QualType TyTy = IntendedTy;
7960   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7961     StringRef Name = UserTy->getDecl()->getName();
7962     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7963       .Case("CFIndex", Context.getNSIntegerType())
7964       .Case("NSInteger", Context.getNSIntegerType())
7965       .Case("NSUInteger", Context.getNSUIntegerType())
7966       .Case("SInt32", Context.IntTy)
7967       .Case("UInt32", Context.UnsignedIntTy)
7968       .Default(QualType());
7969 
7970     if (!CastTy.isNull())
7971       return std::make_pair(CastTy, Name);
7972 
7973     TyTy = UserTy->desugar();
7974   }
7975 
7976   // Strip parens if necessary.
7977   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7978     return shouldNotPrintDirectly(Context,
7979                                   PE->getSubExpr()->getType(),
7980                                   PE->getSubExpr());
7981 
7982   // If this is a conditional expression, then its result type is constructed
7983   // via usual arithmetic conversions and thus there might be no necessary
7984   // typedef sugar there.  Recurse to operands to check for NSInteger &
7985   // Co. usage condition.
7986   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7987     QualType TrueTy, FalseTy;
7988     StringRef TrueName, FalseName;
7989 
7990     std::tie(TrueTy, TrueName) =
7991       shouldNotPrintDirectly(Context,
7992                              CO->getTrueExpr()->getType(),
7993                              CO->getTrueExpr());
7994     std::tie(FalseTy, FalseName) =
7995       shouldNotPrintDirectly(Context,
7996                              CO->getFalseExpr()->getType(),
7997                              CO->getFalseExpr());
7998 
7999     if (TrueTy == FalseTy)
8000       return std::make_pair(TrueTy, TrueName);
8001     else if (TrueTy.isNull())
8002       return std::make_pair(FalseTy, FalseName);
8003     else if (FalseTy.isNull())
8004       return std::make_pair(TrueTy, TrueName);
8005   }
8006 
8007   return std::make_pair(QualType(), StringRef());
8008 }
8009 
8010 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8011 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8012 /// type do not count.
8013 static bool
8014 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8015   QualType From = ICE->getSubExpr()->getType();
8016   QualType To = ICE->getType();
8017   // It's an integer promotion if the destination type is the promoted
8018   // source type.
8019   if (ICE->getCastKind() == CK_IntegralCast &&
8020       From->isPromotableIntegerType() &&
8021       S.Context.getPromotedIntegerType(From) == To)
8022     return true;
8023   // Look through vector types, since we do default argument promotion for
8024   // those in OpenCL.
8025   if (const auto *VecTy = From->getAs<ExtVectorType>())
8026     From = VecTy->getElementType();
8027   if (const auto *VecTy = To->getAs<ExtVectorType>())
8028     To = VecTy->getElementType();
8029   // It's a floating promotion if the source type is a lower rank.
8030   return ICE->getCastKind() == CK_FloatingCast &&
8031          S.Context.getFloatingTypeOrder(From, To) < 0;
8032 }
8033 
8034 bool
8035 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8036                                     const char *StartSpecifier,
8037                                     unsigned SpecifierLen,
8038                                     const Expr *E) {
8039   using namespace analyze_format_string;
8040   using namespace analyze_printf;
8041 
8042   // Now type check the data expression that matches the
8043   // format specifier.
8044   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8045   if (!AT.isValid())
8046     return true;
8047 
8048   QualType ExprTy = E->getType();
8049   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8050     ExprTy = TET->getUnderlyingExpr()->getType();
8051   }
8052 
8053   const analyze_printf::ArgType::MatchKind Match =
8054       AT.matchesType(S.Context, ExprTy);
8055   bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
8056   if (Match == analyze_printf::ArgType::Match)
8057     return true;
8058 
8059   // Look through argument promotions for our error message's reported type.
8060   // This includes the integral and floating promotions, but excludes array
8061   // and function pointer decay (seeing that an argument intended to be a
8062   // string has type 'char [6]' is probably more confusing than 'char *') and
8063   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8064   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8065     if (isArithmeticArgumentPromotion(S, ICE)) {
8066       E = ICE->getSubExpr();
8067       ExprTy = E->getType();
8068 
8069       // Check if we didn't match because of an implicit cast from a 'char'
8070       // or 'short' to an 'int'.  This is done because printf is a varargs
8071       // function.
8072       if (ICE->getType() == S.Context.IntTy ||
8073           ICE->getType() == S.Context.UnsignedIntTy) {
8074         // All further checking is done on the subexpression.
8075         if (AT.matchesType(S.Context, ExprTy))
8076           return true;
8077       }
8078     }
8079   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8080     // Special case for 'a', which has type 'int' in C.
8081     // Note, however, that we do /not/ want to treat multibyte constants like
8082     // 'MooV' as characters! This form is deprecated but still exists.
8083     if (ExprTy == S.Context.IntTy)
8084       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8085         ExprTy = S.Context.CharTy;
8086   }
8087 
8088   // Look through enums to their underlying type.
8089   bool IsEnum = false;
8090   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8091     ExprTy = EnumTy->getDecl()->getIntegerType();
8092     IsEnum = true;
8093   }
8094 
8095   // %C in an Objective-C context prints a unichar, not a wchar_t.
8096   // If the argument is an integer of some kind, believe the %C and suggest
8097   // a cast instead of changing the conversion specifier.
8098   QualType IntendedTy = ExprTy;
8099   if (isObjCContext() &&
8100       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8101     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8102         !ExprTy->isCharType()) {
8103       // 'unichar' is defined as a typedef of unsigned short, but we should
8104       // prefer using the typedef if it is visible.
8105       IntendedTy = S.Context.UnsignedShortTy;
8106 
8107       // While we are here, check if the value is an IntegerLiteral that happens
8108       // to be within the valid range.
8109       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8110         const llvm::APInt &V = IL->getValue();
8111         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8112           return true;
8113       }
8114 
8115       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8116                           Sema::LookupOrdinaryName);
8117       if (S.LookupName(Result, S.getCurScope())) {
8118         NamedDecl *ND = Result.getFoundDecl();
8119         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8120           if (TD->getUnderlyingType() == IntendedTy)
8121             IntendedTy = S.Context.getTypedefType(TD);
8122       }
8123     }
8124   }
8125 
8126   // Special-case some of Darwin's platform-independence types by suggesting
8127   // casts to primitive types that are known to be large enough.
8128   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8129   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8130     QualType CastTy;
8131     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8132     if (!CastTy.isNull()) {
8133       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8134       // (long in ASTContext). Only complain to pedants.
8135       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8136           (AT.isSizeT() || AT.isPtrdiffT()) &&
8137           AT.matchesType(S.Context, CastTy))
8138         Pedantic = true;
8139       IntendedTy = CastTy;
8140       ShouldNotPrintDirectly = true;
8141     }
8142   }
8143 
8144   // We may be able to offer a FixItHint if it is a supported type.
8145   PrintfSpecifier fixedFS = FS;
8146   bool Success =
8147       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8148 
8149   if (Success) {
8150     // Get the fix string from the fixed format specifier
8151     SmallString<16> buf;
8152     llvm::raw_svector_ostream os(buf);
8153     fixedFS.toString(os);
8154 
8155     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8156 
8157     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8158       unsigned Diag =
8159           Pedantic
8160               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8161               : diag::warn_format_conversion_argument_type_mismatch;
8162       // In this case, the specifier is wrong and should be changed to match
8163       // the argument.
8164       EmitFormatDiagnostic(S.PDiag(Diag)
8165                                << AT.getRepresentativeTypeName(S.Context)
8166                                << IntendedTy << IsEnum << E->getSourceRange(),
8167                            E->getBeginLoc(),
8168                            /*IsStringLocation*/ false, SpecRange,
8169                            FixItHint::CreateReplacement(SpecRange, os.str()));
8170     } else {
8171       // The canonical type for formatting this value is different from the
8172       // actual type of the expression. (This occurs, for example, with Darwin's
8173       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8174       // should be printed as 'long' for 64-bit compatibility.)
8175       // Rather than emitting a normal format/argument mismatch, we want to
8176       // add a cast to the recommended type (and correct the format string
8177       // if necessary).
8178       SmallString<16> CastBuf;
8179       llvm::raw_svector_ostream CastFix(CastBuf);
8180       CastFix << "(";
8181       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8182       CastFix << ")";
8183 
8184       SmallVector<FixItHint,4> Hints;
8185       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8186         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8187 
8188       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8189         // If there's already a cast present, just replace it.
8190         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8191         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8192 
8193       } else if (!requiresParensToAddCast(E)) {
8194         // If the expression has high enough precedence,
8195         // just write the C-style cast.
8196         Hints.push_back(
8197             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8198       } else {
8199         // Otherwise, add parens around the expression as well as the cast.
8200         CastFix << "(";
8201         Hints.push_back(
8202             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8203 
8204         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8205         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8206       }
8207 
8208       if (ShouldNotPrintDirectly) {
8209         // The expression has a type that should not be printed directly.
8210         // We extract the name from the typedef because we don't want to show
8211         // the underlying type in the diagnostic.
8212         StringRef Name;
8213         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8214           Name = TypedefTy->getDecl()->getName();
8215         else
8216           Name = CastTyName;
8217         unsigned Diag = Pedantic
8218                             ? diag::warn_format_argument_needs_cast_pedantic
8219                             : diag::warn_format_argument_needs_cast;
8220         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8221                                            << E->getSourceRange(),
8222                              E->getBeginLoc(), /*IsStringLocation=*/false,
8223                              SpecRange, Hints);
8224       } else {
8225         // In this case, the expression could be printed using a different
8226         // specifier, but we've decided that the specifier is probably correct
8227         // and we should cast instead. Just use the normal warning message.
8228         EmitFormatDiagnostic(
8229             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8230                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8231                 << E->getSourceRange(),
8232             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8233       }
8234     }
8235   } else {
8236     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8237                                                    SpecifierLen);
8238     // Since the warning for passing non-POD types to variadic functions
8239     // was deferred until now, we emit a warning for non-POD
8240     // arguments here.
8241     switch (S.isValidVarArgType(ExprTy)) {
8242     case Sema::VAK_Valid:
8243     case Sema::VAK_ValidInCXX11: {
8244       unsigned Diag =
8245           Pedantic
8246               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8247               : diag::warn_format_conversion_argument_type_mismatch;
8248 
8249       EmitFormatDiagnostic(
8250           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8251                         << IsEnum << CSR << E->getSourceRange(),
8252           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8253       break;
8254     }
8255     case Sema::VAK_Undefined:
8256     case Sema::VAK_MSVCUndefined:
8257       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8258                                << S.getLangOpts().CPlusPlus11 << ExprTy
8259                                << CallType
8260                                << AT.getRepresentativeTypeName(S.Context) << CSR
8261                                << E->getSourceRange(),
8262                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8263       checkForCStrMembers(AT, E);
8264       break;
8265 
8266     case Sema::VAK_Invalid:
8267       if (ExprTy->isObjCObjectType())
8268         EmitFormatDiagnostic(
8269             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8270                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8271                 << AT.getRepresentativeTypeName(S.Context) << CSR
8272                 << E->getSourceRange(),
8273             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8274       else
8275         // FIXME: If this is an initializer list, suggest removing the braces
8276         // or inserting a cast to the target type.
8277         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8278             << isa<InitListExpr>(E) << ExprTy << CallType
8279             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8280       break;
8281     }
8282 
8283     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8284            "format string specifier index out of range");
8285     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8286   }
8287 
8288   return true;
8289 }
8290 
8291 //===--- CHECK: Scanf format string checking ------------------------------===//
8292 
8293 namespace {
8294 
8295 class CheckScanfHandler : public CheckFormatHandler {
8296 public:
8297   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8298                     const Expr *origFormatExpr, Sema::FormatStringType type,
8299                     unsigned firstDataArg, unsigned numDataArgs,
8300                     const char *beg, bool hasVAListArg,
8301                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8302                     bool inFunctionCall, Sema::VariadicCallType CallType,
8303                     llvm::SmallBitVector &CheckedVarArgs,
8304                     UncoveredArgHandler &UncoveredArg)
8305       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8306                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8307                            inFunctionCall, CallType, CheckedVarArgs,
8308                            UncoveredArg) {}
8309 
8310   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8311                             const char *startSpecifier,
8312                             unsigned specifierLen) override;
8313 
8314   bool HandleInvalidScanfConversionSpecifier(
8315           const analyze_scanf::ScanfSpecifier &FS,
8316           const char *startSpecifier,
8317           unsigned specifierLen) override;
8318 
8319   void HandleIncompleteScanList(const char *start, const char *end) override;
8320 };
8321 
8322 } // namespace
8323 
8324 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8325                                                  const char *end) {
8326   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8327                        getLocationOfByte(end), /*IsStringLocation*/true,
8328                        getSpecifierRange(start, end - start));
8329 }
8330 
8331 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8332                                         const analyze_scanf::ScanfSpecifier &FS,
8333                                         const char *startSpecifier,
8334                                         unsigned specifierLen) {
8335   const analyze_scanf::ScanfConversionSpecifier &CS =
8336     FS.getConversionSpecifier();
8337 
8338   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8339                                           getLocationOfByte(CS.getStart()),
8340                                           startSpecifier, specifierLen,
8341                                           CS.getStart(), CS.getLength());
8342 }
8343 
8344 bool CheckScanfHandler::HandleScanfSpecifier(
8345                                        const analyze_scanf::ScanfSpecifier &FS,
8346                                        const char *startSpecifier,
8347                                        unsigned specifierLen) {
8348   using namespace analyze_scanf;
8349   using namespace analyze_format_string;
8350 
8351   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8352 
8353   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8354   // be used to decide if we are using positional arguments consistently.
8355   if (FS.consumesDataArgument()) {
8356     if (atFirstArg) {
8357       atFirstArg = false;
8358       usesPositionalArgs = FS.usesPositionalArg();
8359     }
8360     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8361       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8362                                         startSpecifier, specifierLen);
8363       return false;
8364     }
8365   }
8366 
8367   // Check if the field with is non-zero.
8368   const OptionalAmount &Amt = FS.getFieldWidth();
8369   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8370     if (Amt.getConstantAmount() == 0) {
8371       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8372                                                    Amt.getConstantLength());
8373       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8374                            getLocationOfByte(Amt.getStart()),
8375                            /*IsStringLocation*/true, R,
8376                            FixItHint::CreateRemoval(R));
8377     }
8378   }
8379 
8380   if (!FS.consumesDataArgument()) {
8381     // FIXME: Technically specifying a precision or field width here
8382     // makes no sense.  Worth issuing a warning at some point.
8383     return true;
8384   }
8385 
8386   // Consume the argument.
8387   unsigned argIndex = FS.getArgIndex();
8388   if (argIndex < NumDataArgs) {
8389       // The check to see if the argIndex is valid will come later.
8390       // We set the bit here because we may exit early from this
8391       // function if we encounter some other error.
8392     CoveredArgs.set(argIndex);
8393   }
8394 
8395   // Check the length modifier is valid with the given conversion specifier.
8396   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8397                                  S.getLangOpts()))
8398     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8399                                 diag::warn_format_nonsensical_length);
8400   else if (!FS.hasStandardLengthModifier())
8401     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8402   else if (!FS.hasStandardLengthConversionCombination())
8403     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8404                                 diag::warn_format_non_standard_conversion_spec);
8405 
8406   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8407     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8408 
8409   // The remaining checks depend on the data arguments.
8410   if (HasVAListArg)
8411     return true;
8412 
8413   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8414     return false;
8415 
8416   // Check that the argument type matches the format specifier.
8417   const Expr *Ex = getDataArg(argIndex);
8418   if (!Ex)
8419     return true;
8420 
8421   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8422 
8423   if (!AT.isValid()) {
8424     return true;
8425   }
8426 
8427   analyze_format_string::ArgType::MatchKind Match =
8428       AT.matchesType(S.Context, Ex->getType());
8429   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8430   if (Match == analyze_format_string::ArgType::Match)
8431     return true;
8432 
8433   ScanfSpecifier fixedFS = FS;
8434   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8435                                  S.getLangOpts(), S.Context);
8436 
8437   unsigned Diag =
8438       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8439                : diag::warn_format_conversion_argument_type_mismatch;
8440 
8441   if (Success) {
8442     // Get the fix string from the fixed format specifier.
8443     SmallString<128> buf;
8444     llvm::raw_svector_ostream os(buf);
8445     fixedFS.toString(os);
8446 
8447     EmitFormatDiagnostic(
8448         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8449                       << Ex->getType() << false << Ex->getSourceRange(),
8450         Ex->getBeginLoc(),
8451         /*IsStringLocation*/ false,
8452         getSpecifierRange(startSpecifier, specifierLen),
8453         FixItHint::CreateReplacement(
8454             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8455   } else {
8456     EmitFormatDiagnostic(S.PDiag(Diag)
8457                              << AT.getRepresentativeTypeName(S.Context)
8458                              << Ex->getType() << false << Ex->getSourceRange(),
8459                          Ex->getBeginLoc(),
8460                          /*IsStringLocation*/ false,
8461                          getSpecifierRange(startSpecifier, specifierLen));
8462   }
8463 
8464   return true;
8465 }
8466 
8467 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8468                               const Expr *OrigFormatExpr,
8469                               ArrayRef<const Expr *> Args,
8470                               bool HasVAListArg, unsigned format_idx,
8471                               unsigned firstDataArg,
8472                               Sema::FormatStringType Type,
8473                               bool inFunctionCall,
8474                               Sema::VariadicCallType CallType,
8475                               llvm::SmallBitVector &CheckedVarArgs,
8476                               UncoveredArgHandler &UncoveredArg) {
8477   // CHECK: is the format string a wide literal?
8478   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8479     CheckFormatHandler::EmitFormatDiagnostic(
8480         S, inFunctionCall, Args[format_idx],
8481         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8482         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8483     return;
8484   }
8485 
8486   // Str - The format string.  NOTE: this is NOT null-terminated!
8487   StringRef StrRef = FExpr->getString();
8488   const char *Str = StrRef.data();
8489   // Account for cases where the string literal is truncated in a declaration.
8490   const ConstantArrayType *T =
8491     S.Context.getAsConstantArrayType(FExpr->getType());
8492   assert(T && "String literal not of constant array type!");
8493   size_t TypeSize = T->getSize().getZExtValue();
8494   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8495   const unsigned numDataArgs = Args.size() - firstDataArg;
8496 
8497   // Emit a warning if the string literal is truncated and does not contain an
8498   // embedded null character.
8499   if (TypeSize <= StrRef.size() &&
8500       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8501     CheckFormatHandler::EmitFormatDiagnostic(
8502         S, inFunctionCall, Args[format_idx],
8503         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8504         FExpr->getBeginLoc(),
8505         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8506     return;
8507   }
8508 
8509   // CHECK: empty format string?
8510   if (StrLen == 0 && numDataArgs > 0) {
8511     CheckFormatHandler::EmitFormatDiagnostic(
8512         S, inFunctionCall, Args[format_idx],
8513         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8514         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8515     return;
8516   }
8517 
8518   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8519       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8520       Type == Sema::FST_OSTrace) {
8521     CheckPrintfHandler H(
8522         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8523         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8524         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8525         CheckedVarArgs, UncoveredArg);
8526 
8527     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8528                                                   S.getLangOpts(),
8529                                                   S.Context.getTargetInfo(),
8530                                             Type == Sema::FST_FreeBSDKPrintf))
8531       H.DoneProcessing();
8532   } else if (Type == Sema::FST_Scanf) {
8533     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8534                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8535                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8536 
8537     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8538                                                  S.getLangOpts(),
8539                                                  S.Context.getTargetInfo()))
8540       H.DoneProcessing();
8541   } // TODO: handle other formats
8542 }
8543 
8544 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8545   // Str - The format string.  NOTE: this is NOT null-terminated!
8546   StringRef StrRef = FExpr->getString();
8547   const char *Str = StrRef.data();
8548   // Account for cases where the string literal is truncated in a declaration.
8549   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8550   assert(T && "String literal not of constant array type!");
8551   size_t TypeSize = T->getSize().getZExtValue();
8552   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8553   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8554                                                          getLangOpts(),
8555                                                          Context.getTargetInfo());
8556 }
8557 
8558 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8559 
8560 // Returns the related absolute value function that is larger, of 0 if one
8561 // does not exist.
8562 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8563   switch (AbsFunction) {
8564   default:
8565     return 0;
8566 
8567   case Builtin::BI__builtin_abs:
8568     return Builtin::BI__builtin_labs;
8569   case Builtin::BI__builtin_labs:
8570     return Builtin::BI__builtin_llabs;
8571   case Builtin::BI__builtin_llabs:
8572     return 0;
8573 
8574   case Builtin::BI__builtin_fabsf:
8575     return Builtin::BI__builtin_fabs;
8576   case Builtin::BI__builtin_fabs:
8577     return Builtin::BI__builtin_fabsl;
8578   case Builtin::BI__builtin_fabsl:
8579     return 0;
8580 
8581   case Builtin::BI__builtin_cabsf:
8582     return Builtin::BI__builtin_cabs;
8583   case Builtin::BI__builtin_cabs:
8584     return Builtin::BI__builtin_cabsl;
8585   case Builtin::BI__builtin_cabsl:
8586     return 0;
8587 
8588   case Builtin::BIabs:
8589     return Builtin::BIlabs;
8590   case Builtin::BIlabs:
8591     return Builtin::BIllabs;
8592   case Builtin::BIllabs:
8593     return 0;
8594 
8595   case Builtin::BIfabsf:
8596     return Builtin::BIfabs;
8597   case Builtin::BIfabs:
8598     return Builtin::BIfabsl;
8599   case Builtin::BIfabsl:
8600     return 0;
8601 
8602   case Builtin::BIcabsf:
8603    return Builtin::BIcabs;
8604   case Builtin::BIcabs:
8605     return Builtin::BIcabsl;
8606   case Builtin::BIcabsl:
8607     return 0;
8608   }
8609 }
8610 
8611 // Returns the argument type of the absolute value function.
8612 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8613                                              unsigned AbsType) {
8614   if (AbsType == 0)
8615     return QualType();
8616 
8617   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8618   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8619   if (Error != ASTContext::GE_None)
8620     return QualType();
8621 
8622   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8623   if (!FT)
8624     return QualType();
8625 
8626   if (FT->getNumParams() != 1)
8627     return QualType();
8628 
8629   return FT->getParamType(0);
8630 }
8631 
8632 // Returns the best absolute value function, or zero, based on type and
8633 // current absolute value function.
8634 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8635                                    unsigned AbsFunctionKind) {
8636   unsigned BestKind = 0;
8637   uint64_t ArgSize = Context.getTypeSize(ArgType);
8638   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8639        Kind = getLargerAbsoluteValueFunction(Kind)) {
8640     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8641     if (Context.getTypeSize(ParamType) >= ArgSize) {
8642       if (BestKind == 0)
8643         BestKind = Kind;
8644       else if (Context.hasSameType(ParamType, ArgType)) {
8645         BestKind = Kind;
8646         break;
8647       }
8648     }
8649   }
8650   return BestKind;
8651 }
8652 
8653 enum AbsoluteValueKind {
8654   AVK_Integer,
8655   AVK_Floating,
8656   AVK_Complex
8657 };
8658 
8659 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8660   if (T->isIntegralOrEnumerationType())
8661     return AVK_Integer;
8662   if (T->isRealFloatingType())
8663     return AVK_Floating;
8664   if (T->isAnyComplexType())
8665     return AVK_Complex;
8666 
8667   llvm_unreachable("Type not integer, floating, or complex");
8668 }
8669 
8670 // Changes the absolute value function to a different type.  Preserves whether
8671 // the function is a builtin.
8672 static unsigned changeAbsFunction(unsigned AbsKind,
8673                                   AbsoluteValueKind ValueKind) {
8674   switch (ValueKind) {
8675   case AVK_Integer:
8676     switch (AbsKind) {
8677     default:
8678       return 0;
8679     case Builtin::BI__builtin_fabsf:
8680     case Builtin::BI__builtin_fabs:
8681     case Builtin::BI__builtin_fabsl:
8682     case Builtin::BI__builtin_cabsf:
8683     case Builtin::BI__builtin_cabs:
8684     case Builtin::BI__builtin_cabsl:
8685       return Builtin::BI__builtin_abs;
8686     case Builtin::BIfabsf:
8687     case Builtin::BIfabs:
8688     case Builtin::BIfabsl:
8689     case Builtin::BIcabsf:
8690     case Builtin::BIcabs:
8691     case Builtin::BIcabsl:
8692       return Builtin::BIabs;
8693     }
8694   case AVK_Floating:
8695     switch (AbsKind) {
8696     default:
8697       return 0;
8698     case Builtin::BI__builtin_abs:
8699     case Builtin::BI__builtin_labs:
8700     case Builtin::BI__builtin_llabs:
8701     case Builtin::BI__builtin_cabsf:
8702     case Builtin::BI__builtin_cabs:
8703     case Builtin::BI__builtin_cabsl:
8704       return Builtin::BI__builtin_fabsf;
8705     case Builtin::BIabs:
8706     case Builtin::BIlabs:
8707     case Builtin::BIllabs:
8708     case Builtin::BIcabsf:
8709     case Builtin::BIcabs:
8710     case Builtin::BIcabsl:
8711       return Builtin::BIfabsf;
8712     }
8713   case AVK_Complex:
8714     switch (AbsKind) {
8715     default:
8716       return 0;
8717     case Builtin::BI__builtin_abs:
8718     case Builtin::BI__builtin_labs:
8719     case Builtin::BI__builtin_llabs:
8720     case Builtin::BI__builtin_fabsf:
8721     case Builtin::BI__builtin_fabs:
8722     case Builtin::BI__builtin_fabsl:
8723       return Builtin::BI__builtin_cabsf;
8724     case Builtin::BIabs:
8725     case Builtin::BIlabs:
8726     case Builtin::BIllabs:
8727     case Builtin::BIfabsf:
8728     case Builtin::BIfabs:
8729     case Builtin::BIfabsl:
8730       return Builtin::BIcabsf;
8731     }
8732   }
8733   llvm_unreachable("Unable to convert function");
8734 }
8735 
8736 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8737   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8738   if (!FnInfo)
8739     return 0;
8740 
8741   switch (FDecl->getBuiltinID()) {
8742   default:
8743     return 0;
8744   case Builtin::BI__builtin_abs:
8745   case Builtin::BI__builtin_fabs:
8746   case Builtin::BI__builtin_fabsf:
8747   case Builtin::BI__builtin_fabsl:
8748   case Builtin::BI__builtin_labs:
8749   case Builtin::BI__builtin_llabs:
8750   case Builtin::BI__builtin_cabs:
8751   case Builtin::BI__builtin_cabsf:
8752   case Builtin::BI__builtin_cabsl:
8753   case Builtin::BIabs:
8754   case Builtin::BIlabs:
8755   case Builtin::BIllabs:
8756   case Builtin::BIfabs:
8757   case Builtin::BIfabsf:
8758   case Builtin::BIfabsl:
8759   case Builtin::BIcabs:
8760   case Builtin::BIcabsf:
8761   case Builtin::BIcabsl:
8762     return FDecl->getBuiltinID();
8763   }
8764   llvm_unreachable("Unknown Builtin type");
8765 }
8766 
8767 // If the replacement is valid, emit a note with replacement function.
8768 // Additionally, suggest including the proper header if not already included.
8769 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8770                             unsigned AbsKind, QualType ArgType) {
8771   bool EmitHeaderHint = true;
8772   const char *HeaderName = nullptr;
8773   const char *FunctionName = nullptr;
8774   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8775     FunctionName = "std::abs";
8776     if (ArgType->isIntegralOrEnumerationType()) {
8777       HeaderName = "cstdlib";
8778     } else if (ArgType->isRealFloatingType()) {
8779       HeaderName = "cmath";
8780     } else {
8781       llvm_unreachable("Invalid Type");
8782     }
8783 
8784     // Lookup all std::abs
8785     if (NamespaceDecl *Std = S.getStdNamespace()) {
8786       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8787       R.suppressDiagnostics();
8788       S.LookupQualifiedName(R, Std);
8789 
8790       for (const auto *I : R) {
8791         const FunctionDecl *FDecl = nullptr;
8792         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8793           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8794         } else {
8795           FDecl = dyn_cast<FunctionDecl>(I);
8796         }
8797         if (!FDecl)
8798           continue;
8799 
8800         // Found std::abs(), check that they are the right ones.
8801         if (FDecl->getNumParams() != 1)
8802           continue;
8803 
8804         // Check that the parameter type can handle the argument.
8805         QualType ParamType = FDecl->getParamDecl(0)->getType();
8806         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8807             S.Context.getTypeSize(ArgType) <=
8808                 S.Context.getTypeSize(ParamType)) {
8809           // Found a function, don't need the header hint.
8810           EmitHeaderHint = false;
8811           break;
8812         }
8813       }
8814     }
8815   } else {
8816     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8817     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8818 
8819     if (HeaderName) {
8820       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8821       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8822       R.suppressDiagnostics();
8823       S.LookupName(R, S.getCurScope());
8824 
8825       if (R.isSingleResult()) {
8826         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8827         if (FD && FD->getBuiltinID() == AbsKind) {
8828           EmitHeaderHint = false;
8829         } else {
8830           return;
8831         }
8832       } else if (!R.empty()) {
8833         return;
8834       }
8835     }
8836   }
8837 
8838   S.Diag(Loc, diag::note_replace_abs_function)
8839       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8840 
8841   if (!HeaderName)
8842     return;
8843 
8844   if (!EmitHeaderHint)
8845     return;
8846 
8847   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8848                                                     << FunctionName;
8849 }
8850 
8851 template <std::size_t StrLen>
8852 static bool IsStdFunction(const FunctionDecl *FDecl,
8853                           const char (&Str)[StrLen]) {
8854   if (!FDecl)
8855     return false;
8856   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8857     return false;
8858   if (!FDecl->isInStdNamespace())
8859     return false;
8860 
8861   return true;
8862 }
8863 
8864 // Warn when using the wrong abs() function.
8865 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8866                                       const FunctionDecl *FDecl) {
8867   if (Call->getNumArgs() != 1)
8868     return;
8869 
8870   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8871   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8872   if (AbsKind == 0 && !IsStdAbs)
8873     return;
8874 
8875   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8876   QualType ParamType = Call->getArg(0)->getType();
8877 
8878   // Unsigned types cannot be negative.  Suggest removing the absolute value
8879   // function call.
8880   if (ArgType->isUnsignedIntegerType()) {
8881     const char *FunctionName =
8882         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8883     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8884     Diag(Call->getExprLoc(), diag::note_remove_abs)
8885         << FunctionName
8886         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8887     return;
8888   }
8889 
8890   // Taking the absolute value of a pointer is very suspicious, they probably
8891   // wanted to index into an array, dereference a pointer, call a function, etc.
8892   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8893     unsigned DiagType = 0;
8894     if (ArgType->isFunctionType())
8895       DiagType = 1;
8896     else if (ArgType->isArrayType())
8897       DiagType = 2;
8898 
8899     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8900     return;
8901   }
8902 
8903   // std::abs has overloads which prevent most of the absolute value problems
8904   // from occurring.
8905   if (IsStdAbs)
8906     return;
8907 
8908   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8909   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8910 
8911   // The argument and parameter are the same kind.  Check if they are the right
8912   // size.
8913   if (ArgValueKind == ParamValueKind) {
8914     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8915       return;
8916 
8917     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8918     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8919         << FDecl << ArgType << ParamType;
8920 
8921     if (NewAbsKind == 0)
8922       return;
8923 
8924     emitReplacement(*this, Call->getExprLoc(),
8925                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8926     return;
8927   }
8928 
8929   // ArgValueKind != ParamValueKind
8930   // The wrong type of absolute value function was used.  Attempt to find the
8931   // proper one.
8932   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8933   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8934   if (NewAbsKind == 0)
8935     return;
8936 
8937   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8938       << FDecl << ParamValueKind << ArgValueKind;
8939 
8940   emitReplacement(*this, Call->getExprLoc(),
8941                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8942 }
8943 
8944 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8945 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8946                                 const FunctionDecl *FDecl) {
8947   if (!Call || !FDecl) return;
8948 
8949   // Ignore template specializations and macros.
8950   if (inTemplateInstantiation()) return;
8951   if (Call->getExprLoc().isMacroID()) return;
8952 
8953   // Only care about the one template argument, two function parameter std::max
8954   if (Call->getNumArgs() != 2) return;
8955   if (!IsStdFunction(FDecl, "max")) return;
8956   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8957   if (!ArgList) return;
8958   if (ArgList->size() != 1) return;
8959 
8960   // Check that template type argument is unsigned integer.
8961   const auto& TA = ArgList->get(0);
8962   if (TA.getKind() != TemplateArgument::Type) return;
8963   QualType ArgType = TA.getAsType();
8964   if (!ArgType->isUnsignedIntegerType()) return;
8965 
8966   // See if either argument is a literal zero.
8967   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8968     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8969     if (!MTE) return false;
8970     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8971     if (!Num) return false;
8972     if (Num->getValue() != 0) return false;
8973     return true;
8974   };
8975 
8976   const Expr *FirstArg = Call->getArg(0);
8977   const Expr *SecondArg = Call->getArg(1);
8978   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8979   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8980 
8981   // Only warn when exactly one argument is zero.
8982   if (IsFirstArgZero == IsSecondArgZero) return;
8983 
8984   SourceRange FirstRange = FirstArg->getSourceRange();
8985   SourceRange SecondRange = SecondArg->getSourceRange();
8986 
8987   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8988 
8989   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8990       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8991 
8992   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8993   SourceRange RemovalRange;
8994   if (IsFirstArgZero) {
8995     RemovalRange = SourceRange(FirstRange.getBegin(),
8996                                SecondRange.getBegin().getLocWithOffset(-1));
8997   } else {
8998     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8999                                SecondRange.getEnd());
9000   }
9001 
9002   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9003         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9004         << FixItHint::CreateRemoval(RemovalRange);
9005 }
9006 
9007 //===--- CHECK: Standard memory functions ---------------------------------===//
9008 
9009 /// Takes the expression passed to the size_t parameter of functions
9010 /// such as memcmp, strncat, etc and warns if it's a comparison.
9011 ///
9012 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9013 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9014                                            IdentifierInfo *FnName,
9015                                            SourceLocation FnLoc,
9016                                            SourceLocation RParenLoc) {
9017   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9018   if (!Size)
9019     return false;
9020 
9021   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9022   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9023     return false;
9024 
9025   SourceRange SizeRange = Size->getSourceRange();
9026   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9027       << SizeRange << FnName;
9028   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9029       << FnName
9030       << FixItHint::CreateInsertion(
9031              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9032       << FixItHint::CreateRemoval(RParenLoc);
9033   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9034       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9035       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9036                                     ")");
9037 
9038   return true;
9039 }
9040 
9041 /// Determine whether the given type is or contains a dynamic class type
9042 /// (e.g., whether it has a vtable).
9043 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9044                                                      bool &IsContained) {
9045   // Look through array types while ignoring qualifiers.
9046   const Type *Ty = T->getBaseElementTypeUnsafe();
9047   IsContained = false;
9048 
9049   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9050   RD = RD ? RD->getDefinition() : nullptr;
9051   if (!RD || RD->isInvalidDecl())
9052     return nullptr;
9053 
9054   if (RD->isDynamicClass())
9055     return RD;
9056 
9057   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9058   // It's impossible for a class to transitively contain itself by value, so
9059   // infinite recursion is impossible.
9060   for (auto *FD : RD->fields()) {
9061     bool SubContained;
9062     if (const CXXRecordDecl *ContainedRD =
9063             getContainedDynamicClass(FD->getType(), SubContained)) {
9064       IsContained = true;
9065       return ContainedRD;
9066     }
9067   }
9068 
9069   return nullptr;
9070 }
9071 
9072 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9073   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9074     if (Unary->getKind() == UETT_SizeOf)
9075       return Unary;
9076   return nullptr;
9077 }
9078 
9079 /// If E is a sizeof expression, returns its argument expression,
9080 /// otherwise returns NULL.
9081 static const Expr *getSizeOfExprArg(const Expr *E) {
9082   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9083     if (!SizeOf->isArgumentType())
9084       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9085   return nullptr;
9086 }
9087 
9088 /// If E is a sizeof expression, returns its argument type.
9089 static QualType getSizeOfArgType(const Expr *E) {
9090   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9091     return SizeOf->getTypeOfArgument();
9092   return QualType();
9093 }
9094 
9095 namespace {
9096 
9097 struct SearchNonTrivialToInitializeField
9098     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9099   using Super =
9100       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9101 
9102   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9103 
9104   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9105                      SourceLocation SL) {
9106     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9107       asDerived().visitArray(PDIK, AT, SL);
9108       return;
9109     }
9110 
9111     Super::visitWithKind(PDIK, FT, SL);
9112   }
9113 
9114   void visitARCStrong(QualType FT, SourceLocation SL) {
9115     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9116   }
9117   void visitARCWeak(QualType FT, SourceLocation SL) {
9118     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9119   }
9120   void visitStruct(QualType FT, SourceLocation SL) {
9121     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9122       visit(FD->getType(), FD->getLocation());
9123   }
9124   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9125                   const ArrayType *AT, SourceLocation SL) {
9126     visit(getContext().getBaseElementType(AT), SL);
9127   }
9128   void visitTrivial(QualType FT, SourceLocation SL) {}
9129 
9130   static void diag(QualType RT, const Expr *E, Sema &S) {
9131     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9132   }
9133 
9134   ASTContext &getContext() { return S.getASTContext(); }
9135 
9136   const Expr *E;
9137   Sema &S;
9138 };
9139 
9140 struct SearchNonTrivialToCopyField
9141     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9142   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9143 
9144   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9145 
9146   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9147                      SourceLocation SL) {
9148     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9149       asDerived().visitArray(PCK, AT, SL);
9150       return;
9151     }
9152 
9153     Super::visitWithKind(PCK, FT, SL);
9154   }
9155 
9156   void visitARCStrong(QualType FT, SourceLocation SL) {
9157     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9158   }
9159   void visitARCWeak(QualType FT, SourceLocation SL) {
9160     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9161   }
9162   void visitStruct(QualType FT, SourceLocation SL) {
9163     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9164       visit(FD->getType(), FD->getLocation());
9165   }
9166   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9167                   SourceLocation SL) {
9168     visit(getContext().getBaseElementType(AT), SL);
9169   }
9170   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9171                 SourceLocation SL) {}
9172   void visitTrivial(QualType FT, SourceLocation SL) {}
9173   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9174 
9175   static void diag(QualType RT, const Expr *E, Sema &S) {
9176     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9177   }
9178 
9179   ASTContext &getContext() { return S.getASTContext(); }
9180 
9181   const Expr *E;
9182   Sema &S;
9183 };
9184 
9185 }
9186 
9187 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9188 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9189   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9190 
9191   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9192     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9193       return false;
9194 
9195     return doesExprLikelyComputeSize(BO->getLHS()) ||
9196            doesExprLikelyComputeSize(BO->getRHS());
9197   }
9198 
9199   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9200 }
9201 
9202 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9203 ///
9204 /// \code
9205 ///   #define MACRO 0
9206 ///   foo(MACRO);
9207 ///   foo(0);
9208 /// \endcode
9209 ///
9210 /// This should return true for the first call to foo, but not for the second
9211 /// (regardless of whether foo is a macro or function).
9212 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9213                                         SourceLocation CallLoc,
9214                                         SourceLocation ArgLoc) {
9215   if (!CallLoc.isMacroID())
9216     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9217 
9218   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9219          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9220 }
9221 
9222 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9223 /// last two arguments transposed.
9224 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9225   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9226     return;
9227 
9228   const Expr *SizeArg =
9229     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9230 
9231   auto isLiteralZero = [](const Expr *E) {
9232     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9233   };
9234 
9235   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9236   SourceLocation CallLoc = Call->getRParenLoc();
9237   SourceManager &SM = S.getSourceManager();
9238   if (isLiteralZero(SizeArg) &&
9239       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9240 
9241     SourceLocation DiagLoc = SizeArg->getExprLoc();
9242 
9243     // Some platforms #define bzero to __builtin_memset. See if this is the
9244     // case, and if so, emit a better diagnostic.
9245     if (BId == Builtin::BIbzero ||
9246         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9247                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9248       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9249       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9250     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9251       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9252       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9253     }
9254     return;
9255   }
9256 
9257   // If the second argument to a memset is a sizeof expression and the third
9258   // isn't, this is also likely an error. This should catch
9259   // 'memset(buf, sizeof(buf), 0xff)'.
9260   if (BId == Builtin::BImemset &&
9261       doesExprLikelyComputeSize(Call->getArg(1)) &&
9262       !doesExprLikelyComputeSize(Call->getArg(2))) {
9263     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9264     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9265     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9266     return;
9267   }
9268 }
9269 
9270 /// Check for dangerous or invalid arguments to memset().
9271 ///
9272 /// This issues warnings on known problematic, dangerous or unspecified
9273 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9274 /// function calls.
9275 ///
9276 /// \param Call The call expression to diagnose.
9277 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9278                                    unsigned BId,
9279                                    IdentifierInfo *FnName) {
9280   assert(BId != 0);
9281 
9282   // It is possible to have a non-standard definition of memset.  Validate
9283   // we have enough arguments, and if not, abort further checking.
9284   unsigned ExpectedNumArgs =
9285       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9286   if (Call->getNumArgs() < ExpectedNumArgs)
9287     return;
9288 
9289   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9290                       BId == Builtin::BIstrndup ? 1 : 2);
9291   unsigned LenArg =
9292       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9293   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9294 
9295   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9296                                      Call->getBeginLoc(), Call->getRParenLoc()))
9297     return;
9298 
9299   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9300   CheckMemaccessSize(*this, BId, Call);
9301 
9302   // We have special checking when the length is a sizeof expression.
9303   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9304   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9305   llvm::FoldingSetNodeID SizeOfArgID;
9306 
9307   // Although widely used, 'bzero' is not a standard function. Be more strict
9308   // with the argument types before allowing diagnostics and only allow the
9309   // form bzero(ptr, sizeof(...)).
9310   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9311   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9312     return;
9313 
9314   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9315     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9316     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9317 
9318     QualType DestTy = Dest->getType();
9319     QualType PointeeTy;
9320     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9321       PointeeTy = DestPtrTy->getPointeeType();
9322 
9323       // Never warn about void type pointers. This can be used to suppress
9324       // false positives.
9325       if (PointeeTy->isVoidType())
9326         continue;
9327 
9328       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9329       // actually comparing the expressions for equality. Because computing the
9330       // expression IDs can be expensive, we only do this if the diagnostic is
9331       // enabled.
9332       if (SizeOfArg &&
9333           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9334                            SizeOfArg->getExprLoc())) {
9335         // We only compute IDs for expressions if the warning is enabled, and
9336         // cache the sizeof arg's ID.
9337         if (SizeOfArgID == llvm::FoldingSetNodeID())
9338           SizeOfArg->Profile(SizeOfArgID, Context, true);
9339         llvm::FoldingSetNodeID DestID;
9340         Dest->Profile(DestID, Context, true);
9341         if (DestID == SizeOfArgID) {
9342           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9343           //       over sizeof(src) as well.
9344           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9345           StringRef ReadableName = FnName->getName();
9346 
9347           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9348             if (UnaryOp->getOpcode() == UO_AddrOf)
9349               ActionIdx = 1; // If its an address-of operator, just remove it.
9350           if (!PointeeTy->isIncompleteType() &&
9351               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9352             ActionIdx = 2; // If the pointee's size is sizeof(char),
9353                            // suggest an explicit length.
9354 
9355           // If the function is defined as a builtin macro, do not show macro
9356           // expansion.
9357           SourceLocation SL = SizeOfArg->getExprLoc();
9358           SourceRange DSR = Dest->getSourceRange();
9359           SourceRange SSR = SizeOfArg->getSourceRange();
9360           SourceManager &SM = getSourceManager();
9361 
9362           if (SM.isMacroArgExpansion(SL)) {
9363             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9364             SL = SM.getSpellingLoc(SL);
9365             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9366                              SM.getSpellingLoc(DSR.getEnd()));
9367             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9368                              SM.getSpellingLoc(SSR.getEnd()));
9369           }
9370 
9371           DiagRuntimeBehavior(SL, SizeOfArg,
9372                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9373                                 << ReadableName
9374                                 << PointeeTy
9375                                 << DestTy
9376                                 << DSR
9377                                 << SSR);
9378           DiagRuntimeBehavior(SL, SizeOfArg,
9379                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9380                                 << ActionIdx
9381                                 << SSR);
9382 
9383           break;
9384         }
9385       }
9386 
9387       // Also check for cases where the sizeof argument is the exact same
9388       // type as the memory argument, and where it points to a user-defined
9389       // record type.
9390       if (SizeOfArgTy != QualType()) {
9391         if (PointeeTy->isRecordType() &&
9392             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9393           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9394                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9395                                 << FnName << SizeOfArgTy << ArgIdx
9396                                 << PointeeTy << Dest->getSourceRange()
9397                                 << LenExpr->getSourceRange());
9398           break;
9399         }
9400       }
9401     } else if (DestTy->isArrayType()) {
9402       PointeeTy = DestTy;
9403     }
9404 
9405     if (PointeeTy == QualType())
9406       continue;
9407 
9408     // Always complain about dynamic classes.
9409     bool IsContained;
9410     if (const CXXRecordDecl *ContainedRD =
9411             getContainedDynamicClass(PointeeTy, IsContained)) {
9412 
9413       unsigned OperationType = 0;
9414       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9415       // "overwritten" if we're warning about the destination for any call
9416       // but memcmp; otherwise a verb appropriate to the call.
9417       if (ArgIdx != 0 || IsCmp) {
9418         if (BId == Builtin::BImemcpy)
9419           OperationType = 1;
9420         else if(BId == Builtin::BImemmove)
9421           OperationType = 2;
9422         else if (IsCmp)
9423           OperationType = 3;
9424       }
9425 
9426       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9427                           PDiag(diag::warn_dyn_class_memaccess)
9428                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9429                               << IsContained << ContainedRD << OperationType
9430                               << Call->getCallee()->getSourceRange());
9431     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9432              BId != Builtin::BImemset)
9433       DiagRuntimeBehavior(
9434         Dest->getExprLoc(), Dest,
9435         PDiag(diag::warn_arc_object_memaccess)
9436           << ArgIdx << FnName << PointeeTy
9437           << Call->getCallee()->getSourceRange());
9438     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9439       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9440           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9441         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9442                             PDiag(diag::warn_cstruct_memaccess)
9443                                 << ArgIdx << FnName << PointeeTy << 0);
9444         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9445       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9446                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9447         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9448                             PDiag(diag::warn_cstruct_memaccess)
9449                                 << ArgIdx << FnName << PointeeTy << 1);
9450         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9451       } else {
9452         continue;
9453       }
9454     } else
9455       continue;
9456 
9457     DiagRuntimeBehavior(
9458       Dest->getExprLoc(), Dest,
9459       PDiag(diag::note_bad_memaccess_silence)
9460         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9461     break;
9462   }
9463 }
9464 
9465 // A little helper routine: ignore addition and subtraction of integer literals.
9466 // This intentionally does not ignore all integer constant expressions because
9467 // we don't want to remove sizeof().
9468 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9469   Ex = Ex->IgnoreParenCasts();
9470 
9471   while (true) {
9472     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9473     if (!BO || !BO->isAdditiveOp())
9474       break;
9475 
9476     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9477     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9478 
9479     if (isa<IntegerLiteral>(RHS))
9480       Ex = LHS;
9481     else if (isa<IntegerLiteral>(LHS))
9482       Ex = RHS;
9483     else
9484       break;
9485   }
9486 
9487   return Ex;
9488 }
9489 
9490 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9491                                                       ASTContext &Context) {
9492   // Only handle constant-sized or VLAs, but not flexible members.
9493   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9494     // Only issue the FIXIT for arrays of size > 1.
9495     if (CAT->getSize().getSExtValue() <= 1)
9496       return false;
9497   } else if (!Ty->isVariableArrayType()) {
9498     return false;
9499   }
9500   return true;
9501 }
9502 
9503 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9504 // be the size of the source, instead of the destination.
9505 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9506                                     IdentifierInfo *FnName) {
9507 
9508   // Don't crash if the user has the wrong number of arguments
9509   unsigned NumArgs = Call->getNumArgs();
9510   if ((NumArgs != 3) && (NumArgs != 4))
9511     return;
9512 
9513   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9514   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9515   const Expr *CompareWithSrc = nullptr;
9516 
9517   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9518                                      Call->getBeginLoc(), Call->getRParenLoc()))
9519     return;
9520 
9521   // Look for 'strlcpy(dst, x, sizeof(x))'
9522   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9523     CompareWithSrc = Ex;
9524   else {
9525     // Look for 'strlcpy(dst, x, strlen(x))'
9526     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9527       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9528           SizeCall->getNumArgs() == 1)
9529         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9530     }
9531   }
9532 
9533   if (!CompareWithSrc)
9534     return;
9535 
9536   // Determine if the argument to sizeof/strlen is equal to the source
9537   // argument.  In principle there's all kinds of things you could do
9538   // here, for instance creating an == expression and evaluating it with
9539   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9540   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9541   if (!SrcArgDRE)
9542     return;
9543 
9544   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9545   if (!CompareWithSrcDRE ||
9546       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9547     return;
9548 
9549   const Expr *OriginalSizeArg = Call->getArg(2);
9550   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9551       << OriginalSizeArg->getSourceRange() << FnName;
9552 
9553   // Output a FIXIT hint if the destination is an array (rather than a
9554   // pointer to an array).  This could be enhanced to handle some
9555   // pointers if we know the actual size, like if DstArg is 'array+2'
9556   // we could say 'sizeof(array)-2'.
9557   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9558   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9559     return;
9560 
9561   SmallString<128> sizeString;
9562   llvm::raw_svector_ostream OS(sizeString);
9563   OS << "sizeof(";
9564   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9565   OS << ")";
9566 
9567   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9568       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9569                                       OS.str());
9570 }
9571 
9572 /// Check if two expressions refer to the same declaration.
9573 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9574   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9575     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9576       return D1->getDecl() == D2->getDecl();
9577   return false;
9578 }
9579 
9580 static const Expr *getStrlenExprArg(const Expr *E) {
9581   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9582     const FunctionDecl *FD = CE->getDirectCallee();
9583     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9584       return nullptr;
9585     return CE->getArg(0)->IgnoreParenCasts();
9586   }
9587   return nullptr;
9588 }
9589 
9590 // Warn on anti-patterns as the 'size' argument to strncat.
9591 // The correct size argument should look like following:
9592 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9593 void Sema::CheckStrncatArguments(const CallExpr *CE,
9594                                  IdentifierInfo *FnName) {
9595   // Don't crash if the user has the wrong number of arguments.
9596   if (CE->getNumArgs() < 3)
9597     return;
9598   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9599   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9600   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9601 
9602   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9603                                      CE->getRParenLoc()))
9604     return;
9605 
9606   // Identify common expressions, which are wrongly used as the size argument
9607   // to strncat and may lead to buffer overflows.
9608   unsigned PatternType = 0;
9609   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9610     // - sizeof(dst)
9611     if (referToTheSameDecl(SizeOfArg, DstArg))
9612       PatternType = 1;
9613     // - sizeof(src)
9614     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9615       PatternType = 2;
9616   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9617     if (BE->getOpcode() == BO_Sub) {
9618       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9619       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9620       // - sizeof(dst) - strlen(dst)
9621       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9622           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9623         PatternType = 1;
9624       // - sizeof(src) - (anything)
9625       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9626         PatternType = 2;
9627     }
9628   }
9629 
9630   if (PatternType == 0)
9631     return;
9632 
9633   // Generate the diagnostic.
9634   SourceLocation SL = LenArg->getBeginLoc();
9635   SourceRange SR = LenArg->getSourceRange();
9636   SourceManager &SM = getSourceManager();
9637 
9638   // If the function is defined as a builtin macro, do not show macro expansion.
9639   if (SM.isMacroArgExpansion(SL)) {
9640     SL = SM.getSpellingLoc(SL);
9641     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9642                      SM.getSpellingLoc(SR.getEnd()));
9643   }
9644 
9645   // Check if the destination is an array (rather than a pointer to an array).
9646   QualType DstTy = DstArg->getType();
9647   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9648                                                                     Context);
9649   if (!isKnownSizeArray) {
9650     if (PatternType == 1)
9651       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9652     else
9653       Diag(SL, diag::warn_strncat_src_size) << SR;
9654     return;
9655   }
9656 
9657   if (PatternType == 1)
9658     Diag(SL, diag::warn_strncat_large_size) << SR;
9659   else
9660     Diag(SL, diag::warn_strncat_src_size) << SR;
9661 
9662   SmallString<128> sizeString;
9663   llvm::raw_svector_ostream OS(sizeString);
9664   OS << "sizeof(";
9665   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9666   OS << ") - ";
9667   OS << "strlen(";
9668   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9669   OS << ") - 1";
9670 
9671   Diag(SL, diag::note_strncat_wrong_size)
9672     << FixItHint::CreateReplacement(SR, OS.str());
9673 }
9674 
9675 void
9676 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9677                          SourceLocation ReturnLoc,
9678                          bool isObjCMethod,
9679                          const AttrVec *Attrs,
9680                          const FunctionDecl *FD) {
9681   // Check if the return value is null but should not be.
9682   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9683        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9684       CheckNonNullExpr(*this, RetValExp))
9685     Diag(ReturnLoc, diag::warn_null_ret)
9686       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9687 
9688   // C++11 [basic.stc.dynamic.allocation]p4:
9689   //   If an allocation function declared with a non-throwing
9690   //   exception-specification fails to allocate storage, it shall return
9691   //   a null pointer. Any other allocation function that fails to allocate
9692   //   storage shall indicate failure only by throwing an exception [...]
9693   if (FD) {
9694     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9695     if (Op == OO_New || Op == OO_Array_New) {
9696       const FunctionProtoType *Proto
9697         = FD->getType()->castAs<FunctionProtoType>();
9698       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9699           CheckNonNullExpr(*this, RetValExp))
9700         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9701           << FD << getLangOpts().CPlusPlus11;
9702     }
9703   }
9704 }
9705 
9706 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9707 
9708 /// Check for comparisons of floating point operands using != and ==.
9709 /// Issue a warning if these are no self-comparisons, as they are not likely
9710 /// to do what the programmer intended.
9711 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9712   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9713   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9714 
9715   // Special case: check for x == x (which is OK).
9716   // Do not emit warnings for such cases.
9717   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9718     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9719       if (DRL->getDecl() == DRR->getDecl())
9720         return;
9721 
9722   // Special case: check for comparisons against literals that can be exactly
9723   //  represented by APFloat.  In such cases, do not emit a warning.  This
9724   //  is a heuristic: often comparison against such literals are used to
9725   //  detect if a value in a variable has not changed.  This clearly can
9726   //  lead to false negatives.
9727   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9728     if (FLL->isExact())
9729       return;
9730   } else
9731     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9732       if (FLR->isExact())
9733         return;
9734 
9735   // Check for comparisons with builtin types.
9736   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9737     if (CL->getBuiltinCallee())
9738       return;
9739 
9740   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9741     if (CR->getBuiltinCallee())
9742       return;
9743 
9744   // Emit the diagnostic.
9745   Diag(Loc, diag::warn_floatingpoint_eq)
9746     << LHS->getSourceRange() << RHS->getSourceRange();
9747 }
9748 
9749 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9750 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9751 
9752 namespace {
9753 
9754 /// Structure recording the 'active' range of an integer-valued
9755 /// expression.
9756 struct IntRange {
9757   /// The number of bits active in the int.
9758   unsigned Width;
9759 
9760   /// True if the int is known not to have negative values.
9761   bool NonNegative;
9762 
9763   IntRange(unsigned Width, bool NonNegative)
9764       : Width(Width), NonNegative(NonNegative) {}
9765 
9766   /// Returns the range of the bool type.
9767   static IntRange forBoolType() {
9768     return IntRange(1, true);
9769   }
9770 
9771   /// Returns the range of an opaque value of the given integral type.
9772   static IntRange forValueOfType(ASTContext &C, QualType T) {
9773     return forValueOfCanonicalType(C,
9774                           T->getCanonicalTypeInternal().getTypePtr());
9775   }
9776 
9777   /// Returns the range of an opaque value of a canonical integral type.
9778   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9779     assert(T->isCanonicalUnqualified());
9780 
9781     if (const VectorType *VT = dyn_cast<VectorType>(T))
9782       T = VT->getElementType().getTypePtr();
9783     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9784       T = CT->getElementType().getTypePtr();
9785     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9786       T = AT->getValueType().getTypePtr();
9787 
9788     if (!C.getLangOpts().CPlusPlus) {
9789       // For enum types in C code, use the underlying datatype.
9790       if (const EnumType *ET = dyn_cast<EnumType>(T))
9791         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9792     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9793       // For enum types in C++, use the known bit width of the enumerators.
9794       EnumDecl *Enum = ET->getDecl();
9795       // In C++11, enums can have a fixed underlying type. Use this type to
9796       // compute the range.
9797       if (Enum->isFixed()) {
9798         return IntRange(C.getIntWidth(QualType(T, 0)),
9799                         !ET->isSignedIntegerOrEnumerationType());
9800       }
9801 
9802       unsigned NumPositive = Enum->getNumPositiveBits();
9803       unsigned NumNegative = Enum->getNumNegativeBits();
9804 
9805       if (NumNegative == 0)
9806         return IntRange(NumPositive, true/*NonNegative*/);
9807       else
9808         return IntRange(std::max(NumPositive + 1, NumNegative),
9809                         false/*NonNegative*/);
9810     }
9811 
9812     const BuiltinType *BT = cast<BuiltinType>(T);
9813     assert(BT->isInteger());
9814 
9815     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9816   }
9817 
9818   /// Returns the "target" range of a canonical integral type, i.e.
9819   /// the range of values expressible in the type.
9820   ///
9821   /// This matches forValueOfCanonicalType except that enums have the
9822   /// full range of their type, not the range of their enumerators.
9823   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9824     assert(T->isCanonicalUnqualified());
9825 
9826     if (const VectorType *VT = dyn_cast<VectorType>(T))
9827       T = VT->getElementType().getTypePtr();
9828     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9829       T = CT->getElementType().getTypePtr();
9830     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9831       T = AT->getValueType().getTypePtr();
9832     if (const EnumType *ET = dyn_cast<EnumType>(T))
9833       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9834 
9835     const BuiltinType *BT = cast<BuiltinType>(T);
9836     assert(BT->isInteger());
9837 
9838     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9839   }
9840 
9841   /// Returns the supremum of two ranges: i.e. their conservative merge.
9842   static IntRange join(IntRange L, IntRange R) {
9843     return IntRange(std::max(L.Width, R.Width),
9844                     L.NonNegative && R.NonNegative);
9845   }
9846 
9847   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9848   static IntRange meet(IntRange L, IntRange R) {
9849     return IntRange(std::min(L.Width, R.Width),
9850                     L.NonNegative || R.NonNegative);
9851   }
9852 };
9853 
9854 } // namespace
9855 
9856 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9857                               unsigned MaxWidth) {
9858   if (value.isSigned() && value.isNegative())
9859     return IntRange(value.getMinSignedBits(), false);
9860 
9861   if (value.getBitWidth() > MaxWidth)
9862     value = value.trunc(MaxWidth);
9863 
9864   // isNonNegative() just checks the sign bit without considering
9865   // signedness.
9866   return IntRange(value.getActiveBits(), true);
9867 }
9868 
9869 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9870                               unsigned MaxWidth) {
9871   if (result.isInt())
9872     return GetValueRange(C, result.getInt(), MaxWidth);
9873 
9874   if (result.isVector()) {
9875     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9876     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9877       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9878       R = IntRange::join(R, El);
9879     }
9880     return R;
9881   }
9882 
9883   if (result.isComplexInt()) {
9884     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9885     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9886     return IntRange::join(R, I);
9887   }
9888 
9889   // This can happen with lossless casts to intptr_t of "based" lvalues.
9890   // Assume it might use arbitrary bits.
9891   // FIXME: The only reason we need to pass the type in here is to get
9892   // the sign right on this one case.  It would be nice if APValue
9893   // preserved this.
9894   assert(result.isLValue() || result.isAddrLabelDiff());
9895   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9896 }
9897 
9898 static QualType GetExprType(const Expr *E) {
9899   QualType Ty = E->getType();
9900   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9901     Ty = AtomicRHS->getValueType();
9902   return Ty;
9903 }
9904 
9905 /// Pseudo-evaluate the given integer expression, estimating the
9906 /// range of values it might take.
9907 ///
9908 /// \param MaxWidth - the width to which the value will be truncated
9909 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
9910   E = E->IgnoreParens();
9911 
9912   // Try a full evaluation first.
9913   Expr::EvalResult result;
9914   if (E->EvaluateAsRValue(result, C))
9915     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9916 
9917   // I think we only want to look through implicit casts here; if the
9918   // user has an explicit widening cast, we should treat the value as
9919   // being of the new, wider type.
9920   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9921     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9922       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9923 
9924     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9925 
9926     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9927                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9928 
9929     // Assume that non-integer casts can span the full range of the type.
9930     if (!isIntegerCast)
9931       return OutputTypeRange;
9932 
9933     IntRange SubRange
9934       = GetExprRange(C, CE->getSubExpr(),
9935                      std::min(MaxWidth, OutputTypeRange.Width));
9936 
9937     // Bail out if the subexpr's range is as wide as the cast type.
9938     if (SubRange.Width >= OutputTypeRange.Width)
9939       return OutputTypeRange;
9940 
9941     // Otherwise, we take the smaller width, and we're non-negative if
9942     // either the output type or the subexpr is.
9943     return IntRange(SubRange.Width,
9944                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9945   }
9946 
9947   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9948     // If we can fold the condition, just take that operand.
9949     bool CondResult;
9950     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9951       return GetExprRange(C, CondResult ? CO->getTrueExpr()
9952                                         : CO->getFalseExpr(),
9953                           MaxWidth);
9954 
9955     // Otherwise, conservatively merge.
9956     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9957     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9958     return IntRange::join(L, R);
9959   }
9960 
9961   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9962     switch (BO->getOpcode()) {
9963     case BO_Cmp:
9964       llvm_unreachable("builtin <=> should have class type");
9965 
9966     // Boolean-valued operations are single-bit and positive.
9967     case BO_LAnd:
9968     case BO_LOr:
9969     case BO_LT:
9970     case BO_GT:
9971     case BO_LE:
9972     case BO_GE:
9973     case BO_EQ:
9974     case BO_NE:
9975       return IntRange::forBoolType();
9976 
9977     // The type of the assignments is the type of the LHS, so the RHS
9978     // is not necessarily the same type.
9979     case BO_MulAssign:
9980     case BO_DivAssign:
9981     case BO_RemAssign:
9982     case BO_AddAssign:
9983     case BO_SubAssign:
9984     case BO_XorAssign:
9985     case BO_OrAssign:
9986       // TODO: bitfields?
9987       return IntRange::forValueOfType(C, GetExprType(E));
9988 
9989     // Simple assignments just pass through the RHS, which will have
9990     // been coerced to the LHS type.
9991     case BO_Assign:
9992       // TODO: bitfields?
9993       return GetExprRange(C, BO->getRHS(), MaxWidth);
9994 
9995     // Operations with opaque sources are black-listed.
9996     case BO_PtrMemD:
9997     case BO_PtrMemI:
9998       return IntRange::forValueOfType(C, GetExprType(E));
9999 
10000     // Bitwise-and uses the *infinum* of the two source ranges.
10001     case BO_And:
10002     case BO_AndAssign:
10003       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
10004                             GetExprRange(C, BO->getRHS(), MaxWidth));
10005 
10006     // Left shift gets black-listed based on a judgement call.
10007     case BO_Shl:
10008       // ...except that we want to treat '1 << (blah)' as logically
10009       // positive.  It's an important idiom.
10010       if (IntegerLiteral *I
10011             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10012         if (I->getValue() == 1) {
10013           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10014           return IntRange(R.Width, /*NonNegative*/ true);
10015         }
10016       }
10017       LLVM_FALLTHROUGH;
10018 
10019     case BO_ShlAssign:
10020       return IntRange::forValueOfType(C, GetExprType(E));
10021 
10022     // Right shift by a constant can narrow its left argument.
10023     case BO_Shr:
10024     case BO_ShrAssign: {
10025       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
10026 
10027       // If the shift amount is a positive constant, drop the width by
10028       // that much.
10029       llvm::APSInt shift;
10030       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10031           shift.isNonNegative()) {
10032         unsigned zext = shift.getZExtValue();
10033         if (zext >= L.Width)
10034           L.Width = (L.NonNegative ? 0 : 1);
10035         else
10036           L.Width -= zext;
10037       }
10038 
10039       return L;
10040     }
10041 
10042     // Comma acts as its right operand.
10043     case BO_Comma:
10044       return GetExprRange(C, BO->getRHS(), MaxWidth);
10045 
10046     // Black-list pointer subtractions.
10047     case BO_Sub:
10048       if (BO->getLHS()->getType()->isPointerType())
10049         return IntRange::forValueOfType(C, GetExprType(E));
10050       break;
10051 
10052     // The width of a division result is mostly determined by the size
10053     // of the LHS.
10054     case BO_Div: {
10055       // Don't 'pre-truncate' the operands.
10056       unsigned opWidth = C.getIntWidth(GetExprType(E));
10057       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
10058 
10059       // If the divisor is constant, use that.
10060       llvm::APSInt divisor;
10061       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10062         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10063         if (log2 >= L.Width)
10064           L.Width = (L.NonNegative ? 0 : 1);
10065         else
10066           L.Width = std::min(L.Width - log2, MaxWidth);
10067         return L;
10068       }
10069 
10070       // Otherwise, just use the LHS's width.
10071       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
10072       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10073     }
10074 
10075     // The result of a remainder can't be larger than the result of
10076     // either side.
10077     case BO_Rem: {
10078       // Don't 'pre-truncate' the operands.
10079       unsigned opWidth = C.getIntWidth(GetExprType(E));
10080       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
10081       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
10082 
10083       IntRange meet = IntRange::meet(L, R);
10084       meet.Width = std::min(meet.Width, MaxWidth);
10085       return meet;
10086     }
10087 
10088     // The default behavior is okay for these.
10089     case BO_Mul:
10090     case BO_Add:
10091     case BO_Xor:
10092     case BO_Or:
10093       break;
10094     }
10095 
10096     // The default case is to treat the operation as if it were closed
10097     // on the narrowest type that encompasses both operands.
10098     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
10099     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
10100     return IntRange::join(L, R);
10101   }
10102 
10103   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10104     switch (UO->getOpcode()) {
10105     // Boolean-valued operations are white-listed.
10106     case UO_LNot:
10107       return IntRange::forBoolType();
10108 
10109     // Operations with opaque sources are black-listed.
10110     case UO_Deref:
10111     case UO_AddrOf: // should be impossible
10112       return IntRange::forValueOfType(C, GetExprType(E));
10113 
10114     default:
10115       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
10116     }
10117   }
10118 
10119   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10120     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
10121 
10122   if (const auto *BitField = E->getSourceBitField())
10123     return IntRange(BitField->getBitWidthValue(C),
10124                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10125 
10126   return IntRange::forValueOfType(C, GetExprType(E));
10127 }
10128 
10129 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
10130   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
10131 }
10132 
10133 /// Checks whether the given value, which currently has the given
10134 /// source semantics, has the same value when coerced through the
10135 /// target semantics.
10136 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10137                                  const llvm::fltSemantics &Src,
10138                                  const llvm::fltSemantics &Tgt) {
10139   llvm::APFloat truncated = value;
10140 
10141   bool ignored;
10142   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10143   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10144 
10145   return truncated.bitwiseIsEqual(value);
10146 }
10147 
10148 /// Checks whether the given value, which currently has the given
10149 /// source semantics, has the same value when coerced through the
10150 /// target semantics.
10151 ///
10152 /// The value might be a vector of floats (or a complex number).
10153 static bool IsSameFloatAfterCast(const APValue &value,
10154                                  const llvm::fltSemantics &Src,
10155                                  const llvm::fltSemantics &Tgt) {
10156   if (value.isFloat())
10157     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10158 
10159   if (value.isVector()) {
10160     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10161       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10162         return false;
10163     return true;
10164   }
10165 
10166   assert(value.isComplexFloat());
10167   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10168           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10169 }
10170 
10171 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
10172 
10173 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10174   // Suppress cases where we are comparing against an enum constant.
10175   if (const DeclRefExpr *DR =
10176       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10177     if (isa<EnumConstantDecl>(DR->getDecl()))
10178       return true;
10179 
10180   // Suppress cases where the '0' value is expanded from a macro.
10181   if (E->getBeginLoc().isMacroID())
10182     return true;
10183 
10184   return false;
10185 }
10186 
10187 static bool isKnownToHaveUnsignedValue(Expr *E) {
10188   return E->getType()->isIntegerType() &&
10189          (!E->getType()->isSignedIntegerType() ||
10190           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10191 }
10192 
10193 namespace {
10194 /// The promoted range of values of a type. In general this has the
10195 /// following structure:
10196 ///
10197 ///     |-----------| . . . |-----------|
10198 ///     ^           ^       ^           ^
10199 ///    Min       HoleMin  HoleMax      Max
10200 ///
10201 /// ... where there is only a hole if a signed type is promoted to unsigned
10202 /// (in which case Min and Max are the smallest and largest representable
10203 /// values).
10204 struct PromotedRange {
10205   // Min, or HoleMax if there is a hole.
10206   llvm::APSInt PromotedMin;
10207   // Max, or HoleMin if there is a hole.
10208   llvm::APSInt PromotedMax;
10209 
10210   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10211     if (R.Width == 0)
10212       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10213     else if (R.Width >= BitWidth && !Unsigned) {
10214       // Promotion made the type *narrower*. This happens when promoting
10215       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10216       // Treat all values of 'signed int' as being in range for now.
10217       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10218       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10219     } else {
10220       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10221                         .extOrTrunc(BitWidth);
10222       PromotedMin.setIsUnsigned(Unsigned);
10223 
10224       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10225                         .extOrTrunc(BitWidth);
10226       PromotedMax.setIsUnsigned(Unsigned);
10227     }
10228   }
10229 
10230   // Determine whether this range is contiguous (has no hole).
10231   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10232 
10233   // Where a constant value is within the range.
10234   enum ComparisonResult {
10235     LT = 0x1,
10236     LE = 0x2,
10237     GT = 0x4,
10238     GE = 0x8,
10239     EQ = 0x10,
10240     NE = 0x20,
10241     InRangeFlag = 0x40,
10242 
10243     Less = LE | LT | NE,
10244     Min = LE | InRangeFlag,
10245     InRange = InRangeFlag,
10246     Max = GE | InRangeFlag,
10247     Greater = GE | GT | NE,
10248 
10249     OnlyValue = LE | GE | EQ | InRangeFlag,
10250     InHole = NE
10251   };
10252 
10253   ComparisonResult compare(const llvm::APSInt &Value) const {
10254     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10255            Value.isUnsigned() == PromotedMin.isUnsigned());
10256     if (!isContiguous()) {
10257       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10258       if (Value.isMinValue()) return Min;
10259       if (Value.isMaxValue()) return Max;
10260       if (Value >= PromotedMin) return InRange;
10261       if (Value <= PromotedMax) return InRange;
10262       return InHole;
10263     }
10264 
10265     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10266     case -1: return Less;
10267     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10268     case 1:
10269       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10270       case -1: return InRange;
10271       case 0: return Max;
10272       case 1: return Greater;
10273       }
10274     }
10275 
10276     llvm_unreachable("impossible compare result");
10277   }
10278 
10279   static llvm::Optional<StringRef>
10280   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10281     if (Op == BO_Cmp) {
10282       ComparisonResult LTFlag = LT, GTFlag = GT;
10283       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10284 
10285       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10286       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10287       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10288       return llvm::None;
10289     }
10290 
10291     ComparisonResult TrueFlag, FalseFlag;
10292     if (Op == BO_EQ) {
10293       TrueFlag = EQ;
10294       FalseFlag = NE;
10295     } else if (Op == BO_NE) {
10296       TrueFlag = NE;
10297       FalseFlag = EQ;
10298     } else {
10299       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10300         TrueFlag = LT;
10301         FalseFlag = GE;
10302       } else {
10303         TrueFlag = GT;
10304         FalseFlag = LE;
10305       }
10306       if (Op == BO_GE || Op == BO_LE)
10307         std::swap(TrueFlag, FalseFlag);
10308     }
10309     if (R & TrueFlag)
10310       return StringRef("true");
10311     if (R & FalseFlag)
10312       return StringRef("false");
10313     return llvm::None;
10314   }
10315 };
10316 }
10317 
10318 static bool HasEnumType(Expr *E) {
10319   // Strip off implicit integral promotions.
10320   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10321     if (ICE->getCastKind() != CK_IntegralCast &&
10322         ICE->getCastKind() != CK_NoOp)
10323       break;
10324     E = ICE->getSubExpr();
10325   }
10326 
10327   return E->getType()->isEnumeralType();
10328 }
10329 
10330 static int classifyConstantValue(Expr *Constant) {
10331   // The values of this enumeration are used in the diagnostics
10332   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10333   enum ConstantValueKind {
10334     Miscellaneous = 0,
10335     LiteralTrue,
10336     LiteralFalse
10337   };
10338   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10339     return BL->getValue() ? ConstantValueKind::LiteralTrue
10340                           : ConstantValueKind::LiteralFalse;
10341   return ConstantValueKind::Miscellaneous;
10342 }
10343 
10344 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10345                                         Expr *Constant, Expr *Other,
10346                                         const llvm::APSInt &Value,
10347                                         bool RhsConstant) {
10348   if (S.inTemplateInstantiation())
10349     return false;
10350 
10351   Expr *OriginalOther = Other;
10352 
10353   Constant = Constant->IgnoreParenImpCasts();
10354   Other = Other->IgnoreParenImpCasts();
10355 
10356   // Suppress warnings on tautological comparisons between values of the same
10357   // enumeration type. There are only two ways we could warn on this:
10358   //  - If the constant is outside the range of representable values of
10359   //    the enumeration. In such a case, we should warn about the cast
10360   //    to enumeration type, not about the comparison.
10361   //  - If the constant is the maximum / minimum in-range value. For an
10362   //    enumeratin type, such comparisons can be meaningful and useful.
10363   if (Constant->getType()->isEnumeralType() &&
10364       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10365     return false;
10366 
10367   // TODO: Investigate using GetExprRange() to get tighter bounds
10368   // on the bit ranges.
10369   QualType OtherT = Other->getType();
10370   if (const auto *AT = OtherT->getAs<AtomicType>())
10371     OtherT = AT->getValueType();
10372   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10373 
10374   // Whether we're treating Other as being a bool because of the form of
10375   // expression despite it having another type (typically 'int' in C).
10376   bool OtherIsBooleanDespiteType =
10377       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10378   if (OtherIsBooleanDespiteType)
10379     OtherRange = IntRange::forBoolType();
10380 
10381   // Determine the promoted range of the other type and see if a comparison of
10382   // the constant against that range is tautological.
10383   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10384                                    Value.isUnsigned());
10385   auto Cmp = OtherPromotedRange.compare(Value);
10386   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10387   if (!Result)
10388     return false;
10389 
10390   // Suppress the diagnostic for an in-range comparison if the constant comes
10391   // from a macro or enumerator. We don't want to diagnose
10392   //
10393   //   some_long_value <= INT_MAX
10394   //
10395   // when sizeof(int) == sizeof(long).
10396   bool InRange = Cmp & PromotedRange::InRangeFlag;
10397   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10398     return false;
10399 
10400   // If this is a comparison to an enum constant, include that
10401   // constant in the diagnostic.
10402   const EnumConstantDecl *ED = nullptr;
10403   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10404     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10405 
10406   // Should be enough for uint128 (39 decimal digits)
10407   SmallString<64> PrettySourceValue;
10408   llvm::raw_svector_ostream OS(PrettySourceValue);
10409   if (ED)
10410     OS << '\'' << *ED << "' (" << Value << ")";
10411   else
10412     OS << Value;
10413 
10414   // FIXME: We use a somewhat different formatting for the in-range cases and
10415   // cases involving boolean values for historical reasons. We should pick a
10416   // consistent way of presenting these diagnostics.
10417   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10418     S.DiagRuntimeBehavior(
10419       E->getOperatorLoc(), E,
10420       S.PDiag(!InRange ? diag::warn_out_of_range_compare
10421                        : diag::warn_tautological_bool_compare)
10422           << OS.str() << classifyConstantValue(Constant)
10423           << OtherT << OtherIsBooleanDespiteType << *Result
10424           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10425   } else {
10426     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10427                         ? (HasEnumType(OriginalOther)
10428                                ? diag::warn_unsigned_enum_always_true_comparison
10429                                : diag::warn_unsigned_always_true_comparison)
10430                         : diag::warn_tautological_constant_compare;
10431 
10432     S.Diag(E->getOperatorLoc(), Diag)
10433         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10434         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10435   }
10436 
10437   return true;
10438 }
10439 
10440 /// Analyze the operands of the given comparison.  Implements the
10441 /// fallback case from AnalyzeComparison.
10442 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10443   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10444   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10445 }
10446 
10447 /// Implements -Wsign-compare.
10448 ///
10449 /// \param E the binary operator to check for warnings
10450 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10451   // The type the comparison is being performed in.
10452   QualType T = E->getLHS()->getType();
10453 
10454   // Only analyze comparison operators where both sides have been converted to
10455   // the same type.
10456   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10457     return AnalyzeImpConvsInComparison(S, E);
10458 
10459   // Don't analyze value-dependent comparisons directly.
10460   if (E->isValueDependent())
10461     return AnalyzeImpConvsInComparison(S, E);
10462 
10463   Expr *LHS = E->getLHS();
10464   Expr *RHS = E->getRHS();
10465 
10466   if (T->isIntegralType(S.Context)) {
10467     llvm::APSInt RHSValue;
10468     llvm::APSInt LHSValue;
10469 
10470     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10471     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10472 
10473     // We don't care about expressions whose result is a constant.
10474     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10475       return AnalyzeImpConvsInComparison(S, E);
10476 
10477     // We only care about expressions where just one side is literal
10478     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10479       // Is the constant on the RHS or LHS?
10480       const bool RhsConstant = IsRHSIntegralLiteral;
10481       Expr *Const = RhsConstant ? RHS : LHS;
10482       Expr *Other = RhsConstant ? LHS : RHS;
10483       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10484 
10485       // Check whether an integer constant comparison results in a value
10486       // of 'true' or 'false'.
10487       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10488         return AnalyzeImpConvsInComparison(S, E);
10489     }
10490   }
10491 
10492   if (!T->hasUnsignedIntegerRepresentation()) {
10493     // We don't do anything special if this isn't an unsigned integral
10494     // comparison:  we're only interested in integral comparisons, and
10495     // signed comparisons only happen in cases we don't care to warn about.
10496     return AnalyzeImpConvsInComparison(S, E);
10497   }
10498 
10499   LHS = LHS->IgnoreParenImpCasts();
10500   RHS = RHS->IgnoreParenImpCasts();
10501 
10502   if (!S.getLangOpts().CPlusPlus) {
10503     // Avoid warning about comparison of integers with different signs when
10504     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10505     // the type of `E`.
10506     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10507       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10508     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10509       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10510   }
10511 
10512   // Check to see if one of the (unmodified) operands is of different
10513   // signedness.
10514   Expr *signedOperand, *unsignedOperand;
10515   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10516     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10517            "unsigned comparison between two signed integer expressions?");
10518     signedOperand = LHS;
10519     unsignedOperand = RHS;
10520   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10521     signedOperand = RHS;
10522     unsignedOperand = LHS;
10523   } else {
10524     return AnalyzeImpConvsInComparison(S, E);
10525   }
10526 
10527   // Otherwise, calculate the effective range of the signed operand.
10528   IntRange signedRange = GetExprRange(S.Context, signedOperand);
10529 
10530   // Go ahead and analyze implicit conversions in the operands.  Note
10531   // that we skip the implicit conversions on both sides.
10532   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10533   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10534 
10535   // If the signed range is non-negative, -Wsign-compare won't fire.
10536   if (signedRange.NonNegative)
10537     return;
10538 
10539   // For (in)equality comparisons, if the unsigned operand is a
10540   // constant which cannot collide with a overflowed signed operand,
10541   // then reinterpreting the signed operand as unsigned will not
10542   // change the result of the comparison.
10543   if (E->isEqualityOp()) {
10544     unsigned comparisonWidth = S.Context.getIntWidth(T);
10545     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
10546 
10547     // We should never be unable to prove that the unsigned operand is
10548     // non-negative.
10549     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10550 
10551     if (unsignedRange.Width < comparisonWidth)
10552       return;
10553   }
10554 
10555   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10556     S.PDiag(diag::warn_mixed_sign_comparison)
10557       << LHS->getType() << RHS->getType()
10558       << LHS->getSourceRange() << RHS->getSourceRange());
10559 }
10560 
10561 /// Analyzes an attempt to assign the given value to a bitfield.
10562 ///
10563 /// Returns true if there was something fishy about the attempt.
10564 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10565                                       SourceLocation InitLoc) {
10566   assert(Bitfield->isBitField());
10567   if (Bitfield->isInvalidDecl())
10568     return false;
10569 
10570   // White-list bool bitfields.
10571   QualType BitfieldType = Bitfield->getType();
10572   if (BitfieldType->isBooleanType())
10573      return false;
10574 
10575   if (BitfieldType->isEnumeralType()) {
10576     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10577     // If the underlying enum type was not explicitly specified as an unsigned
10578     // type and the enum contain only positive values, MSVC++ will cause an
10579     // inconsistency by storing this as a signed type.
10580     if (S.getLangOpts().CPlusPlus11 &&
10581         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10582         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10583         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10584       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10585         << BitfieldEnumDecl->getNameAsString();
10586     }
10587   }
10588 
10589   if (Bitfield->getType()->isBooleanType())
10590     return false;
10591 
10592   // Ignore value- or type-dependent expressions.
10593   if (Bitfield->getBitWidth()->isValueDependent() ||
10594       Bitfield->getBitWidth()->isTypeDependent() ||
10595       Init->isValueDependent() ||
10596       Init->isTypeDependent())
10597     return false;
10598 
10599   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10600   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10601 
10602   Expr::EvalResult Result;
10603   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10604                                    Expr::SE_AllowSideEffects)) {
10605     // The RHS is not constant.  If the RHS has an enum type, make sure the
10606     // bitfield is wide enough to hold all the values of the enum without
10607     // truncation.
10608     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10609       EnumDecl *ED = EnumTy->getDecl();
10610       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10611 
10612       // Enum types are implicitly signed on Windows, so check if there are any
10613       // negative enumerators to see if the enum was intended to be signed or
10614       // not.
10615       bool SignedEnum = ED->getNumNegativeBits() > 0;
10616 
10617       // Check for surprising sign changes when assigning enum values to a
10618       // bitfield of different signedness.  If the bitfield is signed and we
10619       // have exactly the right number of bits to store this unsigned enum,
10620       // suggest changing the enum to an unsigned type. This typically happens
10621       // on Windows where unfixed enums always use an underlying type of 'int'.
10622       unsigned DiagID = 0;
10623       if (SignedEnum && !SignedBitfield) {
10624         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10625       } else if (SignedBitfield && !SignedEnum &&
10626                  ED->getNumPositiveBits() == FieldWidth) {
10627         DiagID = diag::warn_signed_bitfield_enum_conversion;
10628       }
10629 
10630       if (DiagID) {
10631         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10632         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10633         SourceRange TypeRange =
10634             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10635         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10636             << SignedEnum << TypeRange;
10637       }
10638 
10639       // Compute the required bitwidth. If the enum has negative values, we need
10640       // one more bit than the normal number of positive bits to represent the
10641       // sign bit.
10642       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10643                                                   ED->getNumNegativeBits())
10644                                        : ED->getNumPositiveBits();
10645 
10646       // Check the bitwidth.
10647       if (BitsNeeded > FieldWidth) {
10648         Expr *WidthExpr = Bitfield->getBitWidth();
10649         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10650             << Bitfield << ED;
10651         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10652             << BitsNeeded << ED << WidthExpr->getSourceRange();
10653       }
10654     }
10655 
10656     return false;
10657   }
10658 
10659   llvm::APSInt Value = Result.Val.getInt();
10660 
10661   unsigned OriginalWidth = Value.getBitWidth();
10662 
10663   if (!Value.isSigned() || Value.isNegative())
10664     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10665       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10666         OriginalWidth = Value.getMinSignedBits();
10667 
10668   if (OriginalWidth <= FieldWidth)
10669     return false;
10670 
10671   // Compute the value which the bitfield will contain.
10672   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10673   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10674 
10675   // Check whether the stored value is equal to the original value.
10676   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10677   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10678     return false;
10679 
10680   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10681   // therefore don't strictly fit into a signed bitfield of width 1.
10682   if (FieldWidth == 1 && Value == 1)
10683     return false;
10684 
10685   std::string PrettyValue = Value.toString(10);
10686   std::string PrettyTrunc = TruncatedValue.toString(10);
10687 
10688   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10689     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10690     << Init->getSourceRange();
10691 
10692   return true;
10693 }
10694 
10695 /// Analyze the given simple or compound assignment for warning-worthy
10696 /// operations.
10697 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10698   // Just recurse on the LHS.
10699   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10700 
10701   // We want to recurse on the RHS as normal unless we're assigning to
10702   // a bitfield.
10703   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10704     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10705                                   E->getOperatorLoc())) {
10706       // Recurse, ignoring any implicit conversions on the RHS.
10707       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10708                                         E->getOperatorLoc());
10709     }
10710   }
10711 
10712   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10713 
10714   // Diagnose implicitly sequentially-consistent atomic assignment.
10715   if (E->getLHS()->getType()->isAtomicType())
10716     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10717 }
10718 
10719 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10720 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10721                             SourceLocation CContext, unsigned diag,
10722                             bool pruneControlFlow = false) {
10723   if (pruneControlFlow) {
10724     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10725                           S.PDiag(diag)
10726                             << SourceType << T << E->getSourceRange()
10727                             << SourceRange(CContext));
10728     return;
10729   }
10730   S.Diag(E->getExprLoc(), diag)
10731     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10732 }
10733 
10734 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10735 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10736                             SourceLocation CContext,
10737                             unsigned diag, bool pruneControlFlow = false) {
10738   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10739 }
10740 
10741 /// Diagnose an implicit cast from a floating point value to an integer value.
10742 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10743                                     SourceLocation CContext) {
10744   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10745   const bool PruneWarnings = S.inTemplateInstantiation();
10746 
10747   Expr *InnerE = E->IgnoreParenImpCasts();
10748   // We also want to warn on, e.g., "int i = -1.234"
10749   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10750     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10751       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10752 
10753   const bool IsLiteral =
10754       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10755 
10756   llvm::APFloat Value(0.0);
10757   bool IsConstant =
10758     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10759   if (!IsConstant) {
10760     return DiagnoseImpCast(S, E, T, CContext,
10761                            diag::warn_impcast_float_integer, PruneWarnings);
10762   }
10763 
10764   bool isExact = false;
10765 
10766   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10767                             T->hasUnsignedIntegerRepresentation());
10768   llvm::APFloat::opStatus Result = Value.convertToInteger(
10769       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10770 
10771   if (Result == llvm::APFloat::opOK && isExact) {
10772     if (IsLiteral) return;
10773     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10774                            PruneWarnings);
10775   }
10776 
10777   // Conversion of a floating-point value to a non-bool integer where the
10778   // integral part cannot be represented by the integer type is undefined.
10779   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10780     return DiagnoseImpCast(
10781         S, E, T, CContext,
10782         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10783                   : diag::warn_impcast_float_to_integer_out_of_range,
10784         PruneWarnings);
10785 
10786   unsigned DiagID = 0;
10787   if (IsLiteral) {
10788     // Warn on floating point literal to integer.
10789     DiagID = diag::warn_impcast_literal_float_to_integer;
10790   } else if (IntegerValue == 0) {
10791     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10792       return DiagnoseImpCast(S, E, T, CContext,
10793                              diag::warn_impcast_float_integer, PruneWarnings);
10794     }
10795     // Warn on non-zero to zero conversion.
10796     DiagID = diag::warn_impcast_float_to_integer_zero;
10797   } else {
10798     if (IntegerValue.isUnsigned()) {
10799       if (!IntegerValue.isMaxValue()) {
10800         return DiagnoseImpCast(S, E, T, CContext,
10801                                diag::warn_impcast_float_integer, PruneWarnings);
10802       }
10803     } else {  // IntegerValue.isSigned()
10804       if (!IntegerValue.isMaxSignedValue() &&
10805           !IntegerValue.isMinSignedValue()) {
10806         return DiagnoseImpCast(S, E, T, CContext,
10807                                diag::warn_impcast_float_integer, PruneWarnings);
10808       }
10809     }
10810     // Warn on evaluatable floating point expression to integer conversion.
10811     DiagID = diag::warn_impcast_float_to_integer;
10812   }
10813 
10814   // FIXME: Force the precision of the source value down so we don't print
10815   // digits which are usually useless (we don't really care here if we
10816   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10817   // would automatically print the shortest representation, but it's a bit
10818   // tricky to implement.
10819   SmallString<16> PrettySourceValue;
10820   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10821   precision = (precision * 59 + 195) / 196;
10822   Value.toString(PrettySourceValue, precision);
10823 
10824   SmallString<16> PrettyTargetValue;
10825   if (IsBool)
10826     PrettyTargetValue = Value.isZero() ? "false" : "true";
10827   else
10828     IntegerValue.toString(PrettyTargetValue);
10829 
10830   if (PruneWarnings) {
10831     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10832                           S.PDiag(DiagID)
10833                               << E->getType() << T.getUnqualifiedType()
10834                               << PrettySourceValue << PrettyTargetValue
10835                               << E->getSourceRange() << SourceRange(CContext));
10836   } else {
10837     S.Diag(E->getExprLoc(), DiagID)
10838         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10839         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10840   }
10841 }
10842 
10843 /// Analyze the given compound assignment for the possible losing of
10844 /// floating-point precision.
10845 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10846   assert(isa<CompoundAssignOperator>(E) &&
10847          "Must be compound assignment operation");
10848   // Recurse on the LHS and RHS in here
10849   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10850   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10851 
10852   if (E->getLHS()->getType()->isAtomicType())
10853     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10854 
10855   // Now check the outermost expression
10856   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10857   const auto *RBT = cast<CompoundAssignOperator>(E)
10858                         ->getComputationResultType()
10859                         ->getAs<BuiltinType>();
10860 
10861   // The below checks assume source is floating point.
10862   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10863 
10864   // If source is floating point but target is an integer.
10865   if (ResultBT->isInteger())
10866     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10867                            E->getExprLoc(), diag::warn_impcast_float_integer);
10868 
10869   if (!ResultBT->isFloatingPoint())
10870     return;
10871 
10872   // If both source and target are floating points, warn about losing precision.
10873   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10874       QualType(ResultBT, 0), QualType(RBT, 0));
10875   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10876     // warn about dropping FP rank.
10877     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10878                     diag::warn_impcast_float_result_precision);
10879 }
10880 
10881 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10882                                       IntRange Range) {
10883   if (!Range.Width) return "0";
10884 
10885   llvm::APSInt ValueInRange = Value;
10886   ValueInRange.setIsSigned(!Range.NonNegative);
10887   ValueInRange = ValueInRange.trunc(Range.Width);
10888   return ValueInRange.toString(10);
10889 }
10890 
10891 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10892   if (!isa<ImplicitCastExpr>(Ex))
10893     return false;
10894 
10895   Expr *InnerE = Ex->IgnoreParenImpCasts();
10896   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10897   const Type *Source =
10898     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10899   if (Target->isDependentType())
10900     return false;
10901 
10902   const BuiltinType *FloatCandidateBT =
10903     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10904   const Type *BoolCandidateType = ToBool ? Target : Source;
10905 
10906   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10907           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10908 }
10909 
10910 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10911                                              SourceLocation CC) {
10912   unsigned NumArgs = TheCall->getNumArgs();
10913   for (unsigned i = 0; i < NumArgs; ++i) {
10914     Expr *CurrA = TheCall->getArg(i);
10915     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10916       continue;
10917 
10918     bool IsSwapped = ((i > 0) &&
10919         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10920     IsSwapped |= ((i < (NumArgs - 1)) &&
10921         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10922     if (IsSwapped) {
10923       // Warn on this floating-point to bool conversion.
10924       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10925                       CurrA->getType(), CC,
10926                       diag::warn_impcast_floating_point_to_bool);
10927     }
10928   }
10929 }
10930 
10931 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10932                                    SourceLocation CC) {
10933   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10934                         E->getExprLoc()))
10935     return;
10936 
10937   // Don't warn on functions which have return type nullptr_t.
10938   if (isa<CallExpr>(E))
10939     return;
10940 
10941   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10942   const Expr::NullPointerConstantKind NullKind =
10943       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10944   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10945     return;
10946 
10947   // Return if target type is a safe conversion.
10948   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10949       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10950     return;
10951 
10952   SourceLocation Loc = E->getSourceRange().getBegin();
10953 
10954   // Venture through the macro stacks to get to the source of macro arguments.
10955   // The new location is a better location than the complete location that was
10956   // passed in.
10957   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10958   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10959 
10960   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10961   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10962     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10963         Loc, S.SourceMgr, S.getLangOpts());
10964     if (MacroName == "NULL")
10965       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10966   }
10967 
10968   // Only warn if the null and context location are in the same macro expansion.
10969   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10970     return;
10971 
10972   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10973       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10974       << FixItHint::CreateReplacement(Loc,
10975                                       S.getFixItZeroLiteralForType(T, Loc));
10976 }
10977 
10978 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10979                                   ObjCArrayLiteral *ArrayLiteral);
10980 
10981 static void
10982 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10983                            ObjCDictionaryLiteral *DictionaryLiteral);
10984 
10985 /// Check a single element within a collection literal against the
10986 /// target element type.
10987 static void checkObjCCollectionLiteralElement(Sema &S,
10988                                               QualType TargetElementType,
10989                                               Expr *Element,
10990                                               unsigned ElementKind) {
10991   // Skip a bitcast to 'id' or qualified 'id'.
10992   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10993     if (ICE->getCastKind() == CK_BitCast &&
10994         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10995       Element = ICE->getSubExpr();
10996   }
10997 
10998   QualType ElementType = Element->getType();
10999   ExprResult ElementResult(Element);
11000   if (ElementType->getAs<ObjCObjectPointerType>() &&
11001       S.CheckSingleAssignmentConstraints(TargetElementType,
11002                                          ElementResult,
11003                                          false, false)
11004         != Sema::Compatible) {
11005     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11006         << ElementType << ElementKind << TargetElementType
11007         << Element->getSourceRange();
11008   }
11009 
11010   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11011     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11012   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11013     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11014 }
11015 
11016 /// Check an Objective-C array literal being converted to the given
11017 /// target type.
11018 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11019                                   ObjCArrayLiteral *ArrayLiteral) {
11020   if (!S.NSArrayDecl)
11021     return;
11022 
11023   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11024   if (!TargetObjCPtr)
11025     return;
11026 
11027   if (TargetObjCPtr->isUnspecialized() ||
11028       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11029         != S.NSArrayDecl->getCanonicalDecl())
11030     return;
11031 
11032   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11033   if (TypeArgs.size() != 1)
11034     return;
11035 
11036   QualType TargetElementType = TypeArgs[0];
11037   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11038     checkObjCCollectionLiteralElement(S, TargetElementType,
11039                                       ArrayLiteral->getElement(I),
11040                                       0);
11041   }
11042 }
11043 
11044 /// Check an Objective-C dictionary literal being converted to the given
11045 /// target type.
11046 static void
11047 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11048                            ObjCDictionaryLiteral *DictionaryLiteral) {
11049   if (!S.NSDictionaryDecl)
11050     return;
11051 
11052   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11053   if (!TargetObjCPtr)
11054     return;
11055 
11056   if (TargetObjCPtr->isUnspecialized() ||
11057       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11058         != S.NSDictionaryDecl->getCanonicalDecl())
11059     return;
11060 
11061   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11062   if (TypeArgs.size() != 2)
11063     return;
11064 
11065   QualType TargetKeyType = TypeArgs[0];
11066   QualType TargetObjectType = TypeArgs[1];
11067   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11068     auto Element = DictionaryLiteral->getKeyValueElement(I);
11069     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11070     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11071   }
11072 }
11073 
11074 // Helper function to filter out cases for constant width constant conversion.
11075 // Don't warn on char array initialization or for non-decimal values.
11076 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11077                                           SourceLocation CC) {
11078   // If initializing from a constant, and the constant starts with '0',
11079   // then it is a binary, octal, or hexadecimal.  Allow these constants
11080   // to fill all the bits, even if there is a sign change.
11081   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11082     const char FirstLiteralCharacter =
11083         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11084     if (FirstLiteralCharacter == '0')
11085       return false;
11086   }
11087 
11088   // If the CC location points to a '{', and the type is char, then assume
11089   // assume it is an array initialization.
11090   if (CC.isValid() && T->isCharType()) {
11091     const char FirstContextCharacter =
11092         S.getSourceManager().getCharacterData(CC)[0];
11093     if (FirstContextCharacter == '{')
11094       return false;
11095   }
11096 
11097   return true;
11098 }
11099 
11100 static void
11101 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
11102                         bool *ICContext = nullptr) {
11103   if (E->isTypeDependent() || E->isValueDependent()) return;
11104 
11105   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11106   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11107   if (Source == Target) return;
11108   if (Target->isDependentType()) return;
11109 
11110   // If the conversion context location is invalid don't complain. We also
11111   // don't want to emit a warning if the issue occurs from the expansion of
11112   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11113   // delay this check as long as possible. Once we detect we are in that
11114   // scenario, we just return.
11115   if (CC.isInvalid())
11116     return;
11117 
11118   if (Source->isAtomicType())
11119     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11120 
11121   // Diagnose implicit casts to bool.
11122   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11123     if (isa<StringLiteral>(E))
11124       // Warn on string literal to bool.  Checks for string literals in logical
11125       // and expressions, for instance, assert(0 && "error here"), are
11126       // prevented by a check in AnalyzeImplicitConversions().
11127       return DiagnoseImpCast(S, E, T, CC,
11128                              diag::warn_impcast_string_literal_to_bool);
11129     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11130         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11131       // This covers the literal expressions that evaluate to Objective-C
11132       // objects.
11133       return DiagnoseImpCast(S, E, T, CC,
11134                              diag::warn_impcast_objective_c_literal_to_bool);
11135     }
11136     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11137       // Warn on pointer to bool conversion that is always true.
11138       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11139                                      SourceRange(CC));
11140     }
11141   }
11142 
11143   // Check implicit casts from Objective-C collection literals to specialized
11144   // collection types, e.g., NSArray<NSString *> *.
11145   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11146     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11147   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11148     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11149 
11150   // Strip vector types.
11151   if (isa<VectorType>(Source)) {
11152     if (!isa<VectorType>(Target)) {
11153       if (S.SourceMgr.isInSystemMacro(CC))
11154         return;
11155       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11156     }
11157 
11158     // If the vector cast is cast between two vectors of the same size, it is
11159     // a bitcast, not a conversion.
11160     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11161       return;
11162 
11163     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11164     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11165   }
11166   if (auto VecTy = dyn_cast<VectorType>(Target))
11167     Target = VecTy->getElementType().getTypePtr();
11168 
11169   // Strip complex types.
11170   if (isa<ComplexType>(Source)) {
11171     if (!isa<ComplexType>(Target)) {
11172       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11173         return;
11174 
11175       return DiagnoseImpCast(S, E, T, CC,
11176                              S.getLangOpts().CPlusPlus
11177                                  ? diag::err_impcast_complex_scalar
11178                                  : diag::warn_impcast_complex_scalar);
11179     }
11180 
11181     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11182     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11183   }
11184 
11185   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11186   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11187 
11188   // If the source is floating point...
11189   if (SourceBT && SourceBT->isFloatingPoint()) {
11190     // ...and the target is floating point...
11191     if (TargetBT && TargetBT->isFloatingPoint()) {
11192       // ...then warn if we're dropping FP rank.
11193 
11194       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11195           QualType(SourceBT, 0), QualType(TargetBT, 0));
11196       if (Order > 0) {
11197         // Don't warn about float constants that are precisely
11198         // representable in the target type.
11199         Expr::EvalResult result;
11200         if (E->EvaluateAsRValue(result, S.Context)) {
11201           // Value might be a float, a float vector, or a float complex.
11202           if (IsSameFloatAfterCast(result.Val,
11203                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11204                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11205             return;
11206         }
11207 
11208         if (S.SourceMgr.isInSystemMacro(CC))
11209           return;
11210 
11211         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11212       }
11213       // ... or possibly if we're increasing rank, too
11214       else if (Order < 0) {
11215         if (S.SourceMgr.isInSystemMacro(CC))
11216           return;
11217 
11218         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11219       }
11220       return;
11221     }
11222 
11223     // If the target is integral, always warn.
11224     if (TargetBT && TargetBT->isInteger()) {
11225       if (S.SourceMgr.isInSystemMacro(CC))
11226         return;
11227 
11228       DiagnoseFloatingImpCast(S, E, T, CC);
11229     }
11230 
11231     // Detect the case where a call result is converted from floating-point to
11232     // to bool, and the final argument to the call is converted from bool, to
11233     // discover this typo:
11234     //
11235     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11236     //
11237     // FIXME: This is an incredibly special case; is there some more general
11238     // way to detect this class of misplaced-parentheses bug?
11239     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11240       // Check last argument of function call to see if it is an
11241       // implicit cast from a type matching the type the result
11242       // is being cast to.
11243       CallExpr *CEx = cast<CallExpr>(E);
11244       if (unsigned NumArgs = CEx->getNumArgs()) {
11245         Expr *LastA = CEx->getArg(NumArgs - 1);
11246         Expr *InnerE = LastA->IgnoreParenImpCasts();
11247         if (isa<ImplicitCastExpr>(LastA) &&
11248             InnerE->getType()->isBooleanType()) {
11249           // Warn on this floating-point to bool conversion
11250           DiagnoseImpCast(S, E, T, CC,
11251                           diag::warn_impcast_floating_point_to_bool);
11252         }
11253       }
11254     }
11255     return;
11256   }
11257 
11258   // Valid casts involving fixed point types should be accounted for here.
11259   if (Source->isFixedPointType()) {
11260     if (Target->isUnsaturatedFixedPointType()) {
11261       Expr::EvalResult Result;
11262       if (E->EvaluateAsFixedPoint(Result, S.Context,
11263                                   Expr::SE_AllowSideEffects)) {
11264         APFixedPoint Value = Result.Val.getFixedPoint();
11265         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11266         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11267         if (Value > MaxVal || Value < MinVal) {
11268           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11269                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11270                                     << Value.toString() << T
11271                                     << E->getSourceRange()
11272                                     << clang::SourceRange(CC));
11273           return;
11274         }
11275       }
11276     } else if (Target->isIntegerType()) {
11277       Expr::EvalResult Result;
11278       if (E->EvaluateAsFixedPoint(Result, S.Context,
11279                                   Expr::SE_AllowSideEffects)) {
11280         APFixedPoint FXResult = Result.Val.getFixedPoint();
11281 
11282         bool Overflowed;
11283         llvm::APSInt IntResult = FXResult.convertToInt(
11284             S.Context.getIntWidth(T),
11285             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11286 
11287         if (Overflowed) {
11288           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11289                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11290                                     << FXResult.toString() << T
11291                                     << E->getSourceRange()
11292                                     << clang::SourceRange(CC));
11293           return;
11294         }
11295       }
11296     }
11297   } else if (Target->isUnsaturatedFixedPointType()) {
11298     if (Source->isIntegerType()) {
11299       Expr::EvalResult Result;
11300       if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11301         llvm::APSInt Value = Result.Val.getInt();
11302 
11303         bool Overflowed;
11304         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11305             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11306 
11307         if (Overflowed) {
11308           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11309                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11310                                     << Value.toString(/*radix=*/10) << T
11311                                     << E->getSourceRange()
11312                                     << clang::SourceRange(CC));
11313           return;
11314         }
11315       }
11316     }
11317   }
11318 
11319   DiagnoseNullConversion(S, E, T, CC);
11320 
11321   S.DiscardMisalignedMemberAddress(Target, E);
11322 
11323   if (!Source->isIntegerType() || !Target->isIntegerType())
11324     return;
11325 
11326   // TODO: remove this early return once the false positives for constant->bool
11327   // in templates, macros, etc, are reduced or removed.
11328   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11329     return;
11330 
11331   IntRange SourceRange = GetExprRange(S.Context, E);
11332   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11333 
11334   if (SourceRange.Width > TargetRange.Width) {
11335     // If the source is a constant, use a default-on diagnostic.
11336     // TODO: this should happen for bitfield stores, too.
11337     Expr::EvalResult Result;
11338     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11339       llvm::APSInt Value(32);
11340       Value = Result.Val.getInt();
11341 
11342       if (S.SourceMgr.isInSystemMacro(CC))
11343         return;
11344 
11345       std::string PrettySourceValue = Value.toString(10);
11346       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11347 
11348       S.DiagRuntimeBehavior(E->getExprLoc(), E,
11349         S.PDiag(diag::warn_impcast_integer_precision_constant)
11350             << PrettySourceValue << PrettyTargetValue
11351             << E->getType() << T << E->getSourceRange()
11352             << clang::SourceRange(CC));
11353       return;
11354     }
11355 
11356     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11357     if (S.SourceMgr.isInSystemMacro(CC))
11358       return;
11359 
11360     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11361       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11362                              /* pruneControlFlow */ true);
11363     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11364   }
11365 
11366   if (TargetRange.Width > SourceRange.Width) {
11367     if (auto *UO = dyn_cast<UnaryOperator>(E))
11368       if (UO->getOpcode() == UO_Minus)
11369         if (Source->isUnsignedIntegerType()) {
11370           if (Target->isUnsignedIntegerType())
11371             return DiagnoseImpCast(S, E, T, CC,
11372                                    diag::warn_impcast_high_order_zero_bits);
11373           if (Target->isSignedIntegerType())
11374             return DiagnoseImpCast(S, E, T, CC,
11375                                    diag::warn_impcast_nonnegative_result);
11376         }
11377   }
11378 
11379   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11380       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11381     // Warn when doing a signed to signed conversion, warn if the positive
11382     // source value is exactly the width of the target type, which will
11383     // cause a negative value to be stored.
11384 
11385     Expr::EvalResult Result;
11386     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11387         !S.SourceMgr.isInSystemMacro(CC)) {
11388       llvm::APSInt Value = Result.Val.getInt();
11389       if (isSameWidthConstantConversion(S, E, T, CC)) {
11390         std::string PrettySourceValue = Value.toString(10);
11391         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11392 
11393         S.DiagRuntimeBehavior(
11394             E->getExprLoc(), E,
11395             S.PDiag(diag::warn_impcast_integer_precision_constant)
11396                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11397                 << E->getSourceRange() << clang::SourceRange(CC));
11398         return;
11399       }
11400     }
11401 
11402     // Fall through for non-constants to give a sign conversion warning.
11403   }
11404 
11405   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11406       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11407        SourceRange.Width == TargetRange.Width)) {
11408     if (S.SourceMgr.isInSystemMacro(CC))
11409       return;
11410 
11411     unsigned DiagID = diag::warn_impcast_integer_sign;
11412 
11413     // Traditionally, gcc has warned about this under -Wsign-compare.
11414     // We also want to warn about it in -Wconversion.
11415     // So if -Wconversion is off, use a completely identical diagnostic
11416     // in the sign-compare group.
11417     // The conditional-checking code will
11418     if (ICContext) {
11419       DiagID = diag::warn_impcast_integer_sign_conditional;
11420       *ICContext = true;
11421     }
11422 
11423     return DiagnoseImpCast(S, E, T, CC, DiagID);
11424   }
11425 
11426   // Diagnose conversions between different enumeration types.
11427   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11428   // type, to give us better diagnostics.
11429   QualType SourceType = E->getType();
11430   if (!S.getLangOpts().CPlusPlus) {
11431     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11432       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11433         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11434         SourceType = S.Context.getTypeDeclType(Enum);
11435         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11436       }
11437   }
11438 
11439   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11440     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11441       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11442           TargetEnum->getDecl()->hasNameForLinkage() &&
11443           SourceEnum != TargetEnum) {
11444         if (S.SourceMgr.isInSystemMacro(CC))
11445           return;
11446 
11447         return DiagnoseImpCast(S, E, SourceType, T, CC,
11448                                diag::warn_impcast_different_enum_types);
11449       }
11450 }
11451 
11452 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11453                                      SourceLocation CC, QualType T);
11454 
11455 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11456                                     SourceLocation CC, bool &ICContext) {
11457   E = E->IgnoreParenImpCasts();
11458 
11459   if (isa<ConditionalOperator>(E))
11460     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11461 
11462   AnalyzeImplicitConversions(S, E, CC);
11463   if (E->getType() != T)
11464     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11465 }
11466 
11467 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11468                                      SourceLocation CC, QualType T) {
11469   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11470 
11471   bool Suspicious = false;
11472   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11473   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11474 
11475   // If -Wconversion would have warned about either of the candidates
11476   // for a signedness conversion to the context type...
11477   if (!Suspicious) return;
11478 
11479   // ...but it's currently ignored...
11480   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11481     return;
11482 
11483   // ...then check whether it would have warned about either of the
11484   // candidates for a signedness conversion to the condition type.
11485   if (E->getType() == T) return;
11486 
11487   Suspicious = false;
11488   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11489                           E->getType(), CC, &Suspicious);
11490   if (!Suspicious)
11491     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11492                             E->getType(), CC, &Suspicious);
11493 }
11494 
11495 /// Check conversion of given expression to boolean.
11496 /// Input argument E is a logical expression.
11497 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11498   if (S.getLangOpts().Bool)
11499     return;
11500   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11501     return;
11502   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11503 }
11504 
11505 /// AnalyzeImplicitConversions - Find and report any interesting
11506 /// implicit conversions in the given expression.  There are a couple
11507 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11508 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11509                                        SourceLocation CC) {
11510   QualType T = OrigE->getType();
11511   Expr *E = OrigE->IgnoreParenImpCasts();
11512 
11513   if (E->isTypeDependent() || E->isValueDependent())
11514     return;
11515 
11516   // For conditional operators, we analyze the arguments as if they
11517   // were being fed directly into the output.
11518   if (isa<ConditionalOperator>(E)) {
11519     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11520     CheckConditionalOperator(S, CO, CC, T);
11521     return;
11522   }
11523 
11524   // Check implicit argument conversions for function calls.
11525   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11526     CheckImplicitArgumentConversions(S, Call, CC);
11527 
11528   // Go ahead and check any implicit conversions we might have skipped.
11529   // The non-canonical typecheck is just an optimization;
11530   // CheckImplicitConversion will filter out dead implicit conversions.
11531   if (E->getType() != T)
11532     CheckImplicitConversion(S, E, T, CC);
11533 
11534   // Now continue drilling into this expression.
11535 
11536   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11537     // The bound subexpressions in a PseudoObjectExpr are not reachable
11538     // as transitive children.
11539     // FIXME: Use a more uniform representation for this.
11540     for (auto *SE : POE->semantics())
11541       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11542         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
11543   }
11544 
11545   // Skip past explicit casts.
11546   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11547     E = CE->getSubExpr()->IgnoreParenImpCasts();
11548     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11549       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11550     return AnalyzeImplicitConversions(S, E, CC);
11551   }
11552 
11553   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11554     // Do a somewhat different check with comparison operators.
11555     if (BO->isComparisonOp())
11556       return AnalyzeComparison(S, BO);
11557 
11558     // And with simple assignments.
11559     if (BO->getOpcode() == BO_Assign)
11560       return AnalyzeAssignment(S, BO);
11561     // And with compound assignments.
11562     if (BO->isAssignmentOp())
11563       return AnalyzeCompoundAssignment(S, BO);
11564   }
11565 
11566   // These break the otherwise-useful invariant below.  Fortunately,
11567   // we don't really need to recurse into them, because any internal
11568   // expressions should have been analyzed already when they were
11569   // built into statements.
11570   if (isa<StmtExpr>(E)) return;
11571 
11572   // Don't descend into unevaluated contexts.
11573   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11574 
11575   // Now just recurse over the expression's children.
11576   CC = E->getExprLoc();
11577   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11578   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11579   for (Stmt *SubStmt : E->children()) {
11580     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11581     if (!ChildExpr)
11582       continue;
11583 
11584     if (IsLogicalAndOperator &&
11585         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11586       // Ignore checking string literals that are in logical and operators.
11587       // This is a common pattern for asserts.
11588       continue;
11589     AnalyzeImplicitConversions(S, ChildExpr, CC);
11590   }
11591 
11592   if (BO && BO->isLogicalOp()) {
11593     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11594     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11595       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11596 
11597     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11598     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11599       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11600   }
11601 
11602   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11603     if (U->getOpcode() == UO_LNot) {
11604       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11605     } else if (U->getOpcode() != UO_AddrOf) {
11606       if (U->getSubExpr()->getType()->isAtomicType())
11607         S.Diag(U->getSubExpr()->getBeginLoc(),
11608                diag::warn_atomic_implicit_seq_cst);
11609     }
11610   }
11611 }
11612 
11613 /// Diagnose integer type and any valid implicit conversion to it.
11614 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11615   // Taking into account implicit conversions,
11616   // allow any integer.
11617   if (!E->getType()->isIntegerType()) {
11618     S.Diag(E->getBeginLoc(),
11619            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11620     return true;
11621   }
11622   // Potentially emit standard warnings for implicit conversions if enabled
11623   // using -Wconversion.
11624   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11625   return false;
11626 }
11627 
11628 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11629 // Returns true when emitting a warning about taking the address of a reference.
11630 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11631                               const PartialDiagnostic &PD) {
11632   E = E->IgnoreParenImpCasts();
11633 
11634   const FunctionDecl *FD = nullptr;
11635 
11636   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11637     if (!DRE->getDecl()->getType()->isReferenceType())
11638       return false;
11639   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11640     if (!M->getMemberDecl()->getType()->isReferenceType())
11641       return false;
11642   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11643     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11644       return false;
11645     FD = Call->getDirectCallee();
11646   } else {
11647     return false;
11648   }
11649 
11650   SemaRef.Diag(E->getExprLoc(), PD);
11651 
11652   // If possible, point to location of function.
11653   if (FD) {
11654     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11655   }
11656 
11657   return true;
11658 }
11659 
11660 // Returns true if the SourceLocation is expanded from any macro body.
11661 // Returns false if the SourceLocation is invalid, is from not in a macro
11662 // expansion, or is from expanded from a top-level macro argument.
11663 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11664   if (Loc.isInvalid())
11665     return false;
11666 
11667   while (Loc.isMacroID()) {
11668     if (SM.isMacroBodyExpansion(Loc))
11669       return true;
11670     Loc = SM.getImmediateMacroCallerLoc(Loc);
11671   }
11672 
11673   return false;
11674 }
11675 
11676 /// Diagnose pointers that are always non-null.
11677 /// \param E the expression containing the pointer
11678 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11679 /// compared to a null pointer
11680 /// \param IsEqual True when the comparison is equal to a null pointer
11681 /// \param Range Extra SourceRange to highlight in the diagnostic
11682 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11683                                         Expr::NullPointerConstantKind NullKind,
11684                                         bool IsEqual, SourceRange Range) {
11685   if (!E)
11686     return;
11687 
11688   // Don't warn inside macros.
11689   if (E->getExprLoc().isMacroID()) {
11690     const SourceManager &SM = getSourceManager();
11691     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11692         IsInAnyMacroBody(SM, Range.getBegin()))
11693       return;
11694   }
11695   E = E->IgnoreImpCasts();
11696 
11697   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11698 
11699   if (isa<CXXThisExpr>(E)) {
11700     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11701                                 : diag::warn_this_bool_conversion;
11702     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11703     return;
11704   }
11705 
11706   bool IsAddressOf = false;
11707 
11708   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11709     if (UO->getOpcode() != UO_AddrOf)
11710       return;
11711     IsAddressOf = true;
11712     E = UO->getSubExpr();
11713   }
11714 
11715   if (IsAddressOf) {
11716     unsigned DiagID = IsCompare
11717                           ? diag::warn_address_of_reference_null_compare
11718                           : diag::warn_address_of_reference_bool_conversion;
11719     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11720                                          << IsEqual;
11721     if (CheckForReference(*this, E, PD)) {
11722       return;
11723     }
11724   }
11725 
11726   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11727     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11728     std::string Str;
11729     llvm::raw_string_ostream S(Str);
11730     E->printPretty(S, nullptr, getPrintingPolicy());
11731     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11732                                 : diag::warn_cast_nonnull_to_bool;
11733     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11734       << E->getSourceRange() << Range << IsEqual;
11735     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11736   };
11737 
11738   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11739   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11740     if (auto *Callee = Call->getDirectCallee()) {
11741       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11742         ComplainAboutNonnullParamOrCall(A);
11743         return;
11744       }
11745     }
11746   }
11747 
11748   // Expect to find a single Decl.  Skip anything more complicated.
11749   ValueDecl *D = nullptr;
11750   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11751     D = R->getDecl();
11752   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11753     D = M->getMemberDecl();
11754   }
11755 
11756   // Weak Decls can be null.
11757   if (!D || D->isWeak())
11758     return;
11759 
11760   // Check for parameter decl with nonnull attribute
11761   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11762     if (getCurFunction() &&
11763         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11764       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11765         ComplainAboutNonnullParamOrCall(A);
11766         return;
11767       }
11768 
11769       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11770         // Skip function template not specialized yet.
11771         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11772           return;
11773         auto ParamIter = llvm::find(FD->parameters(), PV);
11774         assert(ParamIter != FD->param_end());
11775         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11776 
11777         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11778           if (!NonNull->args_size()) {
11779               ComplainAboutNonnullParamOrCall(NonNull);
11780               return;
11781           }
11782 
11783           for (const ParamIdx &ArgNo : NonNull->args()) {
11784             if (ArgNo.getASTIndex() == ParamNo) {
11785               ComplainAboutNonnullParamOrCall(NonNull);
11786               return;
11787             }
11788           }
11789         }
11790       }
11791     }
11792   }
11793 
11794   QualType T = D->getType();
11795   const bool IsArray = T->isArrayType();
11796   const bool IsFunction = T->isFunctionType();
11797 
11798   // Address of function is used to silence the function warning.
11799   if (IsAddressOf && IsFunction) {
11800     return;
11801   }
11802 
11803   // Found nothing.
11804   if (!IsAddressOf && !IsFunction && !IsArray)
11805     return;
11806 
11807   // Pretty print the expression for the diagnostic.
11808   std::string Str;
11809   llvm::raw_string_ostream S(Str);
11810   E->printPretty(S, nullptr, getPrintingPolicy());
11811 
11812   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11813                               : diag::warn_impcast_pointer_to_bool;
11814   enum {
11815     AddressOf,
11816     FunctionPointer,
11817     ArrayPointer
11818   } DiagType;
11819   if (IsAddressOf)
11820     DiagType = AddressOf;
11821   else if (IsFunction)
11822     DiagType = FunctionPointer;
11823   else if (IsArray)
11824     DiagType = ArrayPointer;
11825   else
11826     llvm_unreachable("Could not determine diagnostic.");
11827   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11828                                 << Range << IsEqual;
11829 
11830   if (!IsFunction)
11831     return;
11832 
11833   // Suggest '&' to silence the function warning.
11834   Diag(E->getExprLoc(), diag::note_function_warning_silence)
11835       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
11836 
11837   // Check to see if '()' fixit should be emitted.
11838   QualType ReturnType;
11839   UnresolvedSet<4> NonTemplateOverloads;
11840   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11841   if (ReturnType.isNull())
11842     return;
11843 
11844   if (IsCompare) {
11845     // There are two cases here.  If there is null constant, the only suggest
11846     // for a pointer return type.  If the null is 0, then suggest if the return
11847     // type is a pointer or an integer type.
11848     if (!ReturnType->isPointerType()) {
11849       if (NullKind == Expr::NPCK_ZeroExpression ||
11850           NullKind == Expr::NPCK_ZeroLiteral) {
11851         if (!ReturnType->isIntegerType())
11852           return;
11853       } else {
11854         return;
11855       }
11856     }
11857   } else { // !IsCompare
11858     // For function to bool, only suggest if the function pointer has bool
11859     // return type.
11860     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11861       return;
11862   }
11863   Diag(E->getExprLoc(), diag::note_function_to_function_call)
11864       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
11865 }
11866 
11867 /// Diagnoses "dangerous" implicit conversions within the given
11868 /// expression (which is a full expression).  Implements -Wconversion
11869 /// and -Wsign-compare.
11870 ///
11871 /// \param CC the "context" location of the implicit conversion, i.e.
11872 ///   the most location of the syntactic entity requiring the implicit
11873 ///   conversion
11874 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11875   // Don't diagnose in unevaluated contexts.
11876   if (isUnevaluatedContext())
11877     return;
11878 
11879   // Don't diagnose for value- or type-dependent expressions.
11880   if (E->isTypeDependent() || E->isValueDependent())
11881     return;
11882 
11883   // Check for array bounds violations in cases where the check isn't triggered
11884   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11885   // ArraySubscriptExpr is on the RHS of a variable initialization.
11886   CheckArrayAccess(E);
11887 
11888   // This is not the right CC for (e.g.) a variable initialization.
11889   AnalyzeImplicitConversions(*this, E, CC);
11890 }
11891 
11892 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11893 /// Input argument E is a logical expression.
11894 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11895   ::CheckBoolLikeConversion(*this, E, CC);
11896 }
11897 
11898 /// Diagnose when expression is an integer constant expression and its evaluation
11899 /// results in integer overflow
11900 void Sema::CheckForIntOverflow (Expr *E) {
11901   // Use a work list to deal with nested struct initializers.
11902   SmallVector<Expr *, 2> Exprs(1, E);
11903 
11904   do {
11905     Expr *OriginalE = Exprs.pop_back_val();
11906     Expr *E = OriginalE->IgnoreParenCasts();
11907 
11908     if (isa<BinaryOperator>(E)) {
11909       E->EvaluateForOverflow(Context);
11910       continue;
11911     }
11912 
11913     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
11914       Exprs.append(InitList->inits().begin(), InitList->inits().end());
11915     else if (isa<ObjCBoxedExpr>(OriginalE))
11916       E->EvaluateForOverflow(Context);
11917     else if (auto Call = dyn_cast<CallExpr>(E))
11918       Exprs.append(Call->arg_begin(), Call->arg_end());
11919     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11920       Exprs.append(Message->arg_begin(), Message->arg_end());
11921   } while (!Exprs.empty());
11922 }
11923 
11924 namespace {
11925 
11926 /// Visitor for expressions which looks for unsequenced operations on the
11927 /// same object.
11928 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
11929   using Base = EvaluatedExprVisitor<SequenceChecker>;
11930 
11931   /// A tree of sequenced regions within an expression. Two regions are
11932   /// unsequenced if one is an ancestor or a descendent of the other. When we
11933   /// finish processing an expression with sequencing, such as a comma
11934   /// expression, we fold its tree nodes into its parent, since they are
11935   /// unsequenced with respect to nodes we will visit later.
11936   class SequenceTree {
11937     struct Value {
11938       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11939       unsigned Parent : 31;
11940       unsigned Merged : 1;
11941     };
11942     SmallVector<Value, 8> Values;
11943 
11944   public:
11945     /// A region within an expression which may be sequenced with respect
11946     /// to some other region.
11947     class Seq {
11948       friend class SequenceTree;
11949 
11950       unsigned Index;
11951 
11952       explicit Seq(unsigned N) : Index(N) {}
11953 
11954     public:
11955       Seq() : Index(0) {}
11956     };
11957 
11958     SequenceTree() { Values.push_back(Value(0)); }
11959     Seq root() const { return Seq(0); }
11960 
11961     /// Create a new sequence of operations, which is an unsequenced
11962     /// subset of \p Parent. This sequence of operations is sequenced with
11963     /// respect to other children of \p Parent.
11964     Seq allocate(Seq Parent) {
11965       Values.push_back(Value(Parent.Index));
11966       return Seq(Values.size() - 1);
11967     }
11968 
11969     /// Merge a sequence of operations into its parent.
11970     void merge(Seq S) {
11971       Values[S.Index].Merged = true;
11972     }
11973 
11974     /// Determine whether two operations are unsequenced. This operation
11975     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11976     /// should have been merged into its parent as appropriate.
11977     bool isUnsequenced(Seq Cur, Seq Old) {
11978       unsigned C = representative(Cur.Index);
11979       unsigned Target = representative(Old.Index);
11980       while (C >= Target) {
11981         if (C == Target)
11982           return true;
11983         C = Values[C].Parent;
11984       }
11985       return false;
11986     }
11987 
11988   private:
11989     /// Pick a representative for a sequence.
11990     unsigned representative(unsigned K) {
11991       if (Values[K].Merged)
11992         // Perform path compression as we go.
11993         return Values[K].Parent = representative(Values[K].Parent);
11994       return K;
11995     }
11996   };
11997 
11998   /// An object for which we can track unsequenced uses.
11999   using Object = NamedDecl *;
12000 
12001   /// Different flavors of object usage which we track. We only track the
12002   /// least-sequenced usage of each kind.
12003   enum UsageKind {
12004     /// A read of an object. Multiple unsequenced reads are OK.
12005     UK_Use,
12006 
12007     /// A modification of an object which is sequenced before the value
12008     /// computation of the expression, such as ++n in C++.
12009     UK_ModAsValue,
12010 
12011     /// A modification of an object which is not sequenced before the value
12012     /// computation of the expression, such as n++.
12013     UK_ModAsSideEffect,
12014 
12015     UK_Count = UK_ModAsSideEffect + 1
12016   };
12017 
12018   struct Usage {
12019     Expr *Use;
12020     SequenceTree::Seq Seq;
12021 
12022     Usage() : Use(nullptr), Seq() {}
12023   };
12024 
12025   struct UsageInfo {
12026     Usage Uses[UK_Count];
12027 
12028     /// Have we issued a diagnostic for this variable already?
12029     bool Diagnosed;
12030 
12031     UsageInfo() : Uses(), Diagnosed(false) {}
12032   };
12033   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12034 
12035   Sema &SemaRef;
12036 
12037   /// Sequenced regions within the expression.
12038   SequenceTree Tree;
12039 
12040   /// Declaration modifications and references which we have seen.
12041   UsageInfoMap UsageMap;
12042 
12043   /// The region we are currently within.
12044   SequenceTree::Seq Region;
12045 
12046   /// Filled in with declarations which were modified as a side-effect
12047   /// (that is, post-increment operations).
12048   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12049 
12050   /// Expressions to check later. We defer checking these to reduce
12051   /// stack usage.
12052   SmallVectorImpl<Expr *> &WorkList;
12053 
12054   /// RAII object wrapping the visitation of a sequenced subexpression of an
12055   /// expression. At the end of this process, the side-effects of the evaluation
12056   /// become sequenced with respect to the value computation of the result, so
12057   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12058   /// UK_ModAsValue.
12059   struct SequencedSubexpression {
12060     SequencedSubexpression(SequenceChecker &Self)
12061       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12062       Self.ModAsSideEffect = &ModAsSideEffect;
12063     }
12064 
12065     ~SequencedSubexpression() {
12066       for (auto &M : llvm::reverse(ModAsSideEffect)) {
12067         UsageInfo &U = Self.UsageMap[M.first];
12068         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
12069         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
12070         SideEffectUsage = M.second;
12071       }
12072       Self.ModAsSideEffect = OldModAsSideEffect;
12073     }
12074 
12075     SequenceChecker &Self;
12076     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12077     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12078   };
12079 
12080   /// RAII object wrapping the visitation of a subexpression which we might
12081   /// choose to evaluate as a constant. If any subexpression is evaluated and
12082   /// found to be non-constant, this allows us to suppress the evaluation of
12083   /// the outer expression.
12084   class EvaluationTracker {
12085   public:
12086     EvaluationTracker(SequenceChecker &Self)
12087         : Self(Self), Prev(Self.EvalTracker) {
12088       Self.EvalTracker = this;
12089     }
12090 
12091     ~EvaluationTracker() {
12092       Self.EvalTracker = Prev;
12093       if (Prev)
12094         Prev->EvalOK &= EvalOK;
12095     }
12096 
12097     bool evaluate(const Expr *E, bool &Result) {
12098       if (!EvalOK || E->isValueDependent())
12099         return false;
12100       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
12101       return EvalOK;
12102     }
12103 
12104   private:
12105     SequenceChecker &Self;
12106     EvaluationTracker *Prev;
12107     bool EvalOK = true;
12108   } *EvalTracker = nullptr;
12109 
12110   /// Find the object which is produced by the specified expression,
12111   /// if any.
12112   Object getObject(Expr *E, bool Mod) const {
12113     E = E->IgnoreParenCasts();
12114     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12115       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12116         return getObject(UO->getSubExpr(), Mod);
12117     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12118       if (BO->getOpcode() == BO_Comma)
12119         return getObject(BO->getRHS(), Mod);
12120       if (Mod && BO->isAssignmentOp())
12121         return getObject(BO->getLHS(), Mod);
12122     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12123       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12124       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12125         return ME->getMemberDecl();
12126     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12127       // FIXME: If this is a reference, map through to its value.
12128       return DRE->getDecl();
12129     return nullptr;
12130   }
12131 
12132   /// Note that an object was modified or used by an expression.
12133   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
12134     Usage &U = UI.Uses[UK];
12135     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
12136       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12137         ModAsSideEffect->push_back(std::make_pair(O, U));
12138       U.Use = Ref;
12139       U.Seq = Region;
12140     }
12141   }
12142 
12143   /// Check whether a modification or use conflicts with a prior usage.
12144   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
12145                   bool IsModMod) {
12146     if (UI.Diagnosed)
12147       return;
12148 
12149     const Usage &U = UI.Uses[OtherKind];
12150     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
12151       return;
12152 
12153     Expr *Mod = U.Use;
12154     Expr *ModOrUse = Ref;
12155     if (OtherKind == UK_Use)
12156       std::swap(Mod, ModOrUse);
12157 
12158     SemaRef.DiagRuntimeBehavior(
12159         Mod->getExprLoc(), {Mod, ModOrUse},
12160         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12161                                : diag::warn_unsequenced_mod_use)
12162             << O << SourceRange(ModOrUse->getExprLoc()));
12163     UI.Diagnosed = true;
12164   }
12165 
12166   void notePreUse(Object O, Expr *Use) {
12167     UsageInfo &U = UsageMap[O];
12168     // Uses conflict with other modifications.
12169     checkUsage(O, U, Use, UK_ModAsValue, false);
12170   }
12171 
12172   void notePostUse(Object O, Expr *Use) {
12173     UsageInfo &U = UsageMap[O];
12174     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
12175     addUsage(U, O, Use, UK_Use);
12176   }
12177 
12178   void notePreMod(Object O, Expr *Mod) {
12179     UsageInfo &U = UsageMap[O];
12180     // Modifications conflict with other modifications and with uses.
12181     checkUsage(O, U, Mod, UK_ModAsValue, true);
12182     checkUsage(O, U, Mod, UK_Use, false);
12183   }
12184 
12185   void notePostMod(Object O, Expr *Use, UsageKind UK) {
12186     UsageInfo &U = UsageMap[O];
12187     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12188     addUsage(U, O, Use, UK);
12189   }
12190 
12191 public:
12192   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
12193       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12194     Visit(E);
12195   }
12196 
12197   void VisitStmt(Stmt *S) {
12198     // Skip all statements which aren't expressions for now.
12199   }
12200 
12201   void VisitExpr(Expr *E) {
12202     // By default, just recurse to evaluated subexpressions.
12203     Base::VisitStmt(E);
12204   }
12205 
12206   void VisitCastExpr(CastExpr *E) {
12207     Object O = Object();
12208     if (E->getCastKind() == CK_LValueToRValue)
12209       O = getObject(E->getSubExpr(), false);
12210 
12211     if (O)
12212       notePreUse(O, E);
12213     VisitExpr(E);
12214     if (O)
12215       notePostUse(O, E);
12216   }
12217 
12218   void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12219     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12220     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12221     SequenceTree::Seq OldRegion = Region;
12222 
12223     {
12224       SequencedSubexpression SeqBefore(*this);
12225       Region = BeforeRegion;
12226       Visit(SequencedBefore);
12227     }
12228 
12229     Region = AfterRegion;
12230     Visit(SequencedAfter);
12231 
12232     Region = OldRegion;
12233 
12234     Tree.merge(BeforeRegion);
12235     Tree.merge(AfterRegion);
12236   }
12237 
12238   void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12239     // C++17 [expr.sub]p1:
12240     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12241     //   expression E1 is sequenced before the expression E2.
12242     if (SemaRef.getLangOpts().CPlusPlus17)
12243       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12244     else
12245       Base::VisitStmt(ASE);
12246   }
12247 
12248   void VisitBinComma(BinaryOperator *BO) {
12249     // C++11 [expr.comma]p1:
12250     //   Every value computation and side effect associated with the left
12251     //   expression is sequenced before every value computation and side
12252     //   effect associated with the right expression.
12253     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12254   }
12255 
12256   void VisitBinAssign(BinaryOperator *BO) {
12257     // The modification is sequenced after the value computation of the LHS
12258     // and RHS, so check it before inspecting the operands and update the
12259     // map afterwards.
12260     Object O = getObject(BO->getLHS(), true);
12261     if (!O)
12262       return VisitExpr(BO);
12263 
12264     notePreMod(O, BO);
12265 
12266     // C++11 [expr.ass]p7:
12267     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12268     //   only once.
12269     //
12270     // Therefore, for a compound assignment operator, O is considered used
12271     // everywhere except within the evaluation of E1 itself.
12272     if (isa<CompoundAssignOperator>(BO))
12273       notePreUse(O, BO);
12274 
12275     Visit(BO->getLHS());
12276 
12277     if (isa<CompoundAssignOperator>(BO))
12278       notePostUse(O, BO);
12279 
12280     Visit(BO->getRHS());
12281 
12282     // C++11 [expr.ass]p1:
12283     //   the assignment is sequenced [...] before the value computation of the
12284     //   assignment expression.
12285     // C11 6.5.16/3 has no such rule.
12286     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12287                                                        : UK_ModAsSideEffect);
12288   }
12289 
12290   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12291     VisitBinAssign(CAO);
12292   }
12293 
12294   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12295   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12296   void VisitUnaryPreIncDec(UnaryOperator *UO) {
12297     Object O = getObject(UO->getSubExpr(), true);
12298     if (!O)
12299       return VisitExpr(UO);
12300 
12301     notePreMod(O, UO);
12302     Visit(UO->getSubExpr());
12303     // C++11 [expr.pre.incr]p1:
12304     //   the expression ++x is equivalent to x+=1
12305     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12306                                                        : UK_ModAsSideEffect);
12307   }
12308 
12309   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12310   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12311   void VisitUnaryPostIncDec(UnaryOperator *UO) {
12312     Object O = getObject(UO->getSubExpr(), true);
12313     if (!O)
12314       return VisitExpr(UO);
12315 
12316     notePreMod(O, UO);
12317     Visit(UO->getSubExpr());
12318     notePostMod(O, UO, UK_ModAsSideEffect);
12319   }
12320 
12321   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12322   void VisitBinLOr(BinaryOperator *BO) {
12323     // The side-effects of the LHS of an '&&' are sequenced before the
12324     // value computation of the RHS, and hence before the value computation
12325     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12326     // as if they were unconditionally sequenced.
12327     EvaluationTracker Eval(*this);
12328     {
12329       SequencedSubexpression Sequenced(*this);
12330       Visit(BO->getLHS());
12331     }
12332 
12333     bool Result;
12334     if (Eval.evaluate(BO->getLHS(), Result)) {
12335       if (!Result)
12336         Visit(BO->getRHS());
12337     } else {
12338       // Check for unsequenced operations in the RHS, treating it as an
12339       // entirely separate evaluation.
12340       //
12341       // FIXME: If there are operations in the RHS which are unsequenced
12342       // with respect to operations outside the RHS, and those operations
12343       // are unconditionally evaluated, diagnose them.
12344       WorkList.push_back(BO->getRHS());
12345     }
12346   }
12347   void VisitBinLAnd(BinaryOperator *BO) {
12348     EvaluationTracker Eval(*this);
12349     {
12350       SequencedSubexpression Sequenced(*this);
12351       Visit(BO->getLHS());
12352     }
12353 
12354     bool Result;
12355     if (Eval.evaluate(BO->getLHS(), Result)) {
12356       if (Result)
12357         Visit(BO->getRHS());
12358     } else {
12359       WorkList.push_back(BO->getRHS());
12360     }
12361   }
12362 
12363   // Only visit the condition, unless we can be sure which subexpression will
12364   // be chosen.
12365   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12366     EvaluationTracker Eval(*this);
12367     {
12368       SequencedSubexpression Sequenced(*this);
12369       Visit(CO->getCond());
12370     }
12371 
12372     bool Result;
12373     if (Eval.evaluate(CO->getCond(), Result))
12374       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12375     else {
12376       WorkList.push_back(CO->getTrueExpr());
12377       WorkList.push_back(CO->getFalseExpr());
12378     }
12379   }
12380 
12381   void VisitCallExpr(CallExpr *CE) {
12382     // C++11 [intro.execution]p15:
12383     //   When calling a function [...], every value computation and side effect
12384     //   associated with any argument expression, or with the postfix expression
12385     //   designating the called function, is sequenced before execution of every
12386     //   expression or statement in the body of the function [and thus before
12387     //   the value computation of its result].
12388     SequencedSubexpression Sequenced(*this);
12389     Base::VisitCallExpr(CE);
12390 
12391     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12392   }
12393 
12394   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12395     // This is a call, so all subexpressions are sequenced before the result.
12396     SequencedSubexpression Sequenced(*this);
12397 
12398     if (!CCE->isListInitialization())
12399       return VisitExpr(CCE);
12400 
12401     // In C++11, list initializations are sequenced.
12402     SmallVector<SequenceTree::Seq, 32> Elts;
12403     SequenceTree::Seq Parent = Region;
12404     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12405                                         E = CCE->arg_end();
12406          I != E; ++I) {
12407       Region = Tree.allocate(Parent);
12408       Elts.push_back(Region);
12409       Visit(*I);
12410     }
12411 
12412     // Forget that the initializers are sequenced.
12413     Region = Parent;
12414     for (unsigned I = 0; I < Elts.size(); ++I)
12415       Tree.merge(Elts[I]);
12416   }
12417 
12418   void VisitInitListExpr(InitListExpr *ILE) {
12419     if (!SemaRef.getLangOpts().CPlusPlus11)
12420       return VisitExpr(ILE);
12421 
12422     // In C++11, list initializations are sequenced.
12423     SmallVector<SequenceTree::Seq, 32> Elts;
12424     SequenceTree::Seq Parent = Region;
12425     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12426       Expr *E = ILE->getInit(I);
12427       if (!E) continue;
12428       Region = Tree.allocate(Parent);
12429       Elts.push_back(Region);
12430       Visit(E);
12431     }
12432 
12433     // Forget that the initializers are sequenced.
12434     Region = Parent;
12435     for (unsigned I = 0; I < Elts.size(); ++I)
12436       Tree.merge(Elts[I]);
12437   }
12438 };
12439 
12440 } // namespace
12441 
12442 void Sema::CheckUnsequencedOperations(Expr *E) {
12443   SmallVector<Expr *, 8> WorkList;
12444   WorkList.push_back(E);
12445   while (!WorkList.empty()) {
12446     Expr *Item = WorkList.pop_back_val();
12447     SequenceChecker(*this, Item, WorkList);
12448   }
12449 }
12450 
12451 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12452                               bool IsConstexpr) {
12453   CheckImplicitConversions(E, CheckLoc);
12454   if (!E->isInstantiationDependent())
12455     CheckUnsequencedOperations(E);
12456   if (!IsConstexpr && !E->isValueDependent())
12457     CheckForIntOverflow(E);
12458   DiagnoseMisalignedMembers();
12459 }
12460 
12461 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12462                                        FieldDecl *BitField,
12463                                        Expr *Init) {
12464   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12465 }
12466 
12467 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12468                                          SourceLocation Loc) {
12469   if (!PType->isVariablyModifiedType())
12470     return;
12471   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12472     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12473     return;
12474   }
12475   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12476     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12477     return;
12478   }
12479   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12480     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12481     return;
12482   }
12483 
12484   const ArrayType *AT = S.Context.getAsArrayType(PType);
12485   if (!AT)
12486     return;
12487 
12488   if (AT->getSizeModifier() != ArrayType::Star) {
12489     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12490     return;
12491   }
12492 
12493   S.Diag(Loc, diag::err_array_star_in_function_definition);
12494 }
12495 
12496 /// CheckParmsForFunctionDef - Check that the parameters of the given
12497 /// function are appropriate for the definition of a function. This
12498 /// takes care of any checks that cannot be performed on the
12499 /// declaration itself, e.g., that the types of each of the function
12500 /// parameters are complete.
12501 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12502                                     bool CheckParameterNames) {
12503   bool HasInvalidParm = false;
12504   for (ParmVarDecl *Param : Parameters) {
12505     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12506     // function declarator that is part of a function definition of
12507     // that function shall not have incomplete type.
12508     //
12509     // This is also C++ [dcl.fct]p6.
12510     if (!Param->isInvalidDecl() &&
12511         RequireCompleteType(Param->getLocation(), Param->getType(),
12512                             diag::err_typecheck_decl_incomplete_type)) {
12513       Param->setInvalidDecl();
12514       HasInvalidParm = true;
12515     }
12516 
12517     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12518     // declaration of each parameter shall include an identifier.
12519     if (CheckParameterNames &&
12520         Param->getIdentifier() == nullptr &&
12521         !Param->isImplicit() &&
12522         !getLangOpts().CPlusPlus)
12523       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12524 
12525     // C99 6.7.5.3p12:
12526     //   If the function declarator is not part of a definition of that
12527     //   function, parameters may have incomplete type and may use the [*]
12528     //   notation in their sequences of declarator specifiers to specify
12529     //   variable length array types.
12530     QualType PType = Param->getOriginalType();
12531     // FIXME: This diagnostic should point the '[*]' if source-location
12532     // information is added for it.
12533     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12534 
12535     // If the parameter is a c++ class type and it has to be destructed in the
12536     // callee function, declare the destructor so that it can be called by the
12537     // callee function. Do not perform any direct access check on the dtor here.
12538     if (!Param->isInvalidDecl()) {
12539       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12540         if (!ClassDecl->isInvalidDecl() &&
12541             !ClassDecl->hasIrrelevantDestructor() &&
12542             !ClassDecl->isDependentContext() &&
12543             ClassDecl->isParamDestroyedInCallee()) {
12544           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12545           MarkFunctionReferenced(Param->getLocation(), Destructor);
12546           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12547         }
12548       }
12549     }
12550 
12551     // Parameters with the pass_object_size attribute only need to be marked
12552     // constant at function definitions. Because we lack information about
12553     // whether we're on a declaration or definition when we're instantiating the
12554     // attribute, we need to check for constness here.
12555     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12556       if (!Param->getType().isConstQualified())
12557         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12558             << Attr->getSpelling() << 1;
12559 
12560     // Check for parameter names shadowing fields from the class.
12561     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12562       // The owning context for the parameter should be the function, but we
12563       // want to see if this function's declaration context is a record.
12564       DeclContext *DC = Param->getDeclContext();
12565       if (DC && DC->isFunctionOrMethod()) {
12566         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12567           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12568                                      RD, /*DeclIsField*/ false);
12569       }
12570     }
12571   }
12572 
12573   return HasInvalidParm;
12574 }
12575 
12576 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12577 /// or MemberExpr.
12578 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12579                               ASTContext &Context) {
12580   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12581     return Context.getDeclAlign(DRE->getDecl());
12582 
12583   if (const auto *ME = dyn_cast<MemberExpr>(E))
12584     return Context.getDeclAlign(ME->getMemberDecl());
12585 
12586   return TypeAlign;
12587 }
12588 
12589 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12590 /// pointer cast increases the alignment requirements.
12591 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12592   // This is actually a lot of work to potentially be doing on every
12593   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12594   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12595     return;
12596 
12597   // Ignore dependent types.
12598   if (T->isDependentType() || Op->getType()->isDependentType())
12599     return;
12600 
12601   // Require that the destination be a pointer type.
12602   const PointerType *DestPtr = T->getAs<PointerType>();
12603   if (!DestPtr) return;
12604 
12605   // If the destination has alignment 1, we're done.
12606   QualType DestPointee = DestPtr->getPointeeType();
12607   if (DestPointee->isIncompleteType()) return;
12608   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12609   if (DestAlign.isOne()) return;
12610 
12611   // Require that the source be a pointer type.
12612   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12613   if (!SrcPtr) return;
12614   QualType SrcPointee = SrcPtr->getPointeeType();
12615 
12616   // Whitelist casts from cv void*.  We already implicitly
12617   // whitelisted casts to cv void*, since they have alignment 1.
12618   // Also whitelist casts involving incomplete types, which implicitly
12619   // includes 'void'.
12620   if (SrcPointee->isIncompleteType()) return;
12621 
12622   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12623 
12624   if (auto *CE = dyn_cast<CastExpr>(Op)) {
12625     if (CE->getCastKind() == CK_ArrayToPointerDecay)
12626       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12627   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12628     if (UO->getOpcode() == UO_AddrOf)
12629       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12630   }
12631 
12632   if (SrcAlign >= DestAlign) return;
12633 
12634   Diag(TRange.getBegin(), diag::warn_cast_align)
12635     << Op->getType() << T
12636     << static_cast<unsigned>(SrcAlign.getQuantity())
12637     << static_cast<unsigned>(DestAlign.getQuantity())
12638     << TRange << Op->getSourceRange();
12639 }
12640 
12641 /// Check whether this array fits the idiom of a size-one tail padded
12642 /// array member of a struct.
12643 ///
12644 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
12645 /// commonly used to emulate flexible arrays in C89 code.
12646 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
12647                                     const NamedDecl *ND) {
12648   if (Size != 1 || !ND) return false;
12649 
12650   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12651   if (!FD) return false;
12652 
12653   // Don't consider sizes resulting from macro expansions or template argument
12654   // substitution to form C89 tail-padded arrays.
12655 
12656   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
12657   while (TInfo) {
12658     TypeLoc TL = TInfo->getTypeLoc();
12659     // Look through typedefs.
12660     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12661       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
12662       TInfo = TDL->getTypeSourceInfo();
12663       continue;
12664     }
12665     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12666       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
12667       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12668         return false;
12669     }
12670     break;
12671   }
12672 
12673   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
12674   if (!RD) return false;
12675   if (RD->isUnion()) return false;
12676   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12677     if (!CRD->isStandardLayout()) return false;
12678   }
12679 
12680   // See if this is the last field decl in the record.
12681   const Decl *D = FD;
12682   while ((D = D->getNextDeclInContext()))
12683     if (isa<FieldDecl>(D))
12684       return false;
12685   return true;
12686 }
12687 
12688 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12689                             const ArraySubscriptExpr *ASE,
12690                             bool AllowOnePastEnd, bool IndexNegated) {
12691   IndexExpr = IndexExpr->IgnoreParenImpCasts();
12692   if (IndexExpr->isValueDependent())
12693     return;
12694 
12695   const Type *EffectiveType =
12696       BaseExpr->getType()->getPointeeOrArrayElementType();
12697   BaseExpr = BaseExpr->IgnoreParenCasts();
12698   const ConstantArrayType *ArrayTy =
12699       Context.getAsConstantArrayType(BaseExpr->getType());
12700 
12701   if (!ArrayTy)
12702     return;
12703 
12704   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
12705   if (EffectiveType->isDependentType() || BaseType->isDependentType())
12706     return;
12707 
12708   Expr::EvalResult Result;
12709   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
12710     return;
12711 
12712   llvm::APSInt index = Result.Val.getInt();
12713   if (IndexNegated)
12714     index = -index;
12715 
12716   const NamedDecl *ND = nullptr;
12717   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12718     ND = DRE->getDecl();
12719   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12720     ND = ME->getMemberDecl();
12721 
12722   if (index.isUnsigned() || !index.isNegative()) {
12723     // It is possible that the type of the base expression after
12724     // IgnoreParenCasts is incomplete, even though the type of the base
12725     // expression before IgnoreParenCasts is complete (see PR39746 for an
12726     // example). In this case we have no information about whether the array
12727     // access exceeds the array bounds. However we can still diagnose an array
12728     // access which precedes the array bounds.
12729     if (BaseType->isIncompleteType())
12730       return;
12731 
12732     llvm::APInt size = ArrayTy->getSize();
12733     if (!size.isStrictlyPositive())
12734       return;
12735 
12736     if (BaseType != EffectiveType) {
12737       // Make sure we're comparing apples to apples when comparing index to size
12738       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12739       uint64_t array_typesize = Context.getTypeSize(BaseType);
12740       // Handle ptrarith_typesize being zero, such as when casting to void*
12741       if (!ptrarith_typesize) ptrarith_typesize = 1;
12742       if (ptrarith_typesize != array_typesize) {
12743         // There's a cast to a different size type involved
12744         uint64_t ratio = array_typesize / ptrarith_typesize;
12745         // TODO: Be smarter about handling cases where array_typesize is not a
12746         // multiple of ptrarith_typesize
12747         if (ptrarith_typesize * ratio == array_typesize)
12748           size *= llvm::APInt(size.getBitWidth(), ratio);
12749       }
12750     }
12751 
12752     if (size.getBitWidth() > index.getBitWidth())
12753       index = index.zext(size.getBitWidth());
12754     else if (size.getBitWidth() < index.getBitWidth())
12755       size = size.zext(index.getBitWidth());
12756 
12757     // For array subscripting the index must be less than size, but for pointer
12758     // arithmetic also allow the index (offset) to be equal to size since
12759     // computing the next address after the end of the array is legal and
12760     // commonly done e.g. in C++ iterators and range-based for loops.
12761     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
12762       return;
12763 
12764     // Also don't warn for arrays of size 1 which are members of some
12765     // structure. These are often used to approximate flexible arrays in C89
12766     // code.
12767     if (IsTailPaddedMemberArray(*this, size, ND))
12768       return;
12769 
12770     // Suppress the warning if the subscript expression (as identified by the
12771     // ']' location) and the index expression are both from macro expansions
12772     // within a system header.
12773     if (ASE) {
12774       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12775           ASE->getRBracketLoc());
12776       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
12777         SourceLocation IndexLoc =
12778             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
12779         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
12780           return;
12781       }
12782     }
12783 
12784     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
12785     if (ASE)
12786       DiagID = diag::warn_array_index_exceeds_bounds;
12787 
12788     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12789                         PDiag(DiagID) << index.toString(10, true)
12790                                       << size.toString(10, true)
12791                                       << (unsigned)size.getLimitedValue(~0U)
12792                                       << IndexExpr->getSourceRange());
12793   } else {
12794     unsigned DiagID = diag::warn_array_index_precedes_bounds;
12795     if (!ASE) {
12796       DiagID = diag::warn_ptr_arith_precedes_bounds;
12797       if (index.isNegative()) index = -index;
12798     }
12799 
12800     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12801                         PDiag(DiagID) << index.toString(10, true)
12802                                       << IndexExpr->getSourceRange());
12803   }
12804 
12805   if (!ND) {
12806     // Try harder to find a NamedDecl to point at in the note.
12807     while (const ArraySubscriptExpr *ASE =
12808            dyn_cast<ArraySubscriptExpr>(BaseExpr))
12809       BaseExpr = ASE->getBase()->IgnoreParenCasts();
12810     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12811       ND = DRE->getDecl();
12812     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12813       ND = ME->getMemberDecl();
12814   }
12815 
12816   if (ND)
12817     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
12818                         PDiag(diag::note_array_index_out_of_bounds)
12819                             << ND->getDeclName());
12820 }
12821 
12822 void Sema::CheckArrayAccess(const Expr *expr) {
12823   int AllowOnePastEnd = 0;
12824   while (expr) {
12825     expr = expr->IgnoreParenImpCasts();
12826     switch (expr->getStmtClass()) {
12827       case Stmt::ArraySubscriptExprClass: {
12828         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
12829         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
12830                          AllowOnePastEnd > 0);
12831         expr = ASE->getBase();
12832         break;
12833       }
12834       case Stmt::MemberExprClass: {
12835         expr = cast<MemberExpr>(expr)->getBase();
12836         break;
12837       }
12838       case Stmt::OMPArraySectionExprClass: {
12839         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12840         if (ASE->getLowerBound())
12841           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12842                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
12843         return;
12844       }
12845       case Stmt::UnaryOperatorClass: {
12846         // Only unwrap the * and & unary operators
12847         const UnaryOperator *UO = cast<UnaryOperator>(expr);
12848         expr = UO->getSubExpr();
12849         switch (UO->getOpcode()) {
12850           case UO_AddrOf:
12851             AllowOnePastEnd++;
12852             break;
12853           case UO_Deref:
12854             AllowOnePastEnd--;
12855             break;
12856           default:
12857             return;
12858         }
12859         break;
12860       }
12861       case Stmt::ConditionalOperatorClass: {
12862         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12863         if (const Expr *lhs = cond->getLHS())
12864           CheckArrayAccess(lhs);
12865         if (const Expr *rhs = cond->getRHS())
12866           CheckArrayAccess(rhs);
12867         return;
12868       }
12869       case Stmt::CXXOperatorCallExprClass: {
12870         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12871         for (const auto *Arg : OCE->arguments())
12872           CheckArrayAccess(Arg);
12873         return;
12874       }
12875       default:
12876         return;
12877     }
12878   }
12879 }
12880 
12881 //===--- CHECK: Objective-C retain cycles ----------------------------------//
12882 
12883 namespace {
12884 
12885 struct RetainCycleOwner {
12886   VarDecl *Variable = nullptr;
12887   SourceRange Range;
12888   SourceLocation Loc;
12889   bool Indirect = false;
12890 
12891   RetainCycleOwner() = default;
12892 
12893   void setLocsFrom(Expr *e) {
12894     Loc = e->getExprLoc();
12895     Range = e->getSourceRange();
12896   }
12897 };
12898 
12899 } // namespace
12900 
12901 /// Consider whether capturing the given variable can possibly lead to
12902 /// a retain cycle.
12903 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
12904   // In ARC, it's captured strongly iff the variable has __strong
12905   // lifetime.  In MRR, it's captured strongly if the variable is
12906   // __block and has an appropriate type.
12907   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12908     return false;
12909 
12910   owner.Variable = var;
12911   if (ref)
12912     owner.setLocsFrom(ref);
12913   return true;
12914 }
12915 
12916 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
12917   while (true) {
12918     e = e->IgnoreParens();
12919     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12920       switch (cast->getCastKind()) {
12921       case CK_BitCast:
12922       case CK_LValueBitCast:
12923       case CK_LValueToRValue:
12924       case CK_ARCReclaimReturnedObject:
12925         e = cast->getSubExpr();
12926         continue;
12927 
12928       default:
12929         return false;
12930       }
12931     }
12932 
12933     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12934       ObjCIvarDecl *ivar = ref->getDecl();
12935       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12936         return false;
12937 
12938       // Try to find a retain cycle in the base.
12939       if (!findRetainCycleOwner(S, ref->getBase(), owner))
12940         return false;
12941 
12942       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12943       owner.Indirect = true;
12944       return true;
12945     }
12946 
12947     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12948       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12949       if (!var) return false;
12950       return considerVariable(var, ref, owner);
12951     }
12952 
12953     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12954       if (member->isArrow()) return false;
12955 
12956       // Don't count this as an indirect ownership.
12957       e = member->getBase();
12958       continue;
12959     }
12960 
12961     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12962       // Only pay attention to pseudo-objects on property references.
12963       ObjCPropertyRefExpr *pre
12964         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12965                                               ->IgnoreParens());
12966       if (!pre) return false;
12967       if (pre->isImplicitProperty()) return false;
12968       ObjCPropertyDecl *property = pre->getExplicitProperty();
12969       if (!property->isRetaining() &&
12970           !(property->getPropertyIvarDecl() &&
12971             property->getPropertyIvarDecl()->getType()
12972               .getObjCLifetime() == Qualifiers::OCL_Strong))
12973           return false;
12974 
12975       owner.Indirect = true;
12976       if (pre->isSuperReceiver()) {
12977         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12978         if (!owner.Variable)
12979           return false;
12980         owner.Loc = pre->getLocation();
12981         owner.Range = pre->getSourceRange();
12982         return true;
12983       }
12984       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12985                               ->getSourceExpr());
12986       continue;
12987     }
12988 
12989     // Array ivars?
12990 
12991     return false;
12992   }
12993 }
12994 
12995 namespace {
12996 
12997   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
12998     ASTContext &Context;
12999     VarDecl *Variable;
13000     Expr *Capturer = nullptr;
13001     bool VarWillBeReased = false;
13002 
13003     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13004         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13005           Context(Context), Variable(variable) {}
13006 
13007     void VisitDeclRefExpr(DeclRefExpr *ref) {
13008       if (ref->getDecl() == Variable && !Capturer)
13009         Capturer = ref;
13010     }
13011 
13012     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13013       if (Capturer) return;
13014       Visit(ref->getBase());
13015       if (Capturer && ref->isFreeIvar())
13016         Capturer = ref;
13017     }
13018 
13019     void VisitBlockExpr(BlockExpr *block) {
13020       // Look inside nested blocks
13021       if (block->getBlockDecl()->capturesVariable(Variable))
13022         Visit(block->getBlockDecl()->getBody());
13023     }
13024 
13025     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13026       if (Capturer) return;
13027       if (OVE->getSourceExpr())
13028         Visit(OVE->getSourceExpr());
13029     }
13030 
13031     void VisitBinaryOperator(BinaryOperator *BinOp) {
13032       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13033         return;
13034       Expr *LHS = BinOp->getLHS();
13035       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13036         if (DRE->getDecl() != Variable)
13037           return;
13038         if (Expr *RHS = BinOp->getRHS()) {
13039           RHS = RHS->IgnoreParenCasts();
13040           llvm::APSInt Value;
13041           VarWillBeReased =
13042             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13043         }
13044       }
13045     }
13046   };
13047 
13048 } // namespace
13049 
13050 /// Check whether the given argument is a block which captures a
13051 /// variable.
13052 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13053   assert(owner.Variable && owner.Loc.isValid());
13054 
13055   e = e->IgnoreParenCasts();
13056 
13057   // Look through [^{...} copy] and Block_copy(^{...}).
13058   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13059     Selector Cmd = ME->getSelector();
13060     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13061       e = ME->getInstanceReceiver();
13062       if (!e)
13063         return nullptr;
13064       e = e->IgnoreParenCasts();
13065     }
13066   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13067     if (CE->getNumArgs() == 1) {
13068       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13069       if (Fn) {
13070         const IdentifierInfo *FnI = Fn->getIdentifier();
13071         if (FnI && FnI->isStr("_Block_copy")) {
13072           e = CE->getArg(0)->IgnoreParenCasts();
13073         }
13074       }
13075     }
13076   }
13077 
13078   BlockExpr *block = dyn_cast<BlockExpr>(e);
13079   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13080     return nullptr;
13081 
13082   FindCaptureVisitor visitor(S.Context, owner.Variable);
13083   visitor.Visit(block->getBlockDecl()->getBody());
13084   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13085 }
13086 
13087 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13088                                 RetainCycleOwner &owner) {
13089   assert(capturer);
13090   assert(owner.Variable && owner.Loc.isValid());
13091 
13092   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13093     << owner.Variable << capturer->getSourceRange();
13094   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13095     << owner.Indirect << owner.Range;
13096 }
13097 
13098 /// Check for a keyword selector that starts with the word 'add' or
13099 /// 'set'.
13100 static bool isSetterLikeSelector(Selector sel) {
13101   if (sel.isUnarySelector()) return false;
13102 
13103   StringRef str = sel.getNameForSlot(0);
13104   while (!str.empty() && str.front() == '_') str = str.substr(1);
13105   if (str.startswith("set"))
13106     str = str.substr(3);
13107   else if (str.startswith("add")) {
13108     // Specially whitelist 'addOperationWithBlock:'.
13109     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13110       return false;
13111     str = str.substr(3);
13112   }
13113   else
13114     return false;
13115 
13116   if (str.empty()) return true;
13117   return !isLowercase(str.front());
13118 }
13119 
13120 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13121                                                     ObjCMessageExpr *Message) {
13122   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13123                                                 Message->getReceiverInterface(),
13124                                                 NSAPI::ClassId_NSMutableArray);
13125   if (!IsMutableArray) {
13126     return None;
13127   }
13128 
13129   Selector Sel = Message->getSelector();
13130 
13131   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13132     S.NSAPIObj->getNSArrayMethodKind(Sel);
13133   if (!MKOpt) {
13134     return None;
13135   }
13136 
13137   NSAPI::NSArrayMethodKind MK = *MKOpt;
13138 
13139   switch (MK) {
13140     case NSAPI::NSMutableArr_addObject:
13141     case NSAPI::NSMutableArr_insertObjectAtIndex:
13142     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13143       return 0;
13144     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13145       return 1;
13146 
13147     default:
13148       return None;
13149   }
13150 
13151   return None;
13152 }
13153 
13154 static
13155 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13156                                                   ObjCMessageExpr *Message) {
13157   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13158                                             Message->getReceiverInterface(),
13159                                             NSAPI::ClassId_NSMutableDictionary);
13160   if (!IsMutableDictionary) {
13161     return None;
13162   }
13163 
13164   Selector Sel = Message->getSelector();
13165 
13166   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13167     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13168   if (!MKOpt) {
13169     return None;
13170   }
13171 
13172   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13173 
13174   switch (MK) {
13175     case NSAPI::NSMutableDict_setObjectForKey:
13176     case NSAPI::NSMutableDict_setValueForKey:
13177     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13178       return 0;
13179 
13180     default:
13181       return None;
13182   }
13183 
13184   return None;
13185 }
13186 
13187 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13188   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13189                                                 Message->getReceiverInterface(),
13190                                                 NSAPI::ClassId_NSMutableSet);
13191 
13192   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13193                                             Message->getReceiverInterface(),
13194                                             NSAPI::ClassId_NSMutableOrderedSet);
13195   if (!IsMutableSet && !IsMutableOrderedSet) {
13196     return None;
13197   }
13198 
13199   Selector Sel = Message->getSelector();
13200 
13201   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13202   if (!MKOpt) {
13203     return None;
13204   }
13205 
13206   NSAPI::NSSetMethodKind MK = *MKOpt;
13207 
13208   switch (MK) {
13209     case NSAPI::NSMutableSet_addObject:
13210     case NSAPI::NSOrderedSet_setObjectAtIndex:
13211     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13212     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13213       return 0;
13214     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13215       return 1;
13216   }
13217 
13218   return None;
13219 }
13220 
13221 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13222   if (!Message->isInstanceMessage()) {
13223     return;
13224   }
13225 
13226   Optional<int> ArgOpt;
13227 
13228   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13229       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13230       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13231     return;
13232   }
13233 
13234   int ArgIndex = *ArgOpt;
13235 
13236   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13237   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13238     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13239   }
13240 
13241   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13242     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13243       if (ArgRE->isObjCSelfExpr()) {
13244         Diag(Message->getSourceRange().getBegin(),
13245              diag::warn_objc_circular_container)
13246           << ArgRE->getDecl() << StringRef("'super'");
13247       }
13248     }
13249   } else {
13250     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13251 
13252     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13253       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13254     }
13255 
13256     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13257       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13258         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13259           ValueDecl *Decl = ReceiverRE->getDecl();
13260           Diag(Message->getSourceRange().getBegin(),
13261                diag::warn_objc_circular_container)
13262             << Decl << Decl;
13263           if (!ArgRE->isObjCSelfExpr()) {
13264             Diag(Decl->getLocation(),
13265                  diag::note_objc_circular_container_declared_here)
13266               << Decl;
13267           }
13268         }
13269       }
13270     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13271       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13272         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13273           ObjCIvarDecl *Decl = IvarRE->getDecl();
13274           Diag(Message->getSourceRange().getBegin(),
13275                diag::warn_objc_circular_container)
13276             << Decl << Decl;
13277           Diag(Decl->getLocation(),
13278                diag::note_objc_circular_container_declared_here)
13279             << Decl;
13280         }
13281       }
13282     }
13283   }
13284 }
13285 
13286 /// Check a message send to see if it's likely to cause a retain cycle.
13287 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13288   // Only check instance methods whose selector looks like a setter.
13289   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13290     return;
13291 
13292   // Try to find a variable that the receiver is strongly owned by.
13293   RetainCycleOwner owner;
13294   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13295     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13296       return;
13297   } else {
13298     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13299     owner.Variable = getCurMethodDecl()->getSelfDecl();
13300     owner.Loc = msg->getSuperLoc();
13301     owner.Range = msg->getSuperLoc();
13302   }
13303 
13304   // Check whether the receiver is captured by any of the arguments.
13305   const ObjCMethodDecl *MD = msg->getMethodDecl();
13306   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13307     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13308       // noescape blocks should not be retained by the method.
13309       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13310         continue;
13311       return diagnoseRetainCycle(*this, capturer, owner);
13312     }
13313   }
13314 }
13315 
13316 /// Check a property assign to see if it's likely to cause a retain cycle.
13317 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13318   RetainCycleOwner owner;
13319   if (!findRetainCycleOwner(*this, receiver, owner))
13320     return;
13321 
13322   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13323     diagnoseRetainCycle(*this, capturer, owner);
13324 }
13325 
13326 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13327   RetainCycleOwner Owner;
13328   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13329     return;
13330 
13331   // Because we don't have an expression for the variable, we have to set the
13332   // location explicitly here.
13333   Owner.Loc = Var->getLocation();
13334   Owner.Range = Var->getSourceRange();
13335 
13336   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13337     diagnoseRetainCycle(*this, Capturer, Owner);
13338 }
13339 
13340 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13341                                      Expr *RHS, bool isProperty) {
13342   // Check if RHS is an Objective-C object literal, which also can get
13343   // immediately zapped in a weak reference.  Note that we explicitly
13344   // allow ObjCStringLiterals, since those are designed to never really die.
13345   RHS = RHS->IgnoreParenImpCasts();
13346 
13347   // This enum needs to match with the 'select' in
13348   // warn_objc_arc_literal_assign (off-by-1).
13349   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13350   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13351     return false;
13352 
13353   S.Diag(Loc, diag::warn_arc_literal_assign)
13354     << (unsigned) Kind
13355     << (isProperty ? 0 : 1)
13356     << RHS->getSourceRange();
13357 
13358   return true;
13359 }
13360 
13361 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13362                                     Qualifiers::ObjCLifetime LT,
13363                                     Expr *RHS, bool isProperty) {
13364   // Strip off any implicit cast added to get to the one ARC-specific.
13365   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13366     if (cast->getCastKind() == CK_ARCConsumeObject) {
13367       S.Diag(Loc, diag::warn_arc_retained_assign)
13368         << (LT == Qualifiers::OCL_ExplicitNone)
13369         << (isProperty ? 0 : 1)
13370         << RHS->getSourceRange();
13371       return true;
13372     }
13373     RHS = cast->getSubExpr();
13374   }
13375 
13376   if (LT == Qualifiers::OCL_Weak &&
13377       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13378     return true;
13379 
13380   return false;
13381 }
13382 
13383 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13384                               QualType LHS, Expr *RHS) {
13385   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13386 
13387   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13388     return false;
13389 
13390   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13391     return true;
13392 
13393   return false;
13394 }
13395 
13396 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13397                               Expr *LHS, Expr *RHS) {
13398   QualType LHSType;
13399   // PropertyRef on LHS type need be directly obtained from
13400   // its declaration as it has a PseudoType.
13401   ObjCPropertyRefExpr *PRE
13402     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13403   if (PRE && !PRE->isImplicitProperty()) {
13404     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13405     if (PD)
13406       LHSType = PD->getType();
13407   }
13408 
13409   if (LHSType.isNull())
13410     LHSType = LHS->getType();
13411 
13412   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13413 
13414   if (LT == Qualifiers::OCL_Weak) {
13415     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13416       getCurFunction()->markSafeWeakUse(LHS);
13417   }
13418 
13419   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13420     return;
13421 
13422   // FIXME. Check for other life times.
13423   if (LT != Qualifiers::OCL_None)
13424     return;
13425 
13426   if (PRE) {
13427     if (PRE->isImplicitProperty())
13428       return;
13429     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13430     if (!PD)
13431       return;
13432 
13433     unsigned Attributes = PD->getPropertyAttributes();
13434     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13435       // when 'assign' attribute was not explicitly specified
13436       // by user, ignore it and rely on property type itself
13437       // for lifetime info.
13438       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13439       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13440           LHSType->isObjCRetainableType())
13441         return;
13442 
13443       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13444         if (cast->getCastKind() == CK_ARCConsumeObject) {
13445           Diag(Loc, diag::warn_arc_retained_property_assign)
13446           << RHS->getSourceRange();
13447           return;
13448         }
13449         RHS = cast->getSubExpr();
13450       }
13451     }
13452     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13453       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13454         return;
13455     }
13456   }
13457 }
13458 
13459 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13460 
13461 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13462                                         SourceLocation StmtLoc,
13463                                         const NullStmt *Body) {
13464   // Do not warn if the body is a macro that expands to nothing, e.g:
13465   //
13466   // #define CALL(x)
13467   // if (condition)
13468   //   CALL(0);
13469   if (Body->hasLeadingEmptyMacro())
13470     return false;
13471 
13472   // Get line numbers of statement and body.
13473   bool StmtLineInvalid;
13474   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13475                                                       &StmtLineInvalid);
13476   if (StmtLineInvalid)
13477     return false;
13478 
13479   bool BodyLineInvalid;
13480   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13481                                                       &BodyLineInvalid);
13482   if (BodyLineInvalid)
13483     return false;
13484 
13485   // Warn if null statement and body are on the same line.
13486   if (StmtLine != BodyLine)
13487     return false;
13488 
13489   return true;
13490 }
13491 
13492 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13493                                  const Stmt *Body,
13494                                  unsigned DiagID) {
13495   // Since this is a syntactic check, don't emit diagnostic for template
13496   // instantiations, this just adds noise.
13497   if (CurrentInstantiationScope)
13498     return;
13499 
13500   // The body should be a null statement.
13501   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13502   if (!NBody)
13503     return;
13504 
13505   // Do the usual checks.
13506   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13507     return;
13508 
13509   Diag(NBody->getSemiLoc(), DiagID);
13510   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13511 }
13512 
13513 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13514                                  const Stmt *PossibleBody) {
13515   assert(!CurrentInstantiationScope); // Ensured by caller
13516 
13517   SourceLocation StmtLoc;
13518   const Stmt *Body;
13519   unsigned DiagID;
13520   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13521     StmtLoc = FS->getRParenLoc();
13522     Body = FS->getBody();
13523     DiagID = diag::warn_empty_for_body;
13524   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13525     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13526     Body = WS->getBody();
13527     DiagID = diag::warn_empty_while_body;
13528   } else
13529     return; // Neither `for' nor `while'.
13530 
13531   // The body should be a null statement.
13532   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13533   if (!NBody)
13534     return;
13535 
13536   // Skip expensive checks if diagnostic is disabled.
13537   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13538     return;
13539 
13540   // Do the usual checks.
13541   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13542     return;
13543 
13544   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13545   // noise level low, emit diagnostics only if for/while is followed by a
13546   // CompoundStmt, e.g.:
13547   //    for (int i = 0; i < n; i++);
13548   //    {
13549   //      a(i);
13550   //    }
13551   // or if for/while is followed by a statement with more indentation
13552   // than for/while itself:
13553   //    for (int i = 0; i < n; i++);
13554   //      a(i);
13555   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13556   if (!ProbableTypo) {
13557     bool BodyColInvalid;
13558     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13559         PossibleBody->getBeginLoc(), &BodyColInvalid);
13560     if (BodyColInvalid)
13561       return;
13562 
13563     bool StmtColInvalid;
13564     unsigned StmtCol =
13565         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13566     if (StmtColInvalid)
13567       return;
13568 
13569     if (BodyCol > StmtCol)
13570       ProbableTypo = true;
13571   }
13572 
13573   if (ProbableTypo) {
13574     Diag(NBody->getSemiLoc(), DiagID);
13575     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13576   }
13577 }
13578 
13579 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13580 
13581 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13582 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13583                              SourceLocation OpLoc) {
13584   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13585     return;
13586 
13587   if (inTemplateInstantiation())
13588     return;
13589 
13590   // Strip parens and casts away.
13591   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13592   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13593 
13594   // Check for a call expression
13595   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13596   if (!CE || CE->getNumArgs() != 1)
13597     return;
13598 
13599   // Check for a call to std::move
13600   if (!CE->isCallToStdMove())
13601     return;
13602 
13603   // Get argument from std::move
13604   RHSExpr = CE->getArg(0);
13605 
13606   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13607   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13608 
13609   // Two DeclRefExpr's, check that the decls are the same.
13610   if (LHSDeclRef && RHSDeclRef) {
13611     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13612       return;
13613     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13614         RHSDeclRef->getDecl()->getCanonicalDecl())
13615       return;
13616 
13617     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13618                                         << LHSExpr->getSourceRange()
13619                                         << RHSExpr->getSourceRange();
13620     return;
13621   }
13622 
13623   // Member variables require a different approach to check for self moves.
13624   // MemberExpr's are the same if every nested MemberExpr refers to the same
13625   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13626   // the base Expr's are CXXThisExpr's.
13627   const Expr *LHSBase = LHSExpr;
13628   const Expr *RHSBase = RHSExpr;
13629   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13630   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13631   if (!LHSME || !RHSME)
13632     return;
13633 
13634   while (LHSME && RHSME) {
13635     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13636         RHSME->getMemberDecl()->getCanonicalDecl())
13637       return;
13638 
13639     LHSBase = LHSME->getBase();
13640     RHSBase = RHSME->getBase();
13641     LHSME = dyn_cast<MemberExpr>(LHSBase);
13642     RHSME = dyn_cast<MemberExpr>(RHSBase);
13643   }
13644 
13645   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13646   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13647   if (LHSDeclRef && RHSDeclRef) {
13648     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13649       return;
13650     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13651         RHSDeclRef->getDecl()->getCanonicalDecl())
13652       return;
13653 
13654     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13655                                         << LHSExpr->getSourceRange()
13656                                         << RHSExpr->getSourceRange();
13657     return;
13658   }
13659 
13660   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13661     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13662                                         << LHSExpr->getSourceRange()
13663                                         << RHSExpr->getSourceRange();
13664 }
13665 
13666 //===--- Layout compatibility ----------------------------------------------//
13667 
13668 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
13669 
13670 /// Check if two enumeration types are layout-compatible.
13671 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
13672   // C++11 [dcl.enum] p8:
13673   // Two enumeration types are layout-compatible if they have the same
13674   // underlying type.
13675   return ED1->isComplete() && ED2->isComplete() &&
13676          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13677 }
13678 
13679 /// Check if two fields are layout-compatible.
13680 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13681                                FieldDecl *Field2) {
13682   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13683     return false;
13684 
13685   if (Field1->isBitField() != Field2->isBitField())
13686     return false;
13687 
13688   if (Field1->isBitField()) {
13689     // Make sure that the bit-fields are the same length.
13690     unsigned Bits1 = Field1->getBitWidthValue(C);
13691     unsigned Bits2 = Field2->getBitWidthValue(C);
13692 
13693     if (Bits1 != Bits2)
13694       return false;
13695   }
13696 
13697   return true;
13698 }
13699 
13700 /// Check if two standard-layout structs are layout-compatible.
13701 /// (C++11 [class.mem] p17)
13702 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13703                                      RecordDecl *RD2) {
13704   // If both records are C++ classes, check that base classes match.
13705   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13706     // If one of records is a CXXRecordDecl we are in C++ mode,
13707     // thus the other one is a CXXRecordDecl, too.
13708     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13709     // Check number of base classes.
13710     if (D1CXX->getNumBases() != D2CXX->getNumBases())
13711       return false;
13712 
13713     // Check the base classes.
13714     for (CXXRecordDecl::base_class_const_iterator
13715                Base1 = D1CXX->bases_begin(),
13716            BaseEnd1 = D1CXX->bases_end(),
13717               Base2 = D2CXX->bases_begin();
13718          Base1 != BaseEnd1;
13719          ++Base1, ++Base2) {
13720       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13721         return false;
13722     }
13723   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13724     // If only RD2 is a C++ class, it should have zero base classes.
13725     if (D2CXX->getNumBases() > 0)
13726       return false;
13727   }
13728 
13729   // Check the fields.
13730   RecordDecl::field_iterator Field2 = RD2->field_begin(),
13731                              Field2End = RD2->field_end(),
13732                              Field1 = RD1->field_begin(),
13733                              Field1End = RD1->field_end();
13734   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13735     if (!isLayoutCompatible(C, *Field1, *Field2))
13736       return false;
13737   }
13738   if (Field1 != Field1End || Field2 != Field2End)
13739     return false;
13740 
13741   return true;
13742 }
13743 
13744 /// Check if two standard-layout unions are layout-compatible.
13745 /// (C++11 [class.mem] p18)
13746 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13747                                     RecordDecl *RD2) {
13748   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
13749   for (auto *Field2 : RD2->fields())
13750     UnmatchedFields.insert(Field2);
13751 
13752   for (auto *Field1 : RD1->fields()) {
13753     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13754         I = UnmatchedFields.begin(),
13755         E = UnmatchedFields.end();
13756 
13757     for ( ; I != E; ++I) {
13758       if (isLayoutCompatible(C, Field1, *I)) {
13759         bool Result = UnmatchedFields.erase(*I);
13760         (void) Result;
13761         assert(Result);
13762         break;
13763       }
13764     }
13765     if (I == E)
13766       return false;
13767   }
13768 
13769   return UnmatchedFields.empty();
13770 }
13771 
13772 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13773                                RecordDecl *RD2) {
13774   if (RD1->isUnion() != RD2->isUnion())
13775     return false;
13776 
13777   if (RD1->isUnion())
13778     return isLayoutCompatibleUnion(C, RD1, RD2);
13779   else
13780     return isLayoutCompatibleStruct(C, RD1, RD2);
13781 }
13782 
13783 /// Check if two types are layout-compatible in C++11 sense.
13784 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
13785   if (T1.isNull() || T2.isNull())
13786     return false;
13787 
13788   // C++11 [basic.types] p11:
13789   // If two types T1 and T2 are the same type, then T1 and T2 are
13790   // layout-compatible types.
13791   if (C.hasSameType(T1, T2))
13792     return true;
13793 
13794   T1 = T1.getCanonicalType().getUnqualifiedType();
13795   T2 = T2.getCanonicalType().getUnqualifiedType();
13796 
13797   const Type::TypeClass TC1 = T1->getTypeClass();
13798   const Type::TypeClass TC2 = T2->getTypeClass();
13799 
13800   if (TC1 != TC2)
13801     return false;
13802 
13803   if (TC1 == Type::Enum) {
13804     return isLayoutCompatible(C,
13805                               cast<EnumType>(T1)->getDecl(),
13806                               cast<EnumType>(T2)->getDecl());
13807   } else if (TC1 == Type::Record) {
13808     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13809       return false;
13810 
13811     return isLayoutCompatible(C,
13812                               cast<RecordType>(T1)->getDecl(),
13813                               cast<RecordType>(T2)->getDecl());
13814   }
13815 
13816   return false;
13817 }
13818 
13819 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13820 
13821 /// Given a type tag expression find the type tag itself.
13822 ///
13823 /// \param TypeExpr Type tag expression, as it appears in user's code.
13824 ///
13825 /// \param VD Declaration of an identifier that appears in a type tag.
13826 ///
13827 /// \param MagicValue Type tag magic value.
13828 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13829                             const ValueDecl **VD, uint64_t *MagicValue) {
13830   while(true) {
13831     if (!TypeExpr)
13832       return false;
13833 
13834     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13835 
13836     switch (TypeExpr->getStmtClass()) {
13837     case Stmt::UnaryOperatorClass: {
13838       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13839       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13840         TypeExpr = UO->getSubExpr();
13841         continue;
13842       }
13843       return false;
13844     }
13845 
13846     case Stmt::DeclRefExprClass: {
13847       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13848       *VD = DRE->getDecl();
13849       return true;
13850     }
13851 
13852     case Stmt::IntegerLiteralClass: {
13853       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13854       llvm::APInt MagicValueAPInt = IL->getValue();
13855       if (MagicValueAPInt.getActiveBits() <= 64) {
13856         *MagicValue = MagicValueAPInt.getZExtValue();
13857         return true;
13858       } else
13859         return false;
13860     }
13861 
13862     case Stmt::BinaryConditionalOperatorClass:
13863     case Stmt::ConditionalOperatorClass: {
13864       const AbstractConditionalOperator *ACO =
13865           cast<AbstractConditionalOperator>(TypeExpr);
13866       bool Result;
13867       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
13868         if (Result)
13869           TypeExpr = ACO->getTrueExpr();
13870         else
13871           TypeExpr = ACO->getFalseExpr();
13872         continue;
13873       }
13874       return false;
13875     }
13876 
13877     case Stmt::BinaryOperatorClass: {
13878       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13879       if (BO->getOpcode() == BO_Comma) {
13880         TypeExpr = BO->getRHS();
13881         continue;
13882       }
13883       return false;
13884     }
13885 
13886     default:
13887       return false;
13888     }
13889   }
13890 }
13891 
13892 /// Retrieve the C type corresponding to type tag TypeExpr.
13893 ///
13894 /// \param TypeExpr Expression that specifies a type tag.
13895 ///
13896 /// \param MagicValues Registered magic values.
13897 ///
13898 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13899 ///        kind.
13900 ///
13901 /// \param TypeInfo Information about the corresponding C type.
13902 ///
13903 /// \returns true if the corresponding C type was found.
13904 static bool GetMatchingCType(
13905         const IdentifierInfo *ArgumentKind,
13906         const Expr *TypeExpr, const ASTContext &Ctx,
13907         const llvm::DenseMap<Sema::TypeTagMagicValue,
13908                              Sema::TypeTagData> *MagicValues,
13909         bool &FoundWrongKind,
13910         Sema::TypeTagData &TypeInfo) {
13911   FoundWrongKind = false;
13912 
13913   // Variable declaration that has type_tag_for_datatype attribute.
13914   const ValueDecl *VD = nullptr;
13915 
13916   uint64_t MagicValue;
13917 
13918   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
13919     return false;
13920 
13921   if (VD) {
13922     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
13923       if (I->getArgumentKind() != ArgumentKind) {
13924         FoundWrongKind = true;
13925         return false;
13926       }
13927       TypeInfo.Type = I->getMatchingCType();
13928       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13929       TypeInfo.MustBeNull = I->getMustBeNull();
13930       return true;
13931     }
13932     return false;
13933   }
13934 
13935   if (!MagicValues)
13936     return false;
13937 
13938   llvm::DenseMap<Sema::TypeTagMagicValue,
13939                  Sema::TypeTagData>::const_iterator I =
13940       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13941   if (I == MagicValues->end())
13942     return false;
13943 
13944   TypeInfo = I->second;
13945   return true;
13946 }
13947 
13948 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13949                                       uint64_t MagicValue, QualType Type,
13950                                       bool LayoutCompatible,
13951                                       bool MustBeNull) {
13952   if (!TypeTagForDatatypeMagicValues)
13953     TypeTagForDatatypeMagicValues.reset(
13954         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13955 
13956   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13957   (*TypeTagForDatatypeMagicValues)[Magic] =
13958       TypeTagData(Type, LayoutCompatible, MustBeNull);
13959 }
13960 
13961 static bool IsSameCharType(QualType T1, QualType T2) {
13962   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13963   if (!BT1)
13964     return false;
13965 
13966   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13967   if (!BT2)
13968     return false;
13969 
13970   BuiltinType::Kind T1Kind = BT1->getKind();
13971   BuiltinType::Kind T2Kind = BT2->getKind();
13972 
13973   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
13974          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
13975          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13976          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13977 }
13978 
13979 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13980                                     const ArrayRef<const Expr *> ExprArgs,
13981                                     SourceLocation CallSiteLoc) {
13982   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13983   bool IsPointerAttr = Attr->getIsPointer();
13984 
13985   // Retrieve the argument representing the 'type_tag'.
13986   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13987   if (TypeTagIdxAST >= ExprArgs.size()) {
13988     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13989         << 0 << Attr->getTypeTagIdx().getSourceIndex();
13990     return;
13991   }
13992   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
13993   bool FoundWrongKind;
13994   TypeTagData TypeInfo;
13995   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13996                         TypeTagForDatatypeMagicValues.get(),
13997                         FoundWrongKind, TypeInfo)) {
13998     if (FoundWrongKind)
13999       Diag(TypeTagExpr->getExprLoc(),
14000            diag::warn_type_tag_for_datatype_wrong_kind)
14001         << TypeTagExpr->getSourceRange();
14002     return;
14003   }
14004 
14005   // Retrieve the argument representing the 'arg_idx'.
14006   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14007   if (ArgumentIdxAST >= ExprArgs.size()) {
14008     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14009         << 1 << Attr->getArgumentIdx().getSourceIndex();
14010     return;
14011   }
14012   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14013   if (IsPointerAttr) {
14014     // Skip implicit cast of pointer to `void *' (as a function argument).
14015     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14016       if (ICE->getType()->isVoidPointerType() &&
14017           ICE->getCastKind() == CK_BitCast)
14018         ArgumentExpr = ICE->getSubExpr();
14019   }
14020   QualType ArgumentType = ArgumentExpr->getType();
14021 
14022   // Passing a `void*' pointer shouldn't trigger a warning.
14023   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14024     return;
14025 
14026   if (TypeInfo.MustBeNull) {
14027     // Type tag with matching void type requires a null pointer.
14028     if (!ArgumentExpr->isNullPointerConstant(Context,
14029                                              Expr::NPC_ValueDependentIsNotNull)) {
14030       Diag(ArgumentExpr->getExprLoc(),
14031            diag::warn_type_safety_null_pointer_required)
14032           << ArgumentKind->getName()
14033           << ArgumentExpr->getSourceRange()
14034           << TypeTagExpr->getSourceRange();
14035     }
14036     return;
14037   }
14038 
14039   QualType RequiredType = TypeInfo.Type;
14040   if (IsPointerAttr)
14041     RequiredType = Context.getPointerType(RequiredType);
14042 
14043   bool mismatch = false;
14044   if (!TypeInfo.LayoutCompatible) {
14045     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14046 
14047     // C++11 [basic.fundamental] p1:
14048     // Plain char, signed char, and unsigned char are three distinct types.
14049     //
14050     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14051     // char' depending on the current char signedness mode.
14052     if (mismatch)
14053       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14054                                            RequiredType->getPointeeType())) ||
14055           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14056         mismatch = false;
14057   } else
14058     if (IsPointerAttr)
14059       mismatch = !isLayoutCompatible(Context,
14060                                      ArgumentType->getPointeeType(),
14061                                      RequiredType->getPointeeType());
14062     else
14063       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14064 
14065   if (mismatch)
14066     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14067         << ArgumentType << ArgumentKind
14068         << TypeInfo.LayoutCompatible << RequiredType
14069         << ArgumentExpr->getSourceRange()
14070         << TypeTagExpr->getSourceRange();
14071 }
14072 
14073 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14074                                          CharUnits Alignment) {
14075   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14076 }
14077 
14078 void Sema::DiagnoseMisalignedMembers() {
14079   for (MisalignedMember &m : MisalignedMembers) {
14080     const NamedDecl *ND = m.RD;
14081     if (ND->getName().empty()) {
14082       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14083         ND = TD;
14084     }
14085     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14086         << m.MD << ND << m.E->getSourceRange();
14087   }
14088   MisalignedMembers.clear();
14089 }
14090 
14091 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14092   E = E->IgnoreParens();
14093   if (!T->isPointerType() && !T->isIntegerType())
14094     return;
14095   if (isa<UnaryOperator>(E) &&
14096       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14097     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14098     if (isa<MemberExpr>(Op)) {
14099       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14100       if (MA != MisalignedMembers.end() &&
14101           (T->isIntegerType() ||
14102            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14103                                    Context.getTypeAlignInChars(
14104                                        T->getPointeeType()) <= MA->Alignment))))
14105         MisalignedMembers.erase(MA);
14106     }
14107   }
14108 }
14109 
14110 void Sema::RefersToMemberWithReducedAlignment(
14111     Expr *E,
14112     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14113         Action) {
14114   const auto *ME = dyn_cast<MemberExpr>(E);
14115   if (!ME)
14116     return;
14117 
14118   // No need to check expressions with an __unaligned-qualified type.
14119   if (E->getType().getQualifiers().hasUnaligned())
14120     return;
14121 
14122   // For a chain of MemberExpr like "a.b.c.d" this list
14123   // will keep FieldDecl's like [d, c, b].
14124   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14125   const MemberExpr *TopME = nullptr;
14126   bool AnyIsPacked = false;
14127   do {
14128     QualType BaseType = ME->getBase()->getType();
14129     if (ME->isArrow())
14130       BaseType = BaseType->getPointeeType();
14131     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
14132     if (RD->isInvalidDecl())
14133       return;
14134 
14135     ValueDecl *MD = ME->getMemberDecl();
14136     auto *FD = dyn_cast<FieldDecl>(MD);
14137     // We do not care about non-data members.
14138     if (!FD || FD->isInvalidDecl())
14139       return;
14140 
14141     AnyIsPacked =
14142         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14143     ReverseMemberChain.push_back(FD);
14144 
14145     TopME = ME;
14146     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14147   } while (ME);
14148   assert(TopME && "We did not compute a topmost MemberExpr!");
14149 
14150   // Not the scope of this diagnostic.
14151   if (!AnyIsPacked)
14152     return;
14153 
14154   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14155   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14156   // TODO: The innermost base of the member expression may be too complicated.
14157   // For now, just disregard these cases. This is left for future
14158   // improvement.
14159   if (!DRE && !isa<CXXThisExpr>(TopBase))
14160       return;
14161 
14162   // Alignment expected by the whole expression.
14163   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14164 
14165   // No need to do anything else with this case.
14166   if (ExpectedAlignment.isOne())
14167     return;
14168 
14169   // Synthesize offset of the whole access.
14170   CharUnits Offset;
14171   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14172        I++) {
14173     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14174   }
14175 
14176   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14177   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14178       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14179 
14180   // The base expression of the innermost MemberExpr may give
14181   // stronger guarantees than the class containing the member.
14182   if (DRE && !TopME->isArrow()) {
14183     const ValueDecl *VD = DRE->getDecl();
14184     if (!VD->getType()->isReferenceType())
14185       CompleteObjectAlignment =
14186           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14187   }
14188 
14189   // Check if the synthesized offset fulfills the alignment.
14190   if (Offset % ExpectedAlignment != 0 ||
14191       // It may fulfill the offset it but the effective alignment may still be
14192       // lower than the expected expression alignment.
14193       CompleteObjectAlignment < ExpectedAlignment) {
14194     // If this happens, we want to determine a sensible culprit of this.
14195     // Intuitively, watching the chain of member expressions from right to
14196     // left, we start with the required alignment (as required by the field
14197     // type) but some packed attribute in that chain has reduced the alignment.
14198     // It may happen that another packed structure increases it again. But if
14199     // we are here such increase has not been enough. So pointing the first
14200     // FieldDecl that either is packed or else its RecordDecl is,
14201     // seems reasonable.
14202     FieldDecl *FD = nullptr;
14203     CharUnits Alignment;
14204     for (FieldDecl *FDI : ReverseMemberChain) {
14205       if (FDI->hasAttr<PackedAttr>() ||
14206           FDI->getParent()->hasAttr<PackedAttr>()) {
14207         FD = FDI;
14208         Alignment = std::min(
14209             Context.getTypeAlignInChars(FD->getType()),
14210             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14211         break;
14212       }
14213     }
14214     assert(FD && "We did not find a packed FieldDecl!");
14215     Action(E, FD->getParent(), FD, Alignment);
14216   }
14217 }
14218 
14219 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14220   using namespace std::placeholders;
14221 
14222   RefersToMemberWithReducedAlignment(
14223       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14224                      _2, _3, _4));
14225 }
14226