1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements extra semantic analysis beyond what is enforced
11 //  by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/APValue.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/ExprOpenMP.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/Analysis/Analyses/FormatString.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSwitch.h"
79 #include "llvm/ADT/Triple.h"
80 #include "llvm/Support/AtomicOrdering.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ConvertUTF.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/Locale.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <functional>
94 #include <limits>
95 #include <string>
96 #include <tuple>
97 #include <utility>
98 
99 using namespace clang;
100 using namespace sema;
101 
102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103                                                     unsigned ByteNo) const {
104   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105                                Context.getTargetInfo());
106 }
107 
108 /// Checks that a call expression's argument count is the desired number.
109 /// This is useful when doing custom type-checking.  Returns true on error.
110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111   unsigned argCount = call->getNumArgs();
112   if (argCount == desiredArgCount) return false;
113 
114   if (argCount < desiredArgCount)
115     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
116         << 0 /*function call*/ << desiredArgCount << argCount
117         << call->getSourceRange();
118 
119   // Highlight all the excess arguments.
120   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
121                     call->getArg(argCount - 1)->getLocEnd());
122 
123   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124     << 0 /*function call*/ << desiredArgCount << argCount
125     << call->getArg(1)->getSourceRange();
126 }
127 
128 /// Check that the first argument to __builtin_annotation is an integer
129 /// and the second argument is a non-wide string literal.
130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131   if (checkArgCount(S, TheCall, 2))
132     return true;
133 
134   // First argument should be an integer.
135   Expr *ValArg = TheCall->getArg(0);
136   QualType Ty = ValArg->getType();
137   if (!Ty->isIntegerType()) {
138     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
139       << ValArg->getSourceRange();
140     return true;
141   }
142 
143   // Second argument should be a constant string.
144   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146   if (!Literal || !Literal->isAscii()) {
147     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
148       << StrArg->getSourceRange();
149     return true;
150   }
151 
152   TheCall->setType(Ty);
153   return false;
154 }
155 
156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157   // We need at least one argument.
158   if (TheCall->getNumArgs() < 1) {
159     S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
160         << 0 << 1 << TheCall->getNumArgs()
161         << TheCall->getCallee()->getSourceRange();
162     return true;
163   }
164 
165   // All arguments should be wide string literals.
166   for (Expr *Arg : TheCall->arguments()) {
167     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168     if (!Literal || !Literal->isWide()) {
169       S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
170           << Arg->getSourceRange();
171       return true;
172     }
173   }
174 
175   return false;
176 }
177 
178 /// Check that the argument to __builtin_addressof is a glvalue, and set the
179 /// result type to the corresponding pointer type.
180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181   if (checkArgCount(S, TheCall, 1))
182     return true;
183 
184   ExprResult Arg(TheCall->getArg(0));
185   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
186   if (ResultType.isNull())
187     return true;
188 
189   TheCall->setArg(0, Arg.get());
190   TheCall->setType(ResultType);
191   return false;
192 }
193 
194 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
195   if (checkArgCount(S, TheCall, 3))
196     return true;
197 
198   // First two arguments should be integers.
199   for (unsigned I = 0; I < 2; ++I) {
200     ExprResult Arg = TheCall->getArg(I);
201     QualType Ty = Arg.get()->getType();
202     if (!Ty->isIntegerType()) {
203       S.Diag(Arg.get()->getLocStart(), diag::err_overflow_builtin_must_be_int)
204           << Ty << Arg.get()->getSourceRange();
205       return true;
206     }
207     InitializedEntity Entity = InitializedEntity::InitializeParameter(
208         S.getASTContext(), Ty, /*consume*/ false);
209     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
210     if (Arg.isInvalid())
211       return true;
212     TheCall->setArg(I, Arg.get());
213   }
214 
215   // Third argument should be a pointer to a non-const integer.
216   // IRGen correctly handles volatile, restrict, and address spaces, and
217   // the other qualifiers aren't possible.
218   {
219     ExprResult Arg = TheCall->getArg(2);
220     QualType Ty = Arg.get()->getType();
221     const auto *PtrTy = Ty->getAs<PointerType>();
222     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
223           !PtrTy->getPointeeType().isConstQualified())) {
224       S.Diag(Arg.get()->getLocStart(),
225              diag::err_overflow_builtin_must_be_ptr_int)
226           << Ty << Arg.get()->getSourceRange();
227       return true;
228     }
229     InitializedEntity Entity = InitializedEntity::InitializeParameter(
230         S.getASTContext(), Ty, /*consume*/ false);
231     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
232     if (Arg.isInvalid())
233       return true;
234     TheCall->setArg(2, Arg.get());
235   }
236   return false;
237 }
238 
239 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
240 		                  CallExpr *TheCall, unsigned SizeIdx,
241                                   unsigned DstSizeIdx) {
242   if (TheCall->getNumArgs() <= SizeIdx ||
243       TheCall->getNumArgs() <= DstSizeIdx)
244     return;
245 
246   const Expr *SizeArg = TheCall->getArg(SizeIdx);
247   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
248 
249   llvm::APSInt Size, DstSize;
250 
251   // find out if both sizes are known at compile time
252   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
253       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
254     return;
255 
256   if (Size.ule(DstSize))
257     return;
258 
259   // confirmed overflow so generate the diagnostic.
260   IdentifierInfo *FnName = FDecl->getIdentifier();
261   SourceLocation SL = TheCall->getLocStart();
262   SourceRange SR = TheCall->getSourceRange();
263 
264   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
265 }
266 
267 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
268   if (checkArgCount(S, BuiltinCall, 2))
269     return true;
270 
271   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
272   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
273   Expr *Call = BuiltinCall->getArg(0);
274   Expr *Chain = BuiltinCall->getArg(1);
275 
276   if (Call->getStmtClass() != Stmt::CallExprClass) {
277     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
278         << Call->getSourceRange();
279     return true;
280   }
281 
282   auto CE = cast<CallExpr>(Call);
283   if (CE->getCallee()->getType()->isBlockPointerType()) {
284     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
285         << Call->getSourceRange();
286     return true;
287   }
288 
289   const Decl *TargetDecl = CE->getCalleeDecl();
290   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
291     if (FD->getBuiltinID()) {
292       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
293           << Call->getSourceRange();
294       return true;
295     }
296 
297   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
298     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
299         << Call->getSourceRange();
300     return true;
301   }
302 
303   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
304   if (ChainResult.isInvalid())
305     return true;
306   if (!ChainResult.get()->getType()->isPointerType()) {
307     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
308         << Chain->getSourceRange();
309     return true;
310   }
311 
312   QualType ReturnTy = CE->getCallReturnType(S.Context);
313   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
314   QualType BuiltinTy = S.Context.getFunctionType(
315       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
316   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
317 
318   Builtin =
319       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
320 
321   BuiltinCall->setType(CE->getType());
322   BuiltinCall->setValueKind(CE->getValueKind());
323   BuiltinCall->setObjectKind(CE->getObjectKind());
324   BuiltinCall->setCallee(Builtin);
325   BuiltinCall->setArg(1, ChainResult.get());
326 
327   return false;
328 }
329 
330 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
331                                      Scope::ScopeFlags NeededScopeFlags,
332                                      unsigned DiagID) {
333   // Scopes aren't available during instantiation. Fortunately, builtin
334   // functions cannot be template args so they cannot be formed through template
335   // instantiation. Therefore checking once during the parse is sufficient.
336   if (SemaRef.inTemplateInstantiation())
337     return false;
338 
339   Scope *S = SemaRef.getCurScope();
340   while (S && !S->isSEHExceptScope())
341     S = S->getParent();
342   if (!S || !(S->getFlags() & NeededScopeFlags)) {
343     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
344     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
345         << DRE->getDecl()->getIdentifier();
346     return true;
347   }
348 
349   return false;
350 }
351 
352 static inline bool isBlockPointer(Expr *Arg) {
353   return Arg->getType()->isBlockPointerType();
354 }
355 
356 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
357 /// void*, which is a requirement of device side enqueue.
358 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
359   const BlockPointerType *BPT =
360       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
361   ArrayRef<QualType> Params =
362       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
363   unsigned ArgCounter = 0;
364   bool IllegalParams = false;
365   // Iterate through the block parameters until either one is found that is not
366   // a local void*, or the block is valid.
367   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
368        I != E; ++I, ++ArgCounter) {
369     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
370         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
371             LangAS::opencl_local) {
372       // Get the location of the error. If a block literal has been passed
373       // (BlockExpr) then we can point straight to the offending argument,
374       // else we just point to the variable reference.
375       SourceLocation ErrorLoc;
376       if (isa<BlockExpr>(BlockArg)) {
377         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
378         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
379       } else if (isa<DeclRefExpr>(BlockArg)) {
380         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
381       }
382       S.Diag(ErrorLoc,
383              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
384       IllegalParams = true;
385     }
386   }
387 
388   return IllegalParams;
389 }
390 
391 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
392   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
393     S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
394           << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
395     return true;
396   }
397   return false;
398 }
399 
400 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
401   if (checkArgCount(S, TheCall, 2))
402     return true;
403 
404   if (checkOpenCLSubgroupExt(S, TheCall))
405     return true;
406 
407   // First argument is an ndrange_t type.
408   Expr *NDRangeArg = TheCall->getArg(0);
409   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
410     S.Diag(NDRangeArg->getLocStart(),
411            diag::err_opencl_builtin_expected_type)
412         << TheCall->getDirectCallee() << "'ndrange_t'";
413     return true;
414   }
415 
416   Expr *BlockArg = TheCall->getArg(1);
417   if (!isBlockPointer(BlockArg)) {
418     S.Diag(BlockArg->getLocStart(),
419            diag::err_opencl_builtin_expected_type)
420         << TheCall->getDirectCallee() << "block";
421     return true;
422   }
423   return checkOpenCLBlockArgs(S, BlockArg);
424 }
425 
426 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
427 /// get_kernel_work_group_size
428 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
429 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
430   if (checkArgCount(S, TheCall, 1))
431     return true;
432 
433   Expr *BlockArg = TheCall->getArg(0);
434   if (!isBlockPointer(BlockArg)) {
435     S.Diag(BlockArg->getLocStart(),
436            diag::err_opencl_builtin_expected_type)
437         << TheCall->getDirectCallee() << "block";
438     return true;
439   }
440   return checkOpenCLBlockArgs(S, BlockArg);
441 }
442 
443 /// Diagnose integer type and any valid implicit conversion to it.
444 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
445                                       const QualType &IntType);
446 
447 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
448                                             unsigned Start, unsigned End) {
449   bool IllegalParams = false;
450   for (unsigned I = Start; I <= End; ++I)
451     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
452                                               S.Context.getSizeType());
453   return IllegalParams;
454 }
455 
456 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
457 /// 'local void*' parameter of passed block.
458 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
459                                            Expr *BlockArg,
460                                            unsigned NumNonVarArgs) {
461   const BlockPointerType *BPT =
462       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
463   unsigned NumBlockParams =
464       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
465   unsigned TotalNumArgs = TheCall->getNumArgs();
466 
467   // For each argument passed to the block, a corresponding uint needs to
468   // be passed to describe the size of the local memory.
469   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
470     S.Diag(TheCall->getLocStart(),
471            diag::err_opencl_enqueue_kernel_local_size_args);
472     return true;
473   }
474 
475   // Check that the sizes of the local memory are specified by integers.
476   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
477                                          TotalNumArgs - 1);
478 }
479 
480 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
481 /// overload formats specified in Table 6.13.17.1.
482 /// int enqueue_kernel(queue_t queue,
483 ///                    kernel_enqueue_flags_t flags,
484 ///                    const ndrange_t ndrange,
485 ///                    void (^block)(void))
486 /// int enqueue_kernel(queue_t queue,
487 ///                    kernel_enqueue_flags_t flags,
488 ///                    const ndrange_t ndrange,
489 ///                    uint num_events_in_wait_list,
490 ///                    clk_event_t *event_wait_list,
491 ///                    clk_event_t *event_ret,
492 ///                    void (^block)(void))
493 /// int enqueue_kernel(queue_t queue,
494 ///                    kernel_enqueue_flags_t flags,
495 ///                    const ndrange_t ndrange,
496 ///                    void (^block)(local void*, ...),
497 ///                    uint size0, ...)
498 /// int enqueue_kernel(queue_t queue,
499 ///                    kernel_enqueue_flags_t flags,
500 ///                    const ndrange_t ndrange,
501 ///                    uint num_events_in_wait_list,
502 ///                    clk_event_t *event_wait_list,
503 ///                    clk_event_t *event_ret,
504 ///                    void (^block)(local void*, ...),
505 ///                    uint size0, ...)
506 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
507   unsigned NumArgs = TheCall->getNumArgs();
508 
509   if (NumArgs < 4) {
510     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
511     return true;
512   }
513 
514   Expr *Arg0 = TheCall->getArg(0);
515   Expr *Arg1 = TheCall->getArg(1);
516   Expr *Arg2 = TheCall->getArg(2);
517   Expr *Arg3 = TheCall->getArg(3);
518 
519   // First argument always needs to be a queue_t type.
520   if (!Arg0->getType()->isQueueT()) {
521     S.Diag(TheCall->getArg(0)->getLocStart(),
522            diag::err_opencl_builtin_expected_type)
523         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
524     return true;
525   }
526 
527   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
528   if (!Arg1->getType()->isIntegerType()) {
529     S.Diag(TheCall->getArg(1)->getLocStart(),
530            diag::err_opencl_builtin_expected_type)
531         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
532     return true;
533   }
534 
535   // Third argument is always an ndrange_t type.
536   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
537     S.Diag(TheCall->getArg(2)->getLocStart(),
538            diag::err_opencl_builtin_expected_type)
539         << TheCall->getDirectCallee() << "'ndrange_t'";
540     return true;
541   }
542 
543   // With four arguments, there is only one form that the function could be
544   // called in: no events and no variable arguments.
545   if (NumArgs == 4) {
546     // check that the last argument is the right block type.
547     if (!isBlockPointer(Arg3)) {
548       S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
549           << TheCall->getDirectCallee() << "block";
550       return true;
551     }
552     // we have a block type, check the prototype
553     const BlockPointerType *BPT =
554         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
555     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
556       S.Diag(Arg3->getLocStart(),
557              diag::err_opencl_enqueue_kernel_blocks_no_args);
558       return true;
559     }
560     return false;
561   }
562   // we can have block + varargs.
563   if (isBlockPointer(Arg3))
564     return (checkOpenCLBlockArgs(S, Arg3) ||
565             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
566   // last two cases with either exactly 7 args or 7 args and varargs.
567   if (NumArgs >= 7) {
568     // check common block argument.
569     Expr *Arg6 = TheCall->getArg(6);
570     if (!isBlockPointer(Arg6)) {
571       S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
572           << TheCall->getDirectCallee() << "block";
573       return true;
574     }
575     if (checkOpenCLBlockArgs(S, Arg6))
576       return true;
577 
578     // Forth argument has to be any integer type.
579     if (!Arg3->getType()->isIntegerType()) {
580       S.Diag(TheCall->getArg(3)->getLocStart(),
581              diag::err_opencl_builtin_expected_type)
582           << TheCall->getDirectCallee() << "integer";
583       return true;
584     }
585     // check remaining common arguments.
586     Expr *Arg4 = TheCall->getArg(4);
587     Expr *Arg5 = TheCall->getArg(5);
588 
589     // Fifth argument is always passed as a pointer to clk_event_t.
590     if (!Arg4->isNullPointerConstant(S.Context,
591                                      Expr::NPC_ValueDependentIsNotNull) &&
592         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
593       S.Diag(TheCall->getArg(4)->getLocStart(),
594              diag::err_opencl_builtin_expected_type)
595           << TheCall->getDirectCallee()
596           << S.Context.getPointerType(S.Context.OCLClkEventTy);
597       return true;
598     }
599 
600     // Sixth argument is always passed as a pointer to clk_event_t.
601     if (!Arg5->isNullPointerConstant(S.Context,
602                                      Expr::NPC_ValueDependentIsNotNull) &&
603         !(Arg5->getType()->isPointerType() &&
604           Arg5->getType()->getPointeeType()->isClkEventT())) {
605       S.Diag(TheCall->getArg(5)->getLocStart(),
606              diag::err_opencl_builtin_expected_type)
607           << TheCall->getDirectCallee()
608           << S.Context.getPointerType(S.Context.OCLClkEventTy);
609       return true;
610     }
611 
612     if (NumArgs == 7)
613       return false;
614 
615     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
616   }
617 
618   // None of the specific case has been detected, give generic error
619   S.Diag(TheCall->getLocStart(),
620          diag::err_opencl_enqueue_kernel_incorrect_args);
621   return true;
622 }
623 
624 /// Returns OpenCL access qual.
625 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
626     return D->getAttr<OpenCLAccessAttr>();
627 }
628 
629 /// Returns true if pipe element type is different from the pointer.
630 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
631   const Expr *Arg0 = Call->getArg(0);
632   // First argument type should always be pipe.
633   if (!Arg0->getType()->isPipeType()) {
634     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
635         << Call->getDirectCallee() << Arg0->getSourceRange();
636     return true;
637   }
638   OpenCLAccessAttr *AccessQual =
639       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
640   // Validates the access qualifier is compatible with the call.
641   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
642   // read_only and write_only, and assumed to be read_only if no qualifier is
643   // specified.
644   switch (Call->getDirectCallee()->getBuiltinID()) {
645   case Builtin::BIread_pipe:
646   case Builtin::BIreserve_read_pipe:
647   case Builtin::BIcommit_read_pipe:
648   case Builtin::BIwork_group_reserve_read_pipe:
649   case Builtin::BIsub_group_reserve_read_pipe:
650   case Builtin::BIwork_group_commit_read_pipe:
651   case Builtin::BIsub_group_commit_read_pipe:
652     if (!(!AccessQual || AccessQual->isReadOnly())) {
653       S.Diag(Arg0->getLocStart(),
654              diag::err_opencl_builtin_pipe_invalid_access_modifier)
655           << "read_only" << Arg0->getSourceRange();
656       return true;
657     }
658     break;
659   case Builtin::BIwrite_pipe:
660   case Builtin::BIreserve_write_pipe:
661   case Builtin::BIcommit_write_pipe:
662   case Builtin::BIwork_group_reserve_write_pipe:
663   case Builtin::BIsub_group_reserve_write_pipe:
664   case Builtin::BIwork_group_commit_write_pipe:
665   case Builtin::BIsub_group_commit_write_pipe:
666     if (!(AccessQual && AccessQual->isWriteOnly())) {
667       S.Diag(Arg0->getLocStart(),
668              diag::err_opencl_builtin_pipe_invalid_access_modifier)
669           << "write_only" << Arg0->getSourceRange();
670       return true;
671     }
672     break;
673   default:
674     break;
675   }
676   return false;
677 }
678 
679 /// Returns true if pipe element type is different from the pointer.
680 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
681   const Expr *Arg0 = Call->getArg(0);
682   const Expr *ArgIdx = Call->getArg(Idx);
683   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
684   const QualType EltTy = PipeTy->getElementType();
685   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
686   // The Idx argument should be a pointer and the type of the pointer and
687   // the type of pipe element should also be the same.
688   if (!ArgTy ||
689       !S.Context.hasSameType(
690           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
691     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
692         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
693         << ArgIdx->getType() << ArgIdx->getSourceRange();
694     return true;
695   }
696   return false;
697 }
698 
699 // Performs semantic analysis for the read/write_pipe call.
700 // \param S Reference to the semantic analyzer.
701 // \param Call A pointer to the builtin call.
702 // \return True if a semantic error has been found, false otherwise.
703 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
704   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
705   // functions have two forms.
706   switch (Call->getNumArgs()) {
707   case 2:
708     if (checkOpenCLPipeArg(S, Call))
709       return true;
710     // The call with 2 arguments should be
711     // read/write_pipe(pipe T, T*).
712     // Check packet type T.
713     if (checkOpenCLPipePacketType(S, Call, 1))
714       return true;
715     break;
716 
717   case 4: {
718     if (checkOpenCLPipeArg(S, Call))
719       return true;
720     // The call with 4 arguments should be
721     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
722     // Check reserve_id_t.
723     if (!Call->getArg(1)->getType()->isReserveIDT()) {
724       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
725           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
726           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
727       return true;
728     }
729 
730     // Check the index.
731     const Expr *Arg2 = Call->getArg(2);
732     if (!Arg2->getType()->isIntegerType() &&
733         !Arg2->getType()->isUnsignedIntegerType()) {
734       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
735           << Call->getDirectCallee() << S.Context.UnsignedIntTy
736           << Arg2->getType() << Arg2->getSourceRange();
737       return true;
738     }
739 
740     // Check packet type T.
741     if (checkOpenCLPipePacketType(S, Call, 3))
742       return true;
743   } break;
744   default:
745     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
746         << Call->getDirectCallee() << Call->getSourceRange();
747     return true;
748   }
749 
750   return false;
751 }
752 
753 // Performs a semantic analysis on the {work_group_/sub_group_
754 //        /_}reserve_{read/write}_pipe
755 // \param S Reference to the semantic analyzer.
756 // \param Call The call to the builtin function to be analyzed.
757 // \return True if a semantic error was found, false otherwise.
758 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
759   if (checkArgCount(S, Call, 2))
760     return true;
761 
762   if (checkOpenCLPipeArg(S, Call))
763     return true;
764 
765   // Check the reserve size.
766   if (!Call->getArg(1)->getType()->isIntegerType() &&
767       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
768     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
769         << Call->getDirectCallee() << S.Context.UnsignedIntTy
770         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
771     return true;
772   }
773 
774   // Since return type of reserve_read/write_pipe built-in function is
775   // reserve_id_t, which is not defined in the builtin def file , we used int
776   // as return type and need to override the return type of these functions.
777   Call->setType(S.Context.OCLReserveIDTy);
778 
779   return false;
780 }
781 
782 // Performs a semantic analysis on {work_group_/sub_group_
783 //        /_}commit_{read/write}_pipe
784 // \param S Reference to the semantic analyzer.
785 // \param Call The call to the builtin function to be analyzed.
786 // \return True if a semantic error was found, false otherwise.
787 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
788   if (checkArgCount(S, Call, 2))
789     return true;
790 
791   if (checkOpenCLPipeArg(S, Call))
792     return true;
793 
794   // Check reserve_id_t.
795   if (!Call->getArg(1)->getType()->isReserveIDT()) {
796     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
797         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
798         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
799     return true;
800   }
801 
802   return false;
803 }
804 
805 // Performs a semantic analysis on the call to built-in Pipe
806 //        Query Functions.
807 // \param S Reference to the semantic analyzer.
808 // \param Call The call to the builtin function to be analyzed.
809 // \return True if a semantic error was found, false otherwise.
810 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
811   if (checkArgCount(S, Call, 1))
812     return true;
813 
814   if (!Call->getArg(0)->getType()->isPipeType()) {
815     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
816         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
817     return true;
818   }
819 
820   return false;
821 }
822 
823 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
824 // Performs semantic analysis for the to_global/local/private call.
825 // \param S Reference to the semantic analyzer.
826 // \param BuiltinID ID of the builtin function.
827 // \param Call A pointer to the builtin call.
828 // \return True if a semantic error has been found, false otherwise.
829 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
830                                     CallExpr *Call) {
831   if (Call->getNumArgs() != 1) {
832     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
833         << Call->getDirectCallee() << Call->getSourceRange();
834     return true;
835   }
836 
837   auto RT = Call->getArg(0)->getType();
838   if (!RT->isPointerType() || RT->getPointeeType()
839       .getAddressSpace() == LangAS::opencl_constant) {
840     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
841         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
842     return true;
843   }
844 
845   RT = RT->getPointeeType();
846   auto Qual = RT.getQualifiers();
847   switch (BuiltinID) {
848   case Builtin::BIto_global:
849     Qual.setAddressSpace(LangAS::opencl_global);
850     break;
851   case Builtin::BIto_local:
852     Qual.setAddressSpace(LangAS::opencl_local);
853     break;
854   case Builtin::BIto_private:
855     Qual.setAddressSpace(LangAS::opencl_private);
856     break;
857   default:
858     llvm_unreachable("Invalid builtin function");
859   }
860   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
861       RT.getUnqualifiedType(), Qual)));
862 
863   return false;
864 }
865 
866 // Emit an error and return true if the current architecture is not in the list
867 // of supported architectures.
868 static bool
869 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
870                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
871   llvm::Triple::ArchType CurArch =
872       S.getASTContext().getTargetInfo().getTriple().getArch();
873   if (llvm::is_contained(SupportedArchs, CurArch))
874     return false;
875   S.Diag(TheCall->getLocStart(), diag::err_builtin_target_unsupported)
876       << TheCall->getSourceRange();
877   return true;
878 }
879 
880 ExprResult
881 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
882                                CallExpr *TheCall) {
883   ExprResult TheCallResult(TheCall);
884 
885   // Find out if any arguments are required to be integer constant expressions.
886   unsigned ICEArguments = 0;
887   ASTContext::GetBuiltinTypeError Error;
888   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
889   if (Error != ASTContext::GE_None)
890     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
891 
892   // If any arguments are required to be ICE's, check and diagnose.
893   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
894     // Skip arguments not required to be ICE's.
895     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
896 
897     llvm::APSInt Result;
898     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
899       return true;
900     ICEArguments &= ~(1 << ArgNo);
901   }
902 
903   switch (BuiltinID) {
904   case Builtin::BI__builtin___CFStringMakeConstantString:
905     assert(TheCall->getNumArgs() == 1 &&
906            "Wrong # arguments to builtin CFStringMakeConstantString");
907     if (CheckObjCString(TheCall->getArg(0)))
908       return ExprError();
909     break;
910   case Builtin::BI__builtin_ms_va_start:
911   case Builtin::BI__builtin_stdarg_start:
912   case Builtin::BI__builtin_va_start:
913     if (SemaBuiltinVAStart(BuiltinID, TheCall))
914       return ExprError();
915     break;
916   case Builtin::BI__va_start: {
917     switch (Context.getTargetInfo().getTriple().getArch()) {
918     case llvm::Triple::arm:
919     case llvm::Triple::thumb:
920       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
921         return ExprError();
922       break;
923     default:
924       if (SemaBuiltinVAStart(BuiltinID, TheCall))
925         return ExprError();
926       break;
927     }
928     break;
929   }
930 
931   // The acquire, release, and no fence variants are ARM and AArch64 only.
932   case Builtin::BI_interlockedbittestandset_acq:
933   case Builtin::BI_interlockedbittestandset_rel:
934   case Builtin::BI_interlockedbittestandset_nf:
935   case Builtin::BI_interlockedbittestandreset_acq:
936   case Builtin::BI_interlockedbittestandreset_rel:
937   case Builtin::BI_interlockedbittestandreset_nf:
938     if (CheckBuiltinTargetSupport(
939             *this, BuiltinID, TheCall,
940             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
941       return ExprError();
942     break;
943 
944   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
945   case Builtin::BI_bittest64:
946   case Builtin::BI_bittestandcomplement64:
947   case Builtin::BI_bittestandreset64:
948   case Builtin::BI_bittestandset64:
949   case Builtin::BI_interlockedbittestandreset64:
950   case Builtin::BI_interlockedbittestandset64:
951     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
952                                   {llvm::Triple::x86_64, llvm::Triple::arm,
953                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
954       return ExprError();
955     break;
956 
957   case Builtin::BI__builtin_isgreater:
958   case Builtin::BI__builtin_isgreaterequal:
959   case Builtin::BI__builtin_isless:
960   case Builtin::BI__builtin_islessequal:
961   case Builtin::BI__builtin_islessgreater:
962   case Builtin::BI__builtin_isunordered:
963     if (SemaBuiltinUnorderedCompare(TheCall))
964       return ExprError();
965     break;
966   case Builtin::BI__builtin_fpclassify:
967     if (SemaBuiltinFPClassification(TheCall, 6))
968       return ExprError();
969     break;
970   case Builtin::BI__builtin_isfinite:
971   case Builtin::BI__builtin_isinf:
972   case Builtin::BI__builtin_isinf_sign:
973   case Builtin::BI__builtin_isnan:
974   case Builtin::BI__builtin_isnormal:
975   case Builtin::BI__builtin_signbit:
976   case Builtin::BI__builtin_signbitf:
977   case Builtin::BI__builtin_signbitl:
978     if (SemaBuiltinFPClassification(TheCall, 1))
979       return ExprError();
980     break;
981   case Builtin::BI__builtin_shufflevector:
982     return SemaBuiltinShuffleVector(TheCall);
983     // TheCall will be freed by the smart pointer here, but that's fine, since
984     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
985   case Builtin::BI__builtin_prefetch:
986     if (SemaBuiltinPrefetch(TheCall))
987       return ExprError();
988     break;
989   case Builtin::BI__builtin_alloca_with_align:
990     if (SemaBuiltinAllocaWithAlign(TheCall))
991       return ExprError();
992     break;
993   case Builtin::BI__assume:
994   case Builtin::BI__builtin_assume:
995     if (SemaBuiltinAssume(TheCall))
996       return ExprError();
997     break;
998   case Builtin::BI__builtin_assume_aligned:
999     if (SemaBuiltinAssumeAligned(TheCall))
1000       return ExprError();
1001     break;
1002   case Builtin::BI__builtin_object_size:
1003     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1004       return ExprError();
1005     break;
1006   case Builtin::BI__builtin_longjmp:
1007     if (SemaBuiltinLongjmp(TheCall))
1008       return ExprError();
1009     break;
1010   case Builtin::BI__builtin_setjmp:
1011     if (SemaBuiltinSetjmp(TheCall))
1012       return ExprError();
1013     break;
1014   case Builtin::BI_setjmp:
1015   case Builtin::BI_setjmpex:
1016     if (checkArgCount(*this, TheCall, 1))
1017       return true;
1018     break;
1019   case Builtin::BI__builtin_classify_type:
1020     if (checkArgCount(*this, TheCall, 1)) return true;
1021     TheCall->setType(Context.IntTy);
1022     break;
1023   case Builtin::BI__builtin_constant_p:
1024     if (checkArgCount(*this, TheCall, 1)) return true;
1025     TheCall->setType(Context.IntTy);
1026     break;
1027   case Builtin::BI__sync_fetch_and_add:
1028   case Builtin::BI__sync_fetch_and_add_1:
1029   case Builtin::BI__sync_fetch_and_add_2:
1030   case Builtin::BI__sync_fetch_and_add_4:
1031   case Builtin::BI__sync_fetch_and_add_8:
1032   case Builtin::BI__sync_fetch_and_add_16:
1033   case Builtin::BI__sync_fetch_and_sub:
1034   case Builtin::BI__sync_fetch_and_sub_1:
1035   case Builtin::BI__sync_fetch_and_sub_2:
1036   case Builtin::BI__sync_fetch_and_sub_4:
1037   case Builtin::BI__sync_fetch_and_sub_8:
1038   case Builtin::BI__sync_fetch_and_sub_16:
1039   case Builtin::BI__sync_fetch_and_or:
1040   case Builtin::BI__sync_fetch_and_or_1:
1041   case Builtin::BI__sync_fetch_and_or_2:
1042   case Builtin::BI__sync_fetch_and_or_4:
1043   case Builtin::BI__sync_fetch_and_or_8:
1044   case Builtin::BI__sync_fetch_and_or_16:
1045   case Builtin::BI__sync_fetch_and_and:
1046   case Builtin::BI__sync_fetch_and_and_1:
1047   case Builtin::BI__sync_fetch_and_and_2:
1048   case Builtin::BI__sync_fetch_and_and_4:
1049   case Builtin::BI__sync_fetch_and_and_8:
1050   case Builtin::BI__sync_fetch_and_and_16:
1051   case Builtin::BI__sync_fetch_and_xor:
1052   case Builtin::BI__sync_fetch_and_xor_1:
1053   case Builtin::BI__sync_fetch_and_xor_2:
1054   case Builtin::BI__sync_fetch_and_xor_4:
1055   case Builtin::BI__sync_fetch_and_xor_8:
1056   case Builtin::BI__sync_fetch_and_xor_16:
1057   case Builtin::BI__sync_fetch_and_nand:
1058   case Builtin::BI__sync_fetch_and_nand_1:
1059   case Builtin::BI__sync_fetch_and_nand_2:
1060   case Builtin::BI__sync_fetch_and_nand_4:
1061   case Builtin::BI__sync_fetch_and_nand_8:
1062   case Builtin::BI__sync_fetch_and_nand_16:
1063   case Builtin::BI__sync_add_and_fetch:
1064   case Builtin::BI__sync_add_and_fetch_1:
1065   case Builtin::BI__sync_add_and_fetch_2:
1066   case Builtin::BI__sync_add_and_fetch_4:
1067   case Builtin::BI__sync_add_and_fetch_8:
1068   case Builtin::BI__sync_add_and_fetch_16:
1069   case Builtin::BI__sync_sub_and_fetch:
1070   case Builtin::BI__sync_sub_and_fetch_1:
1071   case Builtin::BI__sync_sub_and_fetch_2:
1072   case Builtin::BI__sync_sub_and_fetch_4:
1073   case Builtin::BI__sync_sub_and_fetch_8:
1074   case Builtin::BI__sync_sub_and_fetch_16:
1075   case Builtin::BI__sync_and_and_fetch:
1076   case Builtin::BI__sync_and_and_fetch_1:
1077   case Builtin::BI__sync_and_and_fetch_2:
1078   case Builtin::BI__sync_and_and_fetch_4:
1079   case Builtin::BI__sync_and_and_fetch_8:
1080   case Builtin::BI__sync_and_and_fetch_16:
1081   case Builtin::BI__sync_or_and_fetch:
1082   case Builtin::BI__sync_or_and_fetch_1:
1083   case Builtin::BI__sync_or_and_fetch_2:
1084   case Builtin::BI__sync_or_and_fetch_4:
1085   case Builtin::BI__sync_or_and_fetch_8:
1086   case Builtin::BI__sync_or_and_fetch_16:
1087   case Builtin::BI__sync_xor_and_fetch:
1088   case Builtin::BI__sync_xor_and_fetch_1:
1089   case Builtin::BI__sync_xor_and_fetch_2:
1090   case Builtin::BI__sync_xor_and_fetch_4:
1091   case Builtin::BI__sync_xor_and_fetch_8:
1092   case Builtin::BI__sync_xor_and_fetch_16:
1093   case Builtin::BI__sync_nand_and_fetch:
1094   case Builtin::BI__sync_nand_and_fetch_1:
1095   case Builtin::BI__sync_nand_and_fetch_2:
1096   case Builtin::BI__sync_nand_and_fetch_4:
1097   case Builtin::BI__sync_nand_and_fetch_8:
1098   case Builtin::BI__sync_nand_and_fetch_16:
1099   case Builtin::BI__sync_val_compare_and_swap:
1100   case Builtin::BI__sync_val_compare_and_swap_1:
1101   case Builtin::BI__sync_val_compare_and_swap_2:
1102   case Builtin::BI__sync_val_compare_and_swap_4:
1103   case Builtin::BI__sync_val_compare_and_swap_8:
1104   case Builtin::BI__sync_val_compare_and_swap_16:
1105   case Builtin::BI__sync_bool_compare_and_swap:
1106   case Builtin::BI__sync_bool_compare_and_swap_1:
1107   case Builtin::BI__sync_bool_compare_and_swap_2:
1108   case Builtin::BI__sync_bool_compare_and_swap_4:
1109   case Builtin::BI__sync_bool_compare_and_swap_8:
1110   case Builtin::BI__sync_bool_compare_and_swap_16:
1111   case Builtin::BI__sync_lock_test_and_set:
1112   case Builtin::BI__sync_lock_test_and_set_1:
1113   case Builtin::BI__sync_lock_test_and_set_2:
1114   case Builtin::BI__sync_lock_test_and_set_4:
1115   case Builtin::BI__sync_lock_test_and_set_8:
1116   case Builtin::BI__sync_lock_test_and_set_16:
1117   case Builtin::BI__sync_lock_release:
1118   case Builtin::BI__sync_lock_release_1:
1119   case Builtin::BI__sync_lock_release_2:
1120   case Builtin::BI__sync_lock_release_4:
1121   case Builtin::BI__sync_lock_release_8:
1122   case Builtin::BI__sync_lock_release_16:
1123   case Builtin::BI__sync_swap:
1124   case Builtin::BI__sync_swap_1:
1125   case Builtin::BI__sync_swap_2:
1126   case Builtin::BI__sync_swap_4:
1127   case Builtin::BI__sync_swap_8:
1128   case Builtin::BI__sync_swap_16:
1129     return SemaBuiltinAtomicOverloaded(TheCallResult);
1130   case Builtin::BI__builtin_nontemporal_load:
1131   case Builtin::BI__builtin_nontemporal_store:
1132     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1133 #define BUILTIN(ID, TYPE, ATTRS)
1134 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1135   case Builtin::BI##ID: \
1136     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1137 #include "clang/Basic/Builtins.def"
1138   case Builtin::BI__annotation:
1139     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1140       return ExprError();
1141     break;
1142   case Builtin::BI__builtin_annotation:
1143     if (SemaBuiltinAnnotation(*this, TheCall))
1144       return ExprError();
1145     break;
1146   case Builtin::BI__builtin_addressof:
1147     if (SemaBuiltinAddressof(*this, TheCall))
1148       return ExprError();
1149     break;
1150   case Builtin::BI__builtin_add_overflow:
1151   case Builtin::BI__builtin_sub_overflow:
1152   case Builtin::BI__builtin_mul_overflow:
1153     if (SemaBuiltinOverflow(*this, TheCall))
1154       return ExprError();
1155     break;
1156   case Builtin::BI__builtin_operator_new:
1157   case Builtin::BI__builtin_operator_delete: {
1158     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1159     ExprResult Res =
1160         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1161     if (Res.isInvalid())
1162       CorrectDelayedTyposInExpr(TheCallResult.get());
1163     return Res;
1164   }
1165   case Builtin::BI__builtin_dump_struct: {
1166     // We first want to ensure we are called with 2 arguments
1167     if (checkArgCount(*this, TheCall, 2))
1168       return ExprError();
1169     // Ensure that the first argument is of type 'struct XX *'
1170     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1171     const QualType PtrArgType = PtrArg->getType();
1172     if (!PtrArgType->isPointerType() ||
1173         !PtrArgType->getPointeeType()->isRecordType()) {
1174       Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1175           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1176           << "structure pointer";
1177       return ExprError();
1178     }
1179 
1180     // Ensure that the second argument is of type 'FunctionType'
1181     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1182     const QualType FnPtrArgType = FnPtrArg->getType();
1183     if (!FnPtrArgType->isPointerType()) {
1184       Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1185           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1186           << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1187       return ExprError();
1188     }
1189 
1190     const auto *FuncType =
1191         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1192 
1193     if (!FuncType) {
1194       Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1195           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1196           << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1197       return ExprError();
1198     }
1199 
1200     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1201       if (!FT->getNumParams()) {
1202         Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1203             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1204             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1205         return ExprError();
1206       }
1207       QualType PT = FT->getParamType(0);
1208       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1209           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1210           !PT->getPointeeType().isConstQualified()) {
1211         Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1212             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1213             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1214         return ExprError();
1215       }
1216     }
1217 
1218     TheCall->setType(Context.IntTy);
1219     break;
1220   }
1221 
1222   // check secure string manipulation functions where overflows
1223   // are detectable at compile time
1224   case Builtin::BI__builtin___memcpy_chk:
1225   case Builtin::BI__builtin___memmove_chk:
1226   case Builtin::BI__builtin___memset_chk:
1227   case Builtin::BI__builtin___strlcat_chk:
1228   case Builtin::BI__builtin___strlcpy_chk:
1229   case Builtin::BI__builtin___strncat_chk:
1230   case Builtin::BI__builtin___strncpy_chk:
1231   case Builtin::BI__builtin___stpncpy_chk:
1232     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1233     break;
1234   case Builtin::BI__builtin___memccpy_chk:
1235     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1236     break;
1237   case Builtin::BI__builtin___snprintf_chk:
1238   case Builtin::BI__builtin___vsnprintf_chk:
1239     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1240     break;
1241   case Builtin::BI__builtin_call_with_static_chain:
1242     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1243       return ExprError();
1244     break;
1245   case Builtin::BI__exception_code:
1246   case Builtin::BI_exception_code:
1247     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1248                                  diag::err_seh___except_block))
1249       return ExprError();
1250     break;
1251   case Builtin::BI__exception_info:
1252   case Builtin::BI_exception_info:
1253     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1254                                  diag::err_seh___except_filter))
1255       return ExprError();
1256     break;
1257   case Builtin::BI__GetExceptionInfo:
1258     if (checkArgCount(*this, TheCall, 1))
1259       return ExprError();
1260 
1261     if (CheckCXXThrowOperand(
1262             TheCall->getLocStart(),
1263             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1264             TheCall))
1265       return ExprError();
1266 
1267     TheCall->setType(Context.VoidPtrTy);
1268     break;
1269   // OpenCL v2.0, s6.13.16 - Pipe functions
1270   case Builtin::BIread_pipe:
1271   case Builtin::BIwrite_pipe:
1272     // Since those two functions are declared with var args, we need a semantic
1273     // check for the argument.
1274     if (SemaBuiltinRWPipe(*this, TheCall))
1275       return ExprError();
1276     TheCall->setType(Context.IntTy);
1277     break;
1278   case Builtin::BIreserve_read_pipe:
1279   case Builtin::BIreserve_write_pipe:
1280   case Builtin::BIwork_group_reserve_read_pipe:
1281   case Builtin::BIwork_group_reserve_write_pipe:
1282     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1283       return ExprError();
1284     break;
1285   case Builtin::BIsub_group_reserve_read_pipe:
1286   case Builtin::BIsub_group_reserve_write_pipe:
1287     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1288         SemaBuiltinReserveRWPipe(*this, TheCall))
1289       return ExprError();
1290     break;
1291   case Builtin::BIcommit_read_pipe:
1292   case Builtin::BIcommit_write_pipe:
1293   case Builtin::BIwork_group_commit_read_pipe:
1294   case Builtin::BIwork_group_commit_write_pipe:
1295     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1296       return ExprError();
1297     break;
1298   case Builtin::BIsub_group_commit_read_pipe:
1299   case Builtin::BIsub_group_commit_write_pipe:
1300     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1301         SemaBuiltinCommitRWPipe(*this, TheCall))
1302       return ExprError();
1303     break;
1304   case Builtin::BIget_pipe_num_packets:
1305   case Builtin::BIget_pipe_max_packets:
1306     if (SemaBuiltinPipePackets(*this, TheCall))
1307       return ExprError();
1308     TheCall->setType(Context.UnsignedIntTy);
1309     break;
1310   case Builtin::BIto_global:
1311   case Builtin::BIto_local:
1312   case Builtin::BIto_private:
1313     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1314       return ExprError();
1315     break;
1316   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1317   case Builtin::BIenqueue_kernel:
1318     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1319       return ExprError();
1320     break;
1321   case Builtin::BIget_kernel_work_group_size:
1322   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1323     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1324       return ExprError();
1325     break;
1326   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1327   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1328     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1329       return ExprError();
1330     break;
1331   case Builtin::BI__builtin_os_log_format:
1332   case Builtin::BI__builtin_os_log_format_buffer_size:
1333     if (SemaBuiltinOSLogFormat(TheCall))
1334       return ExprError();
1335     break;
1336   }
1337 
1338   // Since the target specific builtins for each arch overlap, only check those
1339   // of the arch we are compiling for.
1340   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1341     switch (Context.getTargetInfo().getTriple().getArch()) {
1342       case llvm::Triple::arm:
1343       case llvm::Triple::armeb:
1344       case llvm::Triple::thumb:
1345       case llvm::Triple::thumbeb:
1346         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1347           return ExprError();
1348         break;
1349       case llvm::Triple::aarch64:
1350       case llvm::Triple::aarch64_be:
1351         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1352           return ExprError();
1353         break;
1354       case llvm::Triple::hexagon:
1355         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1356           return ExprError();
1357         break;
1358       case llvm::Triple::mips:
1359       case llvm::Triple::mipsel:
1360       case llvm::Triple::mips64:
1361       case llvm::Triple::mips64el:
1362         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1363           return ExprError();
1364         break;
1365       case llvm::Triple::systemz:
1366         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1367           return ExprError();
1368         break;
1369       case llvm::Triple::x86:
1370       case llvm::Triple::x86_64:
1371         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1372           return ExprError();
1373         break;
1374       case llvm::Triple::ppc:
1375       case llvm::Triple::ppc64:
1376       case llvm::Triple::ppc64le:
1377         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1378           return ExprError();
1379         break;
1380       default:
1381         break;
1382     }
1383   }
1384 
1385   return TheCallResult;
1386 }
1387 
1388 // Get the valid immediate range for the specified NEON type code.
1389 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1390   NeonTypeFlags Type(t);
1391   int IsQuad = ForceQuad ? true : Type.isQuad();
1392   switch (Type.getEltType()) {
1393   case NeonTypeFlags::Int8:
1394   case NeonTypeFlags::Poly8:
1395     return shift ? 7 : (8 << IsQuad) - 1;
1396   case NeonTypeFlags::Int16:
1397   case NeonTypeFlags::Poly16:
1398     return shift ? 15 : (4 << IsQuad) - 1;
1399   case NeonTypeFlags::Int32:
1400     return shift ? 31 : (2 << IsQuad) - 1;
1401   case NeonTypeFlags::Int64:
1402   case NeonTypeFlags::Poly64:
1403     return shift ? 63 : (1 << IsQuad) - 1;
1404   case NeonTypeFlags::Poly128:
1405     return shift ? 127 : (1 << IsQuad) - 1;
1406   case NeonTypeFlags::Float16:
1407     assert(!shift && "cannot shift float types!");
1408     return (4 << IsQuad) - 1;
1409   case NeonTypeFlags::Float32:
1410     assert(!shift && "cannot shift float types!");
1411     return (2 << IsQuad) - 1;
1412   case NeonTypeFlags::Float64:
1413     assert(!shift && "cannot shift float types!");
1414     return (1 << IsQuad) - 1;
1415   }
1416   llvm_unreachable("Invalid NeonTypeFlag!");
1417 }
1418 
1419 /// getNeonEltType - Return the QualType corresponding to the elements of
1420 /// the vector type specified by the NeonTypeFlags.  This is used to check
1421 /// the pointer arguments for Neon load/store intrinsics.
1422 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1423                                bool IsPolyUnsigned, bool IsInt64Long) {
1424   switch (Flags.getEltType()) {
1425   case NeonTypeFlags::Int8:
1426     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1427   case NeonTypeFlags::Int16:
1428     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1429   case NeonTypeFlags::Int32:
1430     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1431   case NeonTypeFlags::Int64:
1432     if (IsInt64Long)
1433       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1434     else
1435       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1436                                 : Context.LongLongTy;
1437   case NeonTypeFlags::Poly8:
1438     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1439   case NeonTypeFlags::Poly16:
1440     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1441   case NeonTypeFlags::Poly64:
1442     if (IsInt64Long)
1443       return Context.UnsignedLongTy;
1444     else
1445       return Context.UnsignedLongLongTy;
1446   case NeonTypeFlags::Poly128:
1447     break;
1448   case NeonTypeFlags::Float16:
1449     return Context.HalfTy;
1450   case NeonTypeFlags::Float32:
1451     return Context.FloatTy;
1452   case NeonTypeFlags::Float64:
1453     return Context.DoubleTy;
1454   }
1455   llvm_unreachable("Invalid NeonTypeFlag!");
1456 }
1457 
1458 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1459   llvm::APSInt Result;
1460   uint64_t mask = 0;
1461   unsigned TV = 0;
1462   int PtrArgNum = -1;
1463   bool HasConstPtr = false;
1464   switch (BuiltinID) {
1465 #define GET_NEON_OVERLOAD_CHECK
1466 #include "clang/Basic/arm_neon.inc"
1467 #include "clang/Basic/arm_fp16.inc"
1468 #undef GET_NEON_OVERLOAD_CHECK
1469   }
1470 
1471   // For NEON intrinsics which are overloaded on vector element type, validate
1472   // the immediate which specifies which variant to emit.
1473   unsigned ImmArg = TheCall->getNumArgs()-1;
1474   if (mask) {
1475     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1476       return true;
1477 
1478     TV = Result.getLimitedValue(64);
1479     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1480       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1481         << TheCall->getArg(ImmArg)->getSourceRange();
1482   }
1483 
1484   if (PtrArgNum >= 0) {
1485     // Check that pointer arguments have the specified type.
1486     Expr *Arg = TheCall->getArg(PtrArgNum);
1487     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1488       Arg = ICE->getSubExpr();
1489     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1490     QualType RHSTy = RHS.get()->getType();
1491 
1492     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1493     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1494                           Arch == llvm::Triple::aarch64_be;
1495     bool IsInt64Long =
1496         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1497     QualType EltTy =
1498         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1499     if (HasConstPtr)
1500       EltTy = EltTy.withConst();
1501     QualType LHSTy = Context.getPointerType(EltTy);
1502     AssignConvertType ConvTy;
1503     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1504     if (RHS.isInvalid())
1505       return true;
1506     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1507                                  RHS.get(), AA_Assigning))
1508       return true;
1509   }
1510 
1511   // For NEON intrinsics which take an immediate value as part of the
1512   // instruction, range check them here.
1513   unsigned i = 0, l = 0, u = 0;
1514   switch (BuiltinID) {
1515   default:
1516     return false;
1517   #define GET_NEON_IMMEDIATE_CHECK
1518   #include "clang/Basic/arm_neon.inc"
1519   #include "clang/Basic/arm_fp16.inc"
1520   #undef GET_NEON_IMMEDIATE_CHECK
1521   }
1522 
1523   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1524 }
1525 
1526 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1527                                         unsigned MaxWidth) {
1528   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1529           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1530           BuiltinID == ARM::BI__builtin_arm_strex ||
1531           BuiltinID == ARM::BI__builtin_arm_stlex ||
1532           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1533           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1534           BuiltinID == AArch64::BI__builtin_arm_strex ||
1535           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1536          "unexpected ARM builtin");
1537   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1538                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1539                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1540                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1541 
1542   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1543 
1544   // Ensure that we have the proper number of arguments.
1545   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1546     return true;
1547 
1548   // Inspect the pointer argument of the atomic builtin.  This should always be
1549   // a pointer type, whose element is an integral scalar or pointer type.
1550   // Because it is a pointer type, we don't have to worry about any implicit
1551   // casts here.
1552   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1553   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1554   if (PointerArgRes.isInvalid())
1555     return true;
1556   PointerArg = PointerArgRes.get();
1557 
1558   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1559   if (!pointerType) {
1560     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1561       << PointerArg->getType() << PointerArg->getSourceRange();
1562     return true;
1563   }
1564 
1565   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1566   // task is to insert the appropriate casts into the AST. First work out just
1567   // what the appropriate type is.
1568   QualType ValType = pointerType->getPointeeType();
1569   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1570   if (IsLdrex)
1571     AddrType.addConst();
1572 
1573   // Issue a warning if the cast is dodgy.
1574   CastKind CastNeeded = CK_NoOp;
1575   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1576     CastNeeded = CK_BitCast;
1577     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1578       << PointerArg->getType()
1579       << Context.getPointerType(AddrType)
1580       << AA_Passing << PointerArg->getSourceRange();
1581   }
1582 
1583   // Finally, do the cast and replace the argument with the corrected version.
1584   AddrType = Context.getPointerType(AddrType);
1585   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1586   if (PointerArgRes.isInvalid())
1587     return true;
1588   PointerArg = PointerArgRes.get();
1589 
1590   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1591 
1592   // In general, we allow ints, floats and pointers to be loaded and stored.
1593   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1594       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1595     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1596       << PointerArg->getType() << PointerArg->getSourceRange();
1597     return true;
1598   }
1599 
1600   // But ARM doesn't have instructions to deal with 128-bit versions.
1601   if (Context.getTypeSize(ValType) > MaxWidth) {
1602     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1603     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1604       << PointerArg->getType() << PointerArg->getSourceRange();
1605     return true;
1606   }
1607 
1608   switch (ValType.getObjCLifetime()) {
1609   case Qualifiers::OCL_None:
1610   case Qualifiers::OCL_ExplicitNone:
1611     // okay
1612     break;
1613 
1614   case Qualifiers::OCL_Weak:
1615   case Qualifiers::OCL_Strong:
1616   case Qualifiers::OCL_Autoreleasing:
1617     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1618       << ValType << PointerArg->getSourceRange();
1619     return true;
1620   }
1621 
1622   if (IsLdrex) {
1623     TheCall->setType(ValType);
1624     return false;
1625   }
1626 
1627   // Initialize the argument to be stored.
1628   ExprResult ValArg = TheCall->getArg(0);
1629   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1630       Context, ValType, /*consume*/ false);
1631   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1632   if (ValArg.isInvalid())
1633     return true;
1634   TheCall->setArg(0, ValArg.get());
1635 
1636   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1637   // but the custom checker bypasses all default analysis.
1638   TheCall->setType(Context.IntTy);
1639   return false;
1640 }
1641 
1642 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1643   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1644       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1645       BuiltinID == ARM::BI__builtin_arm_strex ||
1646       BuiltinID == ARM::BI__builtin_arm_stlex) {
1647     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1648   }
1649 
1650   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1651     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1652       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1653   }
1654 
1655   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1656       BuiltinID == ARM::BI__builtin_arm_wsr64)
1657     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1658 
1659   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1660       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1661       BuiltinID == ARM::BI__builtin_arm_wsr ||
1662       BuiltinID == ARM::BI__builtin_arm_wsrp)
1663     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1664 
1665   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1666     return true;
1667 
1668   // For intrinsics which take an immediate value as part of the instruction,
1669   // range check them here.
1670   // FIXME: VFP Intrinsics should error if VFP not present.
1671   switch (BuiltinID) {
1672   default: return false;
1673   case ARM::BI__builtin_arm_ssat:
1674     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1675   case ARM::BI__builtin_arm_usat:
1676     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1677   case ARM::BI__builtin_arm_ssat16:
1678     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1679   case ARM::BI__builtin_arm_usat16:
1680     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1681   case ARM::BI__builtin_arm_vcvtr_f:
1682   case ARM::BI__builtin_arm_vcvtr_d:
1683     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1684   case ARM::BI__builtin_arm_dmb:
1685   case ARM::BI__builtin_arm_dsb:
1686   case ARM::BI__builtin_arm_isb:
1687   case ARM::BI__builtin_arm_dbg:
1688     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1689   }
1690 }
1691 
1692 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1693                                          CallExpr *TheCall) {
1694   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1695       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1696       BuiltinID == AArch64::BI__builtin_arm_strex ||
1697       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1698     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1699   }
1700 
1701   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1702     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1703       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1704       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1705       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1706   }
1707 
1708   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1709       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1710     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1711 
1712   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1713       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1714       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1715       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1716     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1717 
1718   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1719     return true;
1720 
1721   // For intrinsics which take an immediate value as part of the instruction,
1722   // range check them here.
1723   unsigned i = 0, l = 0, u = 0;
1724   switch (BuiltinID) {
1725   default: return false;
1726   case AArch64::BI__builtin_arm_dmb:
1727   case AArch64::BI__builtin_arm_dsb:
1728   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1729   }
1730 
1731   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1732 }
1733 
1734 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
1735                                            CallExpr *TheCall) {
1736   struct ArgInfo {
1737     ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
1738       : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
1739     unsigned OpNum = 0;
1740     bool IsSigned = false;
1741     unsigned BitWidth = 0;
1742     unsigned Align = 0;
1743   };
1744 
1745   static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
1746     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
1747     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
1748     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
1749     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
1750     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
1751     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
1752     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
1753     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
1754     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
1755     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
1756     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
1757 
1758     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
1759     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
1760     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
1761     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
1762     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
1763     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
1764     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
1765     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
1766     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
1767     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
1768     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
1769 
1770     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
1771     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
1772     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
1773     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
1774     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
1775     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
1776     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
1777     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
1778     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
1779     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
1780     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
1781     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
1782     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
1783     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
1784     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
1785     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
1786     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
1787     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
1788     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
1789     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
1790     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
1791     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
1792     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
1793     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
1794     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
1795     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
1796     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
1797     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
1798     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
1799     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
1800     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
1801     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
1802     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
1803     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
1804     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
1805     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
1806     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
1807     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
1808     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
1809     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
1810     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
1811     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
1812     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
1813     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
1814     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
1815     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
1816     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
1817     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
1818     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
1819     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
1820     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
1821     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
1822                                                       {{ 1, false, 6,  0 }} },
1823     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
1824     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
1825     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
1826     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
1827     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
1828     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
1829     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
1830                                                       {{ 1, false, 5,  0 }} },
1831     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
1832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
1833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
1834     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
1835     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
1836     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
1837                                                        { 2, false, 5,  0 }} },
1838     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
1839                                                        { 2, false, 6,  0 }} },
1840     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
1841                                                        { 3, false, 5,  0 }} },
1842     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
1843                                                        { 3, false, 6,  0 }} },
1844     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
1845     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
1846     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
1847     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
1848     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
1849     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
1850     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
1851     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
1852     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
1853     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
1854     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
1855     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
1856     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
1857     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
1858     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
1859     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
1860                                                       {{ 2, false, 4,  0 },
1861                                                        { 3, false, 5,  0 }} },
1862     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
1863                                                       {{ 2, false, 4,  0 },
1864                                                        { 3, false, 5,  0 }} },
1865     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
1866                                                       {{ 2, false, 4,  0 },
1867                                                        { 3, false, 5,  0 }} },
1868     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
1869                                                       {{ 2, false, 4,  0 },
1870                                                        { 3, false, 5,  0 }} },
1871     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
1872     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
1873     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
1874     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
1875     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
1876     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
1877     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
1878     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
1879     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
1880     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
1881     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
1882                                                        { 2, false, 5,  0 }} },
1883     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
1884                                                        { 2, false, 6,  0 }} },
1885     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
1886     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
1887     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
1888     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
1889     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
1890     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
1891     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
1892     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
1893     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
1894                                                       {{ 1, false, 4,  0 }} },
1895     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
1896     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
1897                                                       {{ 1, false, 4,  0 }} },
1898     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
1899     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
1900     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
1901     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
1902     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
1903     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
1904     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
1905     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
1906     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
1907     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
1908     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
1909     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
1910     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
1911     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
1912     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
1913     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
1914     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
1915     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
1916     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
1917     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
1918                                                       {{ 3, false, 1,  0 }} },
1919     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
1920     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
1921     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
1922     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
1923                                                       {{ 3, false, 1,  0 }} },
1924     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
1925     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
1926     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
1927     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
1928                                                       {{ 3, false, 1,  0 }} },
1929   };
1930 
1931   auto F = Infos.find(BuiltinID);
1932   if (F == Infos.end())
1933     return false;
1934 
1935   bool Error = false;
1936 
1937   for (const ArgInfo &A : F->second) {
1938     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
1939     int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
1940     if (!A.Align) {
1941       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
1942     } else {
1943       unsigned M = 1 << A.Align;
1944       Min *= M;
1945       Max *= M;
1946       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
1947                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
1948     }
1949   }
1950   return Error;
1951 }
1952 
1953 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1954 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1955 // ordering for DSP is unspecified. MSA is ordered by the data format used
1956 // by the underlying instruction i.e., df/m, df/n and then by size.
1957 //
1958 // FIXME: The size tests here should instead be tablegen'd along with the
1959 //        definitions from include/clang/Basic/BuiltinsMips.def.
1960 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1961 //        be too.
1962 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1963   unsigned i = 0, l = 0, u = 0, m = 0;
1964   switch (BuiltinID) {
1965   default: return false;
1966   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1967   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1968   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1969   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1970   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1971   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1972   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1973   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1974   // df/m field.
1975   // These intrinsics take an unsigned 3 bit immediate.
1976   case Mips::BI__builtin_msa_bclri_b:
1977   case Mips::BI__builtin_msa_bnegi_b:
1978   case Mips::BI__builtin_msa_bseti_b:
1979   case Mips::BI__builtin_msa_sat_s_b:
1980   case Mips::BI__builtin_msa_sat_u_b:
1981   case Mips::BI__builtin_msa_slli_b:
1982   case Mips::BI__builtin_msa_srai_b:
1983   case Mips::BI__builtin_msa_srari_b:
1984   case Mips::BI__builtin_msa_srli_b:
1985   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1986   case Mips::BI__builtin_msa_binsli_b:
1987   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1988   // These intrinsics take an unsigned 4 bit immediate.
1989   case Mips::BI__builtin_msa_bclri_h:
1990   case Mips::BI__builtin_msa_bnegi_h:
1991   case Mips::BI__builtin_msa_bseti_h:
1992   case Mips::BI__builtin_msa_sat_s_h:
1993   case Mips::BI__builtin_msa_sat_u_h:
1994   case Mips::BI__builtin_msa_slli_h:
1995   case Mips::BI__builtin_msa_srai_h:
1996   case Mips::BI__builtin_msa_srari_h:
1997   case Mips::BI__builtin_msa_srli_h:
1998   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1999   case Mips::BI__builtin_msa_binsli_h:
2000   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2001   // These intrinsics take an unsigned 5 bit immediate.
2002   // The first block of intrinsics actually have an unsigned 5 bit field,
2003   // not a df/n field.
2004   case Mips::BI__builtin_msa_clei_u_b:
2005   case Mips::BI__builtin_msa_clei_u_h:
2006   case Mips::BI__builtin_msa_clei_u_w:
2007   case Mips::BI__builtin_msa_clei_u_d:
2008   case Mips::BI__builtin_msa_clti_u_b:
2009   case Mips::BI__builtin_msa_clti_u_h:
2010   case Mips::BI__builtin_msa_clti_u_w:
2011   case Mips::BI__builtin_msa_clti_u_d:
2012   case Mips::BI__builtin_msa_maxi_u_b:
2013   case Mips::BI__builtin_msa_maxi_u_h:
2014   case Mips::BI__builtin_msa_maxi_u_w:
2015   case Mips::BI__builtin_msa_maxi_u_d:
2016   case Mips::BI__builtin_msa_mini_u_b:
2017   case Mips::BI__builtin_msa_mini_u_h:
2018   case Mips::BI__builtin_msa_mini_u_w:
2019   case Mips::BI__builtin_msa_mini_u_d:
2020   case Mips::BI__builtin_msa_addvi_b:
2021   case Mips::BI__builtin_msa_addvi_h:
2022   case Mips::BI__builtin_msa_addvi_w:
2023   case Mips::BI__builtin_msa_addvi_d:
2024   case Mips::BI__builtin_msa_bclri_w:
2025   case Mips::BI__builtin_msa_bnegi_w:
2026   case Mips::BI__builtin_msa_bseti_w:
2027   case Mips::BI__builtin_msa_sat_s_w:
2028   case Mips::BI__builtin_msa_sat_u_w:
2029   case Mips::BI__builtin_msa_slli_w:
2030   case Mips::BI__builtin_msa_srai_w:
2031   case Mips::BI__builtin_msa_srari_w:
2032   case Mips::BI__builtin_msa_srli_w:
2033   case Mips::BI__builtin_msa_srlri_w:
2034   case Mips::BI__builtin_msa_subvi_b:
2035   case Mips::BI__builtin_msa_subvi_h:
2036   case Mips::BI__builtin_msa_subvi_w:
2037   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2038   case Mips::BI__builtin_msa_binsli_w:
2039   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2040   // These intrinsics take an unsigned 6 bit immediate.
2041   case Mips::BI__builtin_msa_bclri_d:
2042   case Mips::BI__builtin_msa_bnegi_d:
2043   case Mips::BI__builtin_msa_bseti_d:
2044   case Mips::BI__builtin_msa_sat_s_d:
2045   case Mips::BI__builtin_msa_sat_u_d:
2046   case Mips::BI__builtin_msa_slli_d:
2047   case Mips::BI__builtin_msa_srai_d:
2048   case Mips::BI__builtin_msa_srari_d:
2049   case Mips::BI__builtin_msa_srli_d:
2050   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2051   case Mips::BI__builtin_msa_binsli_d:
2052   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2053   // These intrinsics take a signed 5 bit immediate.
2054   case Mips::BI__builtin_msa_ceqi_b:
2055   case Mips::BI__builtin_msa_ceqi_h:
2056   case Mips::BI__builtin_msa_ceqi_w:
2057   case Mips::BI__builtin_msa_ceqi_d:
2058   case Mips::BI__builtin_msa_clti_s_b:
2059   case Mips::BI__builtin_msa_clti_s_h:
2060   case Mips::BI__builtin_msa_clti_s_w:
2061   case Mips::BI__builtin_msa_clti_s_d:
2062   case Mips::BI__builtin_msa_clei_s_b:
2063   case Mips::BI__builtin_msa_clei_s_h:
2064   case Mips::BI__builtin_msa_clei_s_w:
2065   case Mips::BI__builtin_msa_clei_s_d:
2066   case Mips::BI__builtin_msa_maxi_s_b:
2067   case Mips::BI__builtin_msa_maxi_s_h:
2068   case Mips::BI__builtin_msa_maxi_s_w:
2069   case Mips::BI__builtin_msa_maxi_s_d:
2070   case Mips::BI__builtin_msa_mini_s_b:
2071   case Mips::BI__builtin_msa_mini_s_h:
2072   case Mips::BI__builtin_msa_mini_s_w:
2073   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2074   // These intrinsics take an unsigned 8 bit immediate.
2075   case Mips::BI__builtin_msa_andi_b:
2076   case Mips::BI__builtin_msa_nori_b:
2077   case Mips::BI__builtin_msa_ori_b:
2078   case Mips::BI__builtin_msa_shf_b:
2079   case Mips::BI__builtin_msa_shf_h:
2080   case Mips::BI__builtin_msa_shf_w:
2081   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2082   case Mips::BI__builtin_msa_bseli_b:
2083   case Mips::BI__builtin_msa_bmnzi_b:
2084   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2085   // df/n format
2086   // These intrinsics take an unsigned 4 bit immediate.
2087   case Mips::BI__builtin_msa_copy_s_b:
2088   case Mips::BI__builtin_msa_copy_u_b:
2089   case Mips::BI__builtin_msa_insve_b:
2090   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2091   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2092   // These intrinsics take an unsigned 3 bit immediate.
2093   case Mips::BI__builtin_msa_copy_s_h:
2094   case Mips::BI__builtin_msa_copy_u_h:
2095   case Mips::BI__builtin_msa_insve_h:
2096   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2097   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2098   // These intrinsics take an unsigned 2 bit immediate.
2099   case Mips::BI__builtin_msa_copy_s_w:
2100   case Mips::BI__builtin_msa_copy_u_w:
2101   case Mips::BI__builtin_msa_insve_w:
2102   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2103   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2104   // These intrinsics take an unsigned 1 bit immediate.
2105   case Mips::BI__builtin_msa_copy_s_d:
2106   case Mips::BI__builtin_msa_copy_u_d:
2107   case Mips::BI__builtin_msa_insve_d:
2108   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2109   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2110   // Memory offsets and immediate loads.
2111   // These intrinsics take a signed 10 bit immediate.
2112   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2113   case Mips::BI__builtin_msa_ldi_h:
2114   case Mips::BI__builtin_msa_ldi_w:
2115   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2116   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2117   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2118   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2119   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2120   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
2121   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
2122   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
2123   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
2124   }
2125 
2126   if (!m)
2127     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2128 
2129   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2130          SemaBuiltinConstantArgMultiple(TheCall, i, m);
2131 }
2132 
2133 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2134   unsigned i = 0, l = 0, u = 0;
2135   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2136                       BuiltinID == PPC::BI__builtin_divdeu ||
2137                       BuiltinID == PPC::BI__builtin_bpermd;
2138   bool IsTarget64Bit = Context.getTargetInfo()
2139                               .getTypeWidth(Context
2140                                             .getTargetInfo()
2141                                             .getIntPtrType()) == 64;
2142   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2143                        BuiltinID == PPC::BI__builtin_divweu ||
2144                        BuiltinID == PPC::BI__builtin_divde ||
2145                        BuiltinID == PPC::BI__builtin_divdeu;
2146 
2147   if (Is64BitBltin && !IsTarget64Bit)
2148       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
2149              << TheCall->getSourceRange();
2150 
2151   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2152       (BuiltinID == PPC::BI__builtin_bpermd &&
2153        !Context.getTargetInfo().hasFeature("bpermd")))
2154     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
2155            << TheCall->getSourceRange();
2156 
2157   switch (BuiltinID) {
2158   default: return false;
2159   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2160   case PPC::BI__builtin_altivec_crypto_vshasigmad:
2161     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2162            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2163   case PPC::BI__builtin_tbegin:
2164   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2165   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2166   case PPC::BI__builtin_tabortwc:
2167   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2168   case PPC::BI__builtin_tabortwci:
2169   case PPC::BI__builtin_tabortdci:
2170     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2171            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
2172   case PPC::BI__builtin_vsx_xxpermdi:
2173   case PPC::BI__builtin_vsx_xxsldwi:
2174     return SemaBuiltinVSX(TheCall);
2175   }
2176   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2177 }
2178 
2179 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2180                                            CallExpr *TheCall) {
2181   if (BuiltinID == SystemZ::BI__builtin_tabort) {
2182     Expr *Arg = TheCall->getArg(0);
2183     llvm::APSInt AbortCode(32);
2184     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2185         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2186       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
2187              << Arg->getSourceRange();
2188   }
2189 
2190   // For intrinsics which take an immediate value as part of the instruction,
2191   // range check them here.
2192   unsigned i = 0, l = 0, u = 0;
2193   switch (BuiltinID) {
2194   default: return false;
2195   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2196   case SystemZ::BI__builtin_s390_verimb:
2197   case SystemZ::BI__builtin_s390_verimh:
2198   case SystemZ::BI__builtin_s390_verimf:
2199   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2200   case SystemZ::BI__builtin_s390_vfaeb:
2201   case SystemZ::BI__builtin_s390_vfaeh:
2202   case SystemZ::BI__builtin_s390_vfaef:
2203   case SystemZ::BI__builtin_s390_vfaebs:
2204   case SystemZ::BI__builtin_s390_vfaehs:
2205   case SystemZ::BI__builtin_s390_vfaefs:
2206   case SystemZ::BI__builtin_s390_vfaezb:
2207   case SystemZ::BI__builtin_s390_vfaezh:
2208   case SystemZ::BI__builtin_s390_vfaezf:
2209   case SystemZ::BI__builtin_s390_vfaezbs:
2210   case SystemZ::BI__builtin_s390_vfaezhs:
2211   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
2212   case SystemZ::BI__builtin_s390_vfisb:
2213   case SystemZ::BI__builtin_s390_vfidb:
2214     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2215            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2216   case SystemZ::BI__builtin_s390_vftcisb:
2217   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2218   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2219   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2220   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2221   case SystemZ::BI__builtin_s390_vstrcb:
2222   case SystemZ::BI__builtin_s390_vstrch:
2223   case SystemZ::BI__builtin_s390_vstrcf:
2224   case SystemZ::BI__builtin_s390_vstrczb:
2225   case SystemZ::BI__builtin_s390_vstrczh:
2226   case SystemZ::BI__builtin_s390_vstrczf:
2227   case SystemZ::BI__builtin_s390_vstrcbs:
2228   case SystemZ::BI__builtin_s390_vstrchs:
2229   case SystemZ::BI__builtin_s390_vstrcfs:
2230   case SystemZ::BI__builtin_s390_vstrczbs:
2231   case SystemZ::BI__builtin_s390_vstrczhs:
2232   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
2233   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2234   case SystemZ::BI__builtin_s390_vfminsb:
2235   case SystemZ::BI__builtin_s390_vfmaxsb:
2236   case SystemZ::BI__builtin_s390_vfmindb:
2237   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
2238   }
2239   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2240 }
2241 
2242 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2243 /// This checks that the target supports __builtin_cpu_supports and
2244 /// that the string argument is constant and valid.
2245 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2246   Expr *Arg = TheCall->getArg(0);
2247 
2248   // Check if the argument is a string literal.
2249   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2250     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2251            << Arg->getSourceRange();
2252 
2253   // Check the contents of the string.
2254   StringRef Feature =
2255       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2256   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2257     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2258            << Arg->getSourceRange();
2259   return false;
2260 }
2261 
2262 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2263 /// This checks that the target supports __builtin_cpu_is and
2264 /// that the string argument is constant and valid.
2265 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2266   Expr *Arg = TheCall->getArg(0);
2267 
2268   // Check if the argument is a string literal.
2269   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2270     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2271            << Arg->getSourceRange();
2272 
2273   // Check the contents of the string.
2274   StringRef Feature =
2275       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2276   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2277     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
2278            << Arg->getSourceRange();
2279   return false;
2280 }
2281 
2282 // Check if the rounding mode is legal.
2283 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2284   // Indicates if this instruction has rounding control or just SAE.
2285   bool HasRC = false;
2286 
2287   unsigned ArgNum = 0;
2288   switch (BuiltinID) {
2289   default:
2290     return false;
2291   case X86::BI__builtin_ia32_vcvttsd2si32:
2292   case X86::BI__builtin_ia32_vcvttsd2si64:
2293   case X86::BI__builtin_ia32_vcvttsd2usi32:
2294   case X86::BI__builtin_ia32_vcvttsd2usi64:
2295   case X86::BI__builtin_ia32_vcvttss2si32:
2296   case X86::BI__builtin_ia32_vcvttss2si64:
2297   case X86::BI__builtin_ia32_vcvttss2usi32:
2298   case X86::BI__builtin_ia32_vcvttss2usi64:
2299     ArgNum = 1;
2300     break;
2301   case X86::BI__builtin_ia32_maxpd512:
2302   case X86::BI__builtin_ia32_maxps512:
2303   case X86::BI__builtin_ia32_minpd512:
2304   case X86::BI__builtin_ia32_minps512:
2305     ArgNum = 2;
2306     break;
2307   case X86::BI__builtin_ia32_cvtps2pd512_mask:
2308   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2309   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2310   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2311   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2312   case X86::BI__builtin_ia32_cvttps2dq512_mask:
2313   case X86::BI__builtin_ia32_cvttps2qq512_mask:
2314   case X86::BI__builtin_ia32_cvttps2udq512_mask:
2315   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2316   case X86::BI__builtin_ia32_exp2pd_mask:
2317   case X86::BI__builtin_ia32_exp2ps_mask:
2318   case X86::BI__builtin_ia32_getexppd512_mask:
2319   case X86::BI__builtin_ia32_getexpps512_mask:
2320   case X86::BI__builtin_ia32_rcp28pd_mask:
2321   case X86::BI__builtin_ia32_rcp28ps_mask:
2322   case X86::BI__builtin_ia32_rsqrt28pd_mask:
2323   case X86::BI__builtin_ia32_rsqrt28ps_mask:
2324   case X86::BI__builtin_ia32_vcomisd:
2325   case X86::BI__builtin_ia32_vcomiss:
2326   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2327     ArgNum = 3;
2328     break;
2329   case X86::BI__builtin_ia32_cmppd512_mask:
2330   case X86::BI__builtin_ia32_cmpps512_mask:
2331   case X86::BI__builtin_ia32_cmpsd_mask:
2332   case X86::BI__builtin_ia32_cmpss_mask:
2333   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
2334   case X86::BI__builtin_ia32_getexpsd128_round_mask:
2335   case X86::BI__builtin_ia32_getexpss128_round_mask:
2336   case X86::BI__builtin_ia32_maxsd_round_mask:
2337   case X86::BI__builtin_ia32_maxss_round_mask:
2338   case X86::BI__builtin_ia32_minsd_round_mask:
2339   case X86::BI__builtin_ia32_minss_round_mask:
2340   case X86::BI__builtin_ia32_rcp28sd_round_mask:
2341   case X86::BI__builtin_ia32_rcp28ss_round_mask:
2342   case X86::BI__builtin_ia32_reducepd512_mask:
2343   case X86::BI__builtin_ia32_reduceps512_mask:
2344   case X86::BI__builtin_ia32_rndscalepd_mask:
2345   case X86::BI__builtin_ia32_rndscaleps_mask:
2346   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2347   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2348     ArgNum = 4;
2349     break;
2350   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2351   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2352   case X86::BI__builtin_ia32_fixupimmps512_mask:
2353   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2354   case X86::BI__builtin_ia32_fixupimmsd_mask:
2355   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2356   case X86::BI__builtin_ia32_fixupimmss_mask:
2357   case X86::BI__builtin_ia32_fixupimmss_maskz:
2358   case X86::BI__builtin_ia32_rangepd512_mask:
2359   case X86::BI__builtin_ia32_rangeps512_mask:
2360   case X86::BI__builtin_ia32_rangesd128_round_mask:
2361   case X86::BI__builtin_ia32_rangess128_round_mask:
2362   case X86::BI__builtin_ia32_reducesd_mask:
2363   case X86::BI__builtin_ia32_reducess_mask:
2364   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2365   case X86::BI__builtin_ia32_rndscaless_round_mask:
2366     ArgNum = 5;
2367     break;
2368   case X86::BI__builtin_ia32_vcvtsd2si64:
2369   case X86::BI__builtin_ia32_vcvtsd2si32:
2370   case X86::BI__builtin_ia32_vcvtsd2usi32:
2371   case X86::BI__builtin_ia32_vcvtsd2usi64:
2372   case X86::BI__builtin_ia32_vcvtss2si32:
2373   case X86::BI__builtin_ia32_vcvtss2si64:
2374   case X86::BI__builtin_ia32_vcvtss2usi32:
2375   case X86::BI__builtin_ia32_vcvtss2usi64:
2376     ArgNum = 1;
2377     HasRC = true;
2378     break;
2379   case X86::BI__builtin_ia32_addpd512:
2380   case X86::BI__builtin_ia32_addps512:
2381   case X86::BI__builtin_ia32_divpd512:
2382   case X86::BI__builtin_ia32_divps512:
2383   case X86::BI__builtin_ia32_mulpd512:
2384   case X86::BI__builtin_ia32_mulps512:
2385   case X86::BI__builtin_ia32_subpd512:
2386   case X86::BI__builtin_ia32_subps512:
2387   case X86::BI__builtin_ia32_cvtsi2sd64:
2388   case X86::BI__builtin_ia32_cvtsi2ss32:
2389   case X86::BI__builtin_ia32_cvtsi2ss64:
2390   case X86::BI__builtin_ia32_cvtusi2sd64:
2391   case X86::BI__builtin_ia32_cvtusi2ss32:
2392   case X86::BI__builtin_ia32_cvtusi2ss64:
2393     ArgNum = 2;
2394     HasRC = true;
2395     break;
2396   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2397   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2398   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2399   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2400   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2401   case X86::BI__builtin_ia32_cvtps2qq512_mask:
2402   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2403   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2404   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2405   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2406   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2407   case X86::BI__builtin_ia32_sqrtpd512_mask:
2408   case X86::BI__builtin_ia32_sqrtps512_mask:
2409     ArgNum = 3;
2410     HasRC = true;
2411     break;
2412   case X86::BI__builtin_ia32_addss_round_mask:
2413   case X86::BI__builtin_ia32_addsd_round_mask:
2414   case X86::BI__builtin_ia32_divss_round_mask:
2415   case X86::BI__builtin_ia32_divsd_round_mask:
2416   case X86::BI__builtin_ia32_mulss_round_mask:
2417   case X86::BI__builtin_ia32_mulsd_round_mask:
2418   case X86::BI__builtin_ia32_subss_round_mask:
2419   case X86::BI__builtin_ia32_subsd_round_mask:
2420   case X86::BI__builtin_ia32_scalefpd512_mask:
2421   case X86::BI__builtin_ia32_scalefps512_mask:
2422   case X86::BI__builtin_ia32_scalefsd_round_mask:
2423   case X86::BI__builtin_ia32_scalefss_round_mask:
2424   case X86::BI__builtin_ia32_getmantpd512_mask:
2425   case X86::BI__builtin_ia32_getmantps512_mask:
2426   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2427   case X86::BI__builtin_ia32_sqrtsd_round_mask:
2428   case X86::BI__builtin_ia32_sqrtss_round_mask:
2429   case X86::BI__builtin_ia32_vfmaddsd3_mask:
2430   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2431   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2432   case X86::BI__builtin_ia32_vfmaddss3_mask:
2433   case X86::BI__builtin_ia32_vfmaddss3_maskz:
2434   case X86::BI__builtin_ia32_vfmaddss3_mask3:
2435   case X86::BI__builtin_ia32_vfmaddpd512_mask:
2436   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2437   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2438   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2439   case X86::BI__builtin_ia32_vfmaddps512_mask:
2440   case X86::BI__builtin_ia32_vfmaddps512_maskz:
2441   case X86::BI__builtin_ia32_vfmaddps512_mask3:
2442   case X86::BI__builtin_ia32_vfmsubps512_mask3:
2443   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2444   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2445   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2446   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2447   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2448   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2449   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2450   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2451     ArgNum = 4;
2452     HasRC = true;
2453     break;
2454   case X86::BI__builtin_ia32_getmantsd_round_mask:
2455   case X86::BI__builtin_ia32_getmantss_round_mask:
2456     ArgNum = 5;
2457     HasRC = true;
2458     break;
2459   }
2460 
2461   llvm::APSInt Result;
2462 
2463   // We can't check the value of a dependent argument.
2464   Expr *Arg = TheCall->getArg(ArgNum);
2465   if (Arg->isTypeDependent() || Arg->isValueDependent())
2466     return false;
2467 
2468   // Check constant-ness first.
2469   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2470     return true;
2471 
2472   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2473   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2474   // combined with ROUND_NO_EXC.
2475   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2476       Result == 8/*ROUND_NO_EXC*/ ||
2477       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2478     return false;
2479 
2480   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2481     << Arg->getSourceRange();
2482 }
2483 
2484 // Check if the gather/scatter scale is legal.
2485 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2486                                              CallExpr *TheCall) {
2487   unsigned ArgNum = 0;
2488   switch (BuiltinID) {
2489   default:
2490     return false;
2491   case X86::BI__builtin_ia32_gatherpfdpd:
2492   case X86::BI__builtin_ia32_gatherpfdps:
2493   case X86::BI__builtin_ia32_gatherpfqpd:
2494   case X86::BI__builtin_ia32_gatherpfqps:
2495   case X86::BI__builtin_ia32_scatterpfdpd:
2496   case X86::BI__builtin_ia32_scatterpfdps:
2497   case X86::BI__builtin_ia32_scatterpfqpd:
2498   case X86::BI__builtin_ia32_scatterpfqps:
2499     ArgNum = 3;
2500     break;
2501   case X86::BI__builtin_ia32_gatherd_pd:
2502   case X86::BI__builtin_ia32_gatherd_pd256:
2503   case X86::BI__builtin_ia32_gatherq_pd:
2504   case X86::BI__builtin_ia32_gatherq_pd256:
2505   case X86::BI__builtin_ia32_gatherd_ps:
2506   case X86::BI__builtin_ia32_gatherd_ps256:
2507   case X86::BI__builtin_ia32_gatherq_ps:
2508   case X86::BI__builtin_ia32_gatherq_ps256:
2509   case X86::BI__builtin_ia32_gatherd_q:
2510   case X86::BI__builtin_ia32_gatherd_q256:
2511   case X86::BI__builtin_ia32_gatherq_q:
2512   case X86::BI__builtin_ia32_gatherq_q256:
2513   case X86::BI__builtin_ia32_gatherd_d:
2514   case X86::BI__builtin_ia32_gatherd_d256:
2515   case X86::BI__builtin_ia32_gatherq_d:
2516   case X86::BI__builtin_ia32_gatherq_d256:
2517   case X86::BI__builtin_ia32_gather3div2df:
2518   case X86::BI__builtin_ia32_gather3div2di:
2519   case X86::BI__builtin_ia32_gather3div4df:
2520   case X86::BI__builtin_ia32_gather3div4di:
2521   case X86::BI__builtin_ia32_gather3div4sf:
2522   case X86::BI__builtin_ia32_gather3div4si:
2523   case X86::BI__builtin_ia32_gather3div8sf:
2524   case X86::BI__builtin_ia32_gather3div8si:
2525   case X86::BI__builtin_ia32_gather3siv2df:
2526   case X86::BI__builtin_ia32_gather3siv2di:
2527   case X86::BI__builtin_ia32_gather3siv4df:
2528   case X86::BI__builtin_ia32_gather3siv4di:
2529   case X86::BI__builtin_ia32_gather3siv4sf:
2530   case X86::BI__builtin_ia32_gather3siv4si:
2531   case X86::BI__builtin_ia32_gather3siv8sf:
2532   case X86::BI__builtin_ia32_gather3siv8si:
2533   case X86::BI__builtin_ia32_gathersiv8df:
2534   case X86::BI__builtin_ia32_gathersiv16sf:
2535   case X86::BI__builtin_ia32_gatherdiv8df:
2536   case X86::BI__builtin_ia32_gatherdiv16sf:
2537   case X86::BI__builtin_ia32_gathersiv8di:
2538   case X86::BI__builtin_ia32_gathersiv16si:
2539   case X86::BI__builtin_ia32_gatherdiv8di:
2540   case X86::BI__builtin_ia32_gatherdiv16si:
2541   case X86::BI__builtin_ia32_scatterdiv2df:
2542   case X86::BI__builtin_ia32_scatterdiv2di:
2543   case X86::BI__builtin_ia32_scatterdiv4df:
2544   case X86::BI__builtin_ia32_scatterdiv4di:
2545   case X86::BI__builtin_ia32_scatterdiv4sf:
2546   case X86::BI__builtin_ia32_scatterdiv4si:
2547   case X86::BI__builtin_ia32_scatterdiv8sf:
2548   case X86::BI__builtin_ia32_scatterdiv8si:
2549   case X86::BI__builtin_ia32_scattersiv2df:
2550   case X86::BI__builtin_ia32_scattersiv2di:
2551   case X86::BI__builtin_ia32_scattersiv4df:
2552   case X86::BI__builtin_ia32_scattersiv4di:
2553   case X86::BI__builtin_ia32_scattersiv4sf:
2554   case X86::BI__builtin_ia32_scattersiv4si:
2555   case X86::BI__builtin_ia32_scattersiv8sf:
2556   case X86::BI__builtin_ia32_scattersiv8si:
2557   case X86::BI__builtin_ia32_scattersiv8df:
2558   case X86::BI__builtin_ia32_scattersiv16sf:
2559   case X86::BI__builtin_ia32_scatterdiv8df:
2560   case X86::BI__builtin_ia32_scatterdiv16sf:
2561   case X86::BI__builtin_ia32_scattersiv8di:
2562   case X86::BI__builtin_ia32_scattersiv16si:
2563   case X86::BI__builtin_ia32_scatterdiv8di:
2564   case X86::BI__builtin_ia32_scatterdiv16si:
2565     ArgNum = 4;
2566     break;
2567   }
2568 
2569   llvm::APSInt Result;
2570 
2571   // We can't check the value of a dependent argument.
2572   Expr *Arg = TheCall->getArg(ArgNum);
2573   if (Arg->isTypeDependent() || Arg->isValueDependent())
2574     return false;
2575 
2576   // Check constant-ness first.
2577   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2578     return true;
2579 
2580   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2581     return false;
2582 
2583   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2584     << Arg->getSourceRange();
2585 }
2586 
2587 static bool isX86_32Builtin(unsigned BuiltinID) {
2588   // These builtins only work on x86-32 targets.
2589   switch (BuiltinID) {
2590   case X86::BI__builtin_ia32_readeflags_u32:
2591   case X86::BI__builtin_ia32_writeeflags_u32:
2592     return true;
2593   }
2594 
2595   return false;
2596 }
2597 
2598 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2599   if (BuiltinID == X86::BI__builtin_cpu_supports)
2600     return SemaBuiltinCpuSupports(*this, TheCall);
2601 
2602   if (BuiltinID == X86::BI__builtin_cpu_is)
2603     return SemaBuiltinCpuIs(*this, TheCall);
2604 
2605   // Check for 32-bit only builtins on a 64-bit target.
2606   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2607   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2608     return Diag(TheCall->getCallee()->getLocStart(),
2609                 diag::err_32_bit_builtin_64_bit_tgt);
2610 
2611   // If the intrinsic has rounding or SAE make sure its valid.
2612   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2613     return true;
2614 
2615   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2616   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2617     return true;
2618 
2619   // For intrinsics which take an immediate value as part of the instruction,
2620   // range check them here.
2621   int i = 0, l = 0, u = 0;
2622   switch (BuiltinID) {
2623   default:
2624     return false;
2625   case X86::BI__builtin_ia32_vec_ext_v2si:
2626   case X86::BI__builtin_ia32_vec_ext_v2di:
2627   case X86::BI__builtin_ia32_vextractf128_pd256:
2628   case X86::BI__builtin_ia32_vextractf128_ps256:
2629   case X86::BI__builtin_ia32_vextractf128_si256:
2630   case X86::BI__builtin_ia32_extract128i256:
2631   case X86::BI__builtin_ia32_extractf64x4_mask:
2632   case X86::BI__builtin_ia32_extracti64x4_mask:
2633   case X86::BI__builtin_ia32_extractf32x8_mask:
2634   case X86::BI__builtin_ia32_extracti32x8_mask:
2635   case X86::BI__builtin_ia32_extractf64x2_256_mask:
2636   case X86::BI__builtin_ia32_extracti64x2_256_mask:
2637   case X86::BI__builtin_ia32_extractf32x4_256_mask:
2638   case X86::BI__builtin_ia32_extracti32x4_256_mask:
2639     i = 1; l = 0; u = 1;
2640     break;
2641   case X86::BI__builtin_ia32_vec_set_v2di:
2642   case X86::BI__builtin_ia32_vinsertf128_pd256:
2643   case X86::BI__builtin_ia32_vinsertf128_ps256:
2644   case X86::BI__builtin_ia32_vinsertf128_si256:
2645   case X86::BI__builtin_ia32_insert128i256:
2646   case X86::BI__builtin_ia32_insertf32x8:
2647   case X86::BI__builtin_ia32_inserti32x8:
2648   case X86::BI__builtin_ia32_insertf64x4:
2649   case X86::BI__builtin_ia32_inserti64x4:
2650   case X86::BI__builtin_ia32_insertf64x2_256:
2651   case X86::BI__builtin_ia32_inserti64x2_256:
2652   case X86::BI__builtin_ia32_insertf32x4_256:
2653   case X86::BI__builtin_ia32_inserti32x4_256:
2654     i = 2; l = 0; u = 1;
2655     break;
2656   case X86::BI__builtin_ia32_vpermilpd:
2657   case X86::BI__builtin_ia32_vec_ext_v4hi:
2658   case X86::BI__builtin_ia32_vec_ext_v4si:
2659   case X86::BI__builtin_ia32_vec_ext_v4sf:
2660   case X86::BI__builtin_ia32_vec_ext_v4di:
2661   case X86::BI__builtin_ia32_extractf32x4_mask:
2662   case X86::BI__builtin_ia32_extracti32x4_mask:
2663   case X86::BI__builtin_ia32_extractf64x2_512_mask:
2664   case X86::BI__builtin_ia32_extracti64x2_512_mask:
2665     i = 1; l = 0; u = 3;
2666     break;
2667   case X86::BI_mm_prefetch:
2668   case X86::BI__builtin_ia32_vec_ext_v8hi:
2669   case X86::BI__builtin_ia32_vec_ext_v8si:
2670     i = 1; l = 0; u = 7;
2671     break;
2672   case X86::BI__builtin_ia32_sha1rnds4:
2673   case X86::BI__builtin_ia32_blendpd:
2674   case X86::BI__builtin_ia32_shufpd:
2675   case X86::BI__builtin_ia32_vec_set_v4hi:
2676   case X86::BI__builtin_ia32_vec_set_v4si:
2677   case X86::BI__builtin_ia32_vec_set_v4di:
2678   case X86::BI__builtin_ia32_shuf_f32x4_256:
2679   case X86::BI__builtin_ia32_shuf_f64x2_256:
2680   case X86::BI__builtin_ia32_shuf_i32x4_256:
2681   case X86::BI__builtin_ia32_shuf_i64x2_256:
2682   case X86::BI__builtin_ia32_insertf64x2_512:
2683   case X86::BI__builtin_ia32_inserti64x2_512:
2684   case X86::BI__builtin_ia32_insertf32x4:
2685   case X86::BI__builtin_ia32_inserti32x4:
2686     i = 2; l = 0; u = 3;
2687     break;
2688   case X86::BI__builtin_ia32_vpermil2pd:
2689   case X86::BI__builtin_ia32_vpermil2pd256:
2690   case X86::BI__builtin_ia32_vpermil2ps:
2691   case X86::BI__builtin_ia32_vpermil2ps256:
2692     i = 3; l = 0; u = 3;
2693     break;
2694   case X86::BI__builtin_ia32_cmpb128_mask:
2695   case X86::BI__builtin_ia32_cmpw128_mask:
2696   case X86::BI__builtin_ia32_cmpd128_mask:
2697   case X86::BI__builtin_ia32_cmpq128_mask:
2698   case X86::BI__builtin_ia32_cmpb256_mask:
2699   case X86::BI__builtin_ia32_cmpw256_mask:
2700   case X86::BI__builtin_ia32_cmpd256_mask:
2701   case X86::BI__builtin_ia32_cmpq256_mask:
2702   case X86::BI__builtin_ia32_cmpb512_mask:
2703   case X86::BI__builtin_ia32_cmpw512_mask:
2704   case X86::BI__builtin_ia32_cmpd512_mask:
2705   case X86::BI__builtin_ia32_cmpq512_mask:
2706   case X86::BI__builtin_ia32_ucmpb128_mask:
2707   case X86::BI__builtin_ia32_ucmpw128_mask:
2708   case X86::BI__builtin_ia32_ucmpd128_mask:
2709   case X86::BI__builtin_ia32_ucmpq128_mask:
2710   case X86::BI__builtin_ia32_ucmpb256_mask:
2711   case X86::BI__builtin_ia32_ucmpw256_mask:
2712   case X86::BI__builtin_ia32_ucmpd256_mask:
2713   case X86::BI__builtin_ia32_ucmpq256_mask:
2714   case X86::BI__builtin_ia32_ucmpb512_mask:
2715   case X86::BI__builtin_ia32_ucmpw512_mask:
2716   case X86::BI__builtin_ia32_ucmpd512_mask:
2717   case X86::BI__builtin_ia32_ucmpq512_mask:
2718   case X86::BI__builtin_ia32_vpcomub:
2719   case X86::BI__builtin_ia32_vpcomuw:
2720   case X86::BI__builtin_ia32_vpcomud:
2721   case X86::BI__builtin_ia32_vpcomuq:
2722   case X86::BI__builtin_ia32_vpcomb:
2723   case X86::BI__builtin_ia32_vpcomw:
2724   case X86::BI__builtin_ia32_vpcomd:
2725   case X86::BI__builtin_ia32_vpcomq:
2726   case X86::BI__builtin_ia32_vec_set_v8hi:
2727   case X86::BI__builtin_ia32_vec_set_v8si:
2728     i = 2; l = 0; u = 7;
2729     break;
2730   case X86::BI__builtin_ia32_vpermilpd256:
2731   case X86::BI__builtin_ia32_roundps:
2732   case X86::BI__builtin_ia32_roundpd:
2733   case X86::BI__builtin_ia32_roundps256:
2734   case X86::BI__builtin_ia32_roundpd256:
2735   case X86::BI__builtin_ia32_getmantpd128_mask:
2736   case X86::BI__builtin_ia32_getmantpd256_mask:
2737   case X86::BI__builtin_ia32_getmantps128_mask:
2738   case X86::BI__builtin_ia32_getmantps256_mask:
2739   case X86::BI__builtin_ia32_getmantpd512_mask:
2740   case X86::BI__builtin_ia32_getmantps512_mask:
2741   case X86::BI__builtin_ia32_vec_ext_v16qi:
2742   case X86::BI__builtin_ia32_vec_ext_v16hi:
2743     i = 1; l = 0; u = 15;
2744     break;
2745   case X86::BI__builtin_ia32_pblendd128:
2746   case X86::BI__builtin_ia32_blendps:
2747   case X86::BI__builtin_ia32_blendpd256:
2748   case X86::BI__builtin_ia32_shufpd256:
2749   case X86::BI__builtin_ia32_roundss:
2750   case X86::BI__builtin_ia32_roundsd:
2751   case X86::BI__builtin_ia32_rangepd128_mask:
2752   case X86::BI__builtin_ia32_rangepd256_mask:
2753   case X86::BI__builtin_ia32_rangepd512_mask:
2754   case X86::BI__builtin_ia32_rangeps128_mask:
2755   case X86::BI__builtin_ia32_rangeps256_mask:
2756   case X86::BI__builtin_ia32_rangeps512_mask:
2757   case X86::BI__builtin_ia32_getmantsd_round_mask:
2758   case X86::BI__builtin_ia32_getmantss_round_mask:
2759   case X86::BI__builtin_ia32_vec_set_v16qi:
2760   case X86::BI__builtin_ia32_vec_set_v16hi:
2761     i = 2; l = 0; u = 15;
2762     break;
2763   case X86::BI__builtin_ia32_vec_ext_v32qi:
2764     i = 1; l = 0; u = 31;
2765     break;
2766   case X86::BI__builtin_ia32_cmpps:
2767   case X86::BI__builtin_ia32_cmpss:
2768   case X86::BI__builtin_ia32_cmppd:
2769   case X86::BI__builtin_ia32_cmpsd:
2770   case X86::BI__builtin_ia32_cmpps256:
2771   case X86::BI__builtin_ia32_cmppd256:
2772   case X86::BI__builtin_ia32_cmpps128_mask:
2773   case X86::BI__builtin_ia32_cmppd128_mask:
2774   case X86::BI__builtin_ia32_cmpps256_mask:
2775   case X86::BI__builtin_ia32_cmppd256_mask:
2776   case X86::BI__builtin_ia32_cmpps512_mask:
2777   case X86::BI__builtin_ia32_cmppd512_mask:
2778   case X86::BI__builtin_ia32_cmpsd_mask:
2779   case X86::BI__builtin_ia32_cmpss_mask:
2780   case X86::BI__builtin_ia32_vec_set_v32qi:
2781     i = 2; l = 0; u = 31;
2782     break;
2783   case X86::BI__builtin_ia32_permdf256:
2784   case X86::BI__builtin_ia32_permdi256:
2785   case X86::BI__builtin_ia32_permdf512:
2786   case X86::BI__builtin_ia32_permdi512:
2787   case X86::BI__builtin_ia32_vpermilps:
2788   case X86::BI__builtin_ia32_vpermilps256:
2789   case X86::BI__builtin_ia32_vpermilpd512:
2790   case X86::BI__builtin_ia32_vpermilps512:
2791   case X86::BI__builtin_ia32_pshufd:
2792   case X86::BI__builtin_ia32_pshufd256:
2793   case X86::BI__builtin_ia32_pshufd512:
2794   case X86::BI__builtin_ia32_pshufhw:
2795   case X86::BI__builtin_ia32_pshufhw256:
2796   case X86::BI__builtin_ia32_pshufhw512:
2797   case X86::BI__builtin_ia32_pshuflw:
2798   case X86::BI__builtin_ia32_pshuflw256:
2799   case X86::BI__builtin_ia32_pshuflw512:
2800   case X86::BI__builtin_ia32_vcvtps2ph:
2801   case X86::BI__builtin_ia32_vcvtps2ph_mask:
2802   case X86::BI__builtin_ia32_vcvtps2ph256:
2803   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2804   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2805   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2806   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2807   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2808   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2809   case X86::BI__builtin_ia32_rndscaleps_mask:
2810   case X86::BI__builtin_ia32_rndscalepd_mask:
2811   case X86::BI__builtin_ia32_reducepd128_mask:
2812   case X86::BI__builtin_ia32_reducepd256_mask:
2813   case X86::BI__builtin_ia32_reducepd512_mask:
2814   case X86::BI__builtin_ia32_reduceps128_mask:
2815   case X86::BI__builtin_ia32_reduceps256_mask:
2816   case X86::BI__builtin_ia32_reduceps512_mask:
2817   case X86::BI__builtin_ia32_prold512_mask:
2818   case X86::BI__builtin_ia32_prolq512_mask:
2819   case X86::BI__builtin_ia32_prold128_mask:
2820   case X86::BI__builtin_ia32_prold256_mask:
2821   case X86::BI__builtin_ia32_prolq128_mask:
2822   case X86::BI__builtin_ia32_prolq256_mask:
2823   case X86::BI__builtin_ia32_prord512_mask:
2824   case X86::BI__builtin_ia32_prorq512_mask:
2825   case X86::BI__builtin_ia32_prord128_mask:
2826   case X86::BI__builtin_ia32_prord256_mask:
2827   case X86::BI__builtin_ia32_prorq128_mask:
2828   case X86::BI__builtin_ia32_prorq256_mask:
2829   case X86::BI__builtin_ia32_fpclasspd128_mask:
2830   case X86::BI__builtin_ia32_fpclasspd256_mask:
2831   case X86::BI__builtin_ia32_fpclassps128_mask:
2832   case X86::BI__builtin_ia32_fpclassps256_mask:
2833   case X86::BI__builtin_ia32_fpclassps512_mask:
2834   case X86::BI__builtin_ia32_fpclasspd512_mask:
2835   case X86::BI__builtin_ia32_fpclasssd_mask:
2836   case X86::BI__builtin_ia32_fpclassss_mask:
2837   case X86::BI__builtin_ia32_pslldqi128_byteshift:
2838   case X86::BI__builtin_ia32_pslldqi256_byteshift:
2839   case X86::BI__builtin_ia32_pslldqi512_byteshift:
2840   case X86::BI__builtin_ia32_psrldqi128_byteshift:
2841   case X86::BI__builtin_ia32_psrldqi256_byteshift:
2842   case X86::BI__builtin_ia32_psrldqi512_byteshift:
2843     i = 1; l = 0; u = 255;
2844     break;
2845   case X86::BI__builtin_ia32_vperm2f128_pd256:
2846   case X86::BI__builtin_ia32_vperm2f128_ps256:
2847   case X86::BI__builtin_ia32_vperm2f128_si256:
2848   case X86::BI__builtin_ia32_permti256:
2849   case X86::BI__builtin_ia32_pblendw128:
2850   case X86::BI__builtin_ia32_pblendw256:
2851   case X86::BI__builtin_ia32_blendps256:
2852   case X86::BI__builtin_ia32_pblendd256:
2853   case X86::BI__builtin_ia32_palignr128:
2854   case X86::BI__builtin_ia32_palignr256:
2855   case X86::BI__builtin_ia32_palignr512:
2856   case X86::BI__builtin_ia32_alignq512:
2857   case X86::BI__builtin_ia32_alignd512:
2858   case X86::BI__builtin_ia32_alignd128:
2859   case X86::BI__builtin_ia32_alignd256:
2860   case X86::BI__builtin_ia32_alignq128:
2861   case X86::BI__builtin_ia32_alignq256:
2862   case X86::BI__builtin_ia32_vcomisd:
2863   case X86::BI__builtin_ia32_vcomiss:
2864   case X86::BI__builtin_ia32_shuf_f32x4:
2865   case X86::BI__builtin_ia32_shuf_f64x2:
2866   case X86::BI__builtin_ia32_shuf_i32x4:
2867   case X86::BI__builtin_ia32_shuf_i64x2:
2868   case X86::BI__builtin_ia32_shufpd512:
2869   case X86::BI__builtin_ia32_shufps:
2870   case X86::BI__builtin_ia32_shufps256:
2871   case X86::BI__builtin_ia32_shufps512:
2872   case X86::BI__builtin_ia32_dbpsadbw128:
2873   case X86::BI__builtin_ia32_dbpsadbw256:
2874   case X86::BI__builtin_ia32_dbpsadbw512:
2875   case X86::BI__builtin_ia32_vpshldd128:
2876   case X86::BI__builtin_ia32_vpshldd256:
2877   case X86::BI__builtin_ia32_vpshldd512:
2878   case X86::BI__builtin_ia32_vpshldq128:
2879   case X86::BI__builtin_ia32_vpshldq256:
2880   case X86::BI__builtin_ia32_vpshldq512:
2881   case X86::BI__builtin_ia32_vpshldw128:
2882   case X86::BI__builtin_ia32_vpshldw256:
2883   case X86::BI__builtin_ia32_vpshldw512:
2884   case X86::BI__builtin_ia32_vpshrdd128:
2885   case X86::BI__builtin_ia32_vpshrdd256:
2886   case X86::BI__builtin_ia32_vpshrdd512:
2887   case X86::BI__builtin_ia32_vpshrdq128:
2888   case X86::BI__builtin_ia32_vpshrdq256:
2889   case X86::BI__builtin_ia32_vpshrdq512:
2890   case X86::BI__builtin_ia32_vpshrdw128:
2891   case X86::BI__builtin_ia32_vpshrdw256:
2892   case X86::BI__builtin_ia32_vpshrdw512:
2893     i = 2; l = 0; u = 255;
2894     break;
2895   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2896   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2897   case X86::BI__builtin_ia32_fixupimmps512_mask:
2898   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2899   case X86::BI__builtin_ia32_fixupimmsd_mask:
2900   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2901   case X86::BI__builtin_ia32_fixupimmss_mask:
2902   case X86::BI__builtin_ia32_fixupimmss_maskz:
2903   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2904   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2905   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2906   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2907   case X86::BI__builtin_ia32_fixupimmps128_mask:
2908   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2909   case X86::BI__builtin_ia32_fixupimmps256_mask:
2910   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2911   case X86::BI__builtin_ia32_pternlogd512_mask:
2912   case X86::BI__builtin_ia32_pternlogd512_maskz:
2913   case X86::BI__builtin_ia32_pternlogq512_mask:
2914   case X86::BI__builtin_ia32_pternlogq512_maskz:
2915   case X86::BI__builtin_ia32_pternlogd128_mask:
2916   case X86::BI__builtin_ia32_pternlogd128_maskz:
2917   case X86::BI__builtin_ia32_pternlogd256_mask:
2918   case X86::BI__builtin_ia32_pternlogd256_maskz:
2919   case X86::BI__builtin_ia32_pternlogq128_mask:
2920   case X86::BI__builtin_ia32_pternlogq128_maskz:
2921   case X86::BI__builtin_ia32_pternlogq256_mask:
2922   case X86::BI__builtin_ia32_pternlogq256_maskz:
2923     i = 3; l = 0; u = 255;
2924     break;
2925   case X86::BI__builtin_ia32_gatherpfdpd:
2926   case X86::BI__builtin_ia32_gatherpfdps:
2927   case X86::BI__builtin_ia32_gatherpfqpd:
2928   case X86::BI__builtin_ia32_gatherpfqps:
2929   case X86::BI__builtin_ia32_scatterpfdpd:
2930   case X86::BI__builtin_ia32_scatterpfdps:
2931   case X86::BI__builtin_ia32_scatterpfqpd:
2932   case X86::BI__builtin_ia32_scatterpfqps:
2933     i = 4; l = 2; u = 3;
2934     break;
2935   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2936   case X86::BI__builtin_ia32_rndscaless_round_mask:
2937     i = 4; l = 0; u = 255;
2938     break;
2939   }
2940 
2941   // Note that we don't force a hard error on the range check here, allowing
2942   // template-generated or macro-generated dead code to potentially have out-of-
2943   // range values. These need to code generate, but don't need to necessarily
2944   // make any sense. We use a warning that defaults to an error.
2945   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
2946 }
2947 
2948 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2949 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2950 /// Returns true when the format fits the function and the FormatStringInfo has
2951 /// been populated.
2952 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2953                                FormatStringInfo *FSI) {
2954   FSI->HasVAListArg = Format->getFirstArg() == 0;
2955   FSI->FormatIdx = Format->getFormatIdx() - 1;
2956   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2957 
2958   // The way the format attribute works in GCC, the implicit this argument
2959   // of member functions is counted. However, it doesn't appear in our own
2960   // lists, so decrement format_idx in that case.
2961   if (IsCXXMember) {
2962     if(FSI->FormatIdx == 0)
2963       return false;
2964     --FSI->FormatIdx;
2965     if (FSI->FirstDataArg != 0)
2966       --FSI->FirstDataArg;
2967   }
2968   return true;
2969 }
2970 
2971 /// Checks if a the given expression evaluates to null.
2972 ///
2973 /// Returns true if the value evaluates to null.
2974 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2975   // If the expression has non-null type, it doesn't evaluate to null.
2976   if (auto nullability
2977         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2978     if (*nullability == NullabilityKind::NonNull)
2979       return false;
2980   }
2981 
2982   // As a special case, transparent unions initialized with zero are
2983   // considered null for the purposes of the nonnull attribute.
2984   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2985     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2986       if (const CompoundLiteralExpr *CLE =
2987           dyn_cast<CompoundLiteralExpr>(Expr))
2988         if (const InitListExpr *ILE =
2989             dyn_cast<InitListExpr>(CLE->getInitializer()))
2990           Expr = ILE->getInit(0);
2991   }
2992 
2993   bool Result;
2994   return (!Expr->isValueDependent() &&
2995           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2996           !Result);
2997 }
2998 
2999 static void CheckNonNullArgument(Sema &S,
3000                                  const Expr *ArgExpr,
3001                                  SourceLocation CallSiteLoc) {
3002   if (CheckNonNullExpr(S, ArgExpr))
3003     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3004            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
3005 }
3006 
3007 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3008   FormatStringInfo FSI;
3009   if ((GetFormatStringType(Format) == FST_NSString) &&
3010       getFormatStringInfo(Format, false, &FSI)) {
3011     Idx = FSI.FormatIdx;
3012     return true;
3013   }
3014   return false;
3015 }
3016 
3017 /// Diagnose use of %s directive in an NSString which is being passed
3018 /// as formatting string to formatting method.
3019 static void
3020 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3021                                         const NamedDecl *FDecl,
3022                                         Expr **Args,
3023                                         unsigned NumArgs) {
3024   unsigned Idx = 0;
3025   bool Format = false;
3026   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3027   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3028     Idx = 2;
3029     Format = true;
3030   }
3031   else
3032     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3033       if (S.GetFormatNSStringIdx(I, Idx)) {
3034         Format = true;
3035         break;
3036       }
3037     }
3038   if (!Format || NumArgs <= Idx)
3039     return;
3040   const Expr *FormatExpr = Args[Idx];
3041   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3042     FormatExpr = CSCE->getSubExpr();
3043   const StringLiteral *FormatString;
3044   if (const ObjCStringLiteral *OSL =
3045       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3046     FormatString = OSL->getString();
3047   else
3048     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3049   if (!FormatString)
3050     return;
3051   if (S.FormatStringHasSArg(FormatString)) {
3052     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3053       << "%s" << 1 << 1;
3054     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3055       << FDecl->getDeclName();
3056   }
3057 }
3058 
3059 /// Determine whether the given type has a non-null nullability annotation.
3060 static bool isNonNullType(ASTContext &ctx, QualType type) {
3061   if (auto nullability = type->getNullability(ctx))
3062     return *nullability == NullabilityKind::NonNull;
3063 
3064   return false;
3065 }
3066 
3067 static void CheckNonNullArguments(Sema &S,
3068                                   const NamedDecl *FDecl,
3069                                   const FunctionProtoType *Proto,
3070                                   ArrayRef<const Expr *> Args,
3071                                   SourceLocation CallSiteLoc) {
3072   assert((FDecl || Proto) && "Need a function declaration or prototype");
3073 
3074   // Check the attributes attached to the method/function itself.
3075   llvm::SmallBitVector NonNullArgs;
3076   if (FDecl) {
3077     // Handle the nonnull attribute on the function/method declaration itself.
3078     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3079       if (!NonNull->args_size()) {
3080         // Easy case: all pointer arguments are nonnull.
3081         for (const auto *Arg : Args)
3082           if (S.isValidPointerAttrType(Arg->getType()))
3083             CheckNonNullArgument(S, Arg, CallSiteLoc);
3084         return;
3085       }
3086 
3087       for (const ParamIdx &Idx : NonNull->args()) {
3088         unsigned IdxAST = Idx.getASTIndex();
3089         if (IdxAST >= Args.size())
3090           continue;
3091         if (NonNullArgs.empty())
3092           NonNullArgs.resize(Args.size());
3093         NonNullArgs.set(IdxAST);
3094       }
3095     }
3096   }
3097 
3098   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3099     // Handle the nonnull attribute on the parameters of the
3100     // function/method.
3101     ArrayRef<ParmVarDecl*> parms;
3102     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3103       parms = FD->parameters();
3104     else
3105       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3106 
3107     unsigned ParamIndex = 0;
3108     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3109          I != E; ++I, ++ParamIndex) {
3110       const ParmVarDecl *PVD = *I;
3111       if (PVD->hasAttr<NonNullAttr>() ||
3112           isNonNullType(S.Context, PVD->getType())) {
3113         if (NonNullArgs.empty())
3114           NonNullArgs.resize(Args.size());
3115 
3116         NonNullArgs.set(ParamIndex);
3117       }
3118     }
3119   } else {
3120     // If we have a non-function, non-method declaration but no
3121     // function prototype, try to dig out the function prototype.
3122     if (!Proto) {
3123       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3124         QualType type = VD->getType().getNonReferenceType();
3125         if (auto pointerType = type->getAs<PointerType>())
3126           type = pointerType->getPointeeType();
3127         else if (auto blockType = type->getAs<BlockPointerType>())
3128           type = blockType->getPointeeType();
3129         // FIXME: data member pointers?
3130 
3131         // Dig out the function prototype, if there is one.
3132         Proto = type->getAs<FunctionProtoType>();
3133       }
3134     }
3135 
3136     // Fill in non-null argument information from the nullability
3137     // information on the parameter types (if we have them).
3138     if (Proto) {
3139       unsigned Index = 0;
3140       for (auto paramType : Proto->getParamTypes()) {
3141         if (isNonNullType(S.Context, paramType)) {
3142           if (NonNullArgs.empty())
3143             NonNullArgs.resize(Args.size());
3144 
3145           NonNullArgs.set(Index);
3146         }
3147 
3148         ++Index;
3149       }
3150     }
3151   }
3152 
3153   // Check for non-null arguments.
3154   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3155        ArgIndex != ArgIndexEnd; ++ArgIndex) {
3156     if (NonNullArgs[ArgIndex])
3157       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
3158   }
3159 }
3160 
3161 /// Handles the checks for format strings, non-POD arguments to vararg
3162 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3163 /// attributes.
3164 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
3165                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
3166                      bool IsMemberFunction, SourceLocation Loc,
3167                      SourceRange Range, VariadicCallType CallType) {
3168   // FIXME: We should check as much as we can in the template definition.
3169   if (CurContext->isDependentContext())
3170     return;
3171 
3172   // Printf and scanf checking.
3173   llvm::SmallBitVector CheckedVarArgs;
3174   if (FDecl) {
3175     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3176       // Only create vector if there are format attributes.
3177       CheckedVarArgs.resize(Args.size());
3178 
3179       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3180                            CheckedVarArgs);
3181     }
3182   }
3183 
3184   // Refuse POD arguments that weren't caught by the format string
3185   // checks above.
3186   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3187   if (CallType != VariadicDoesNotApply &&
3188       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3189     unsigned NumParams = Proto ? Proto->getNumParams()
3190                        : FDecl && isa<FunctionDecl>(FDecl)
3191                            ? cast<FunctionDecl>(FDecl)->getNumParams()
3192                        : FDecl && isa<ObjCMethodDecl>(FDecl)
3193                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
3194                        : 0;
3195 
3196     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3197       // Args[ArgIdx] can be null in malformed code.
3198       if (const Expr *Arg = Args[ArgIdx]) {
3199         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3200           checkVariadicArgument(Arg, CallType);
3201       }
3202     }
3203   }
3204 
3205   if (FDecl || Proto) {
3206     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3207 
3208     // Type safety checking.
3209     if (FDecl) {
3210       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3211         CheckArgumentWithTypeTag(I, Args, Loc);
3212     }
3213   }
3214 
3215   if (FD)
3216     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3217 }
3218 
3219 /// CheckConstructorCall - Check a constructor call for correctness and safety
3220 /// properties not enforced by the C type system.
3221 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3222                                 ArrayRef<const Expr *> Args,
3223                                 const FunctionProtoType *Proto,
3224                                 SourceLocation Loc) {
3225   VariadicCallType CallType =
3226     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3227   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3228             Loc, SourceRange(), CallType);
3229 }
3230 
3231 /// CheckFunctionCall - Check a direct function call for various correctness
3232 /// and safety properties not strictly enforced by the C type system.
3233 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3234                              const FunctionProtoType *Proto) {
3235   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3236                               isa<CXXMethodDecl>(FDecl);
3237   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3238                           IsMemberOperatorCall;
3239   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3240                                                   TheCall->getCallee());
3241   Expr** Args = TheCall->getArgs();
3242   unsigned NumArgs = TheCall->getNumArgs();
3243 
3244   Expr *ImplicitThis = nullptr;
3245   if (IsMemberOperatorCall) {
3246     // If this is a call to a member operator, hide the first argument
3247     // from checkCall.
3248     // FIXME: Our choice of AST representation here is less than ideal.
3249     ImplicitThis = Args[0];
3250     ++Args;
3251     --NumArgs;
3252   } else if (IsMemberFunction)
3253     ImplicitThis =
3254         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3255 
3256   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
3257             IsMemberFunction, TheCall->getRParenLoc(),
3258             TheCall->getCallee()->getSourceRange(), CallType);
3259 
3260   IdentifierInfo *FnInfo = FDecl->getIdentifier();
3261   // None of the checks below are needed for functions that don't have
3262   // simple names (e.g., C++ conversion functions).
3263   if (!FnInfo)
3264     return false;
3265 
3266   CheckAbsoluteValueFunction(TheCall, FDecl);
3267   CheckMaxUnsignedZero(TheCall, FDecl);
3268 
3269   if (getLangOpts().ObjC1)
3270     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
3271 
3272   unsigned CMId = FDecl->getMemoryFunctionKind();
3273   if (CMId == 0)
3274     return false;
3275 
3276   // Handle memory setting and copying functions.
3277   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
3278     CheckStrlcpycatArguments(TheCall, FnInfo);
3279   else if (CMId == Builtin::BIstrncat)
3280     CheckStrncatArguments(TheCall, FnInfo);
3281   else
3282     CheckMemaccessArguments(TheCall, CMId, FnInfo);
3283 
3284   return false;
3285 }
3286 
3287 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
3288                                ArrayRef<const Expr *> Args) {
3289   VariadicCallType CallType =
3290       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
3291 
3292   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3293             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
3294             CallType);
3295 
3296   return false;
3297 }
3298 
3299 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3300                             const FunctionProtoType *Proto) {
3301   QualType Ty;
3302   if (const auto *V = dyn_cast<VarDecl>(NDecl))
3303     Ty = V->getType().getNonReferenceType();
3304   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
3305     Ty = F->getType().getNonReferenceType();
3306   else
3307     return false;
3308 
3309   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3310       !Ty->isFunctionProtoType())
3311     return false;
3312 
3313   VariadicCallType CallType;
3314   if (!Proto || !Proto->isVariadic()) {
3315     CallType = VariadicDoesNotApply;
3316   } else if (Ty->isBlockPointerType()) {
3317     CallType = VariadicBlock;
3318   } else { // Ty->isFunctionPointerType()
3319     CallType = VariadicFunction;
3320   }
3321 
3322   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
3323             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3324             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3325             TheCall->getCallee()->getSourceRange(), CallType);
3326 
3327   return false;
3328 }
3329 
3330 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3331 /// such as function pointers returned from functions.
3332 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
3333   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
3334                                                   TheCall->getCallee());
3335   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
3336             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3337             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3338             TheCall->getCallee()->getSourceRange(), CallType);
3339 
3340   return false;
3341 }
3342 
3343 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
3344   if (!llvm::isValidAtomicOrderingCABI(Ordering))
3345     return false;
3346 
3347   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
3348   switch (Op) {
3349   case AtomicExpr::AO__c11_atomic_init:
3350   case AtomicExpr::AO__opencl_atomic_init:
3351     llvm_unreachable("There is no ordering argument for an init");
3352 
3353   case AtomicExpr::AO__c11_atomic_load:
3354   case AtomicExpr::AO__opencl_atomic_load:
3355   case AtomicExpr::AO__atomic_load_n:
3356   case AtomicExpr::AO__atomic_load:
3357     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3358            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3359 
3360   case AtomicExpr::AO__c11_atomic_store:
3361   case AtomicExpr::AO__opencl_atomic_store:
3362   case AtomicExpr::AO__atomic_store:
3363   case AtomicExpr::AO__atomic_store_n:
3364     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3365            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3366            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3367 
3368   default:
3369     return true;
3370   }
3371 }
3372 
3373 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3374                                          AtomicExpr::AtomicOp Op) {
3375   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3376   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3377 
3378   // All the non-OpenCL operations take one of the following forms.
3379   // The OpenCL operations take the __c11 forms with one extra argument for
3380   // synchronization scope.
3381   enum {
3382     // C    __c11_atomic_init(A *, C)
3383     Init,
3384 
3385     // C    __c11_atomic_load(A *, int)
3386     Load,
3387 
3388     // void __atomic_load(A *, CP, int)
3389     LoadCopy,
3390 
3391     // void __atomic_store(A *, CP, int)
3392     Copy,
3393 
3394     // C    __c11_atomic_add(A *, M, int)
3395     Arithmetic,
3396 
3397     // C    __atomic_exchange_n(A *, CP, int)
3398     Xchg,
3399 
3400     // void __atomic_exchange(A *, C *, CP, int)
3401     GNUXchg,
3402 
3403     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3404     C11CmpXchg,
3405 
3406     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3407     GNUCmpXchg
3408   } Form = Init;
3409 
3410   const unsigned NumForm = GNUCmpXchg + 1;
3411   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3412   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
3413   // where:
3414   //   C is an appropriate type,
3415   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3416   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3417   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3418   //   the int parameters are for orderings.
3419 
3420   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3421       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3422       "need to update code for modified forms");
3423   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3424                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3425                         AtomicExpr::AO__atomic_load,
3426                 "need to update code for modified C11 atomics");
3427   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3428                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3429   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3430                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3431                IsOpenCL;
3432   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3433              Op == AtomicExpr::AO__atomic_store_n ||
3434              Op == AtomicExpr::AO__atomic_exchange_n ||
3435              Op == AtomicExpr::AO__atomic_compare_exchange_n;
3436   bool IsAddSub = false;
3437   bool IsMinMax = false;
3438 
3439   switch (Op) {
3440   case AtomicExpr::AO__c11_atomic_init:
3441   case AtomicExpr::AO__opencl_atomic_init:
3442     Form = Init;
3443     break;
3444 
3445   case AtomicExpr::AO__c11_atomic_load:
3446   case AtomicExpr::AO__opencl_atomic_load:
3447   case AtomicExpr::AO__atomic_load_n:
3448     Form = Load;
3449     break;
3450 
3451   case AtomicExpr::AO__atomic_load:
3452     Form = LoadCopy;
3453     break;
3454 
3455   case AtomicExpr::AO__c11_atomic_store:
3456   case AtomicExpr::AO__opencl_atomic_store:
3457   case AtomicExpr::AO__atomic_store:
3458   case AtomicExpr::AO__atomic_store_n:
3459     Form = Copy;
3460     break;
3461 
3462   case AtomicExpr::AO__c11_atomic_fetch_add:
3463   case AtomicExpr::AO__c11_atomic_fetch_sub:
3464   case AtomicExpr::AO__opencl_atomic_fetch_add:
3465   case AtomicExpr::AO__opencl_atomic_fetch_sub:
3466   case AtomicExpr::AO__opencl_atomic_fetch_min:
3467   case AtomicExpr::AO__opencl_atomic_fetch_max:
3468   case AtomicExpr::AO__atomic_fetch_add:
3469   case AtomicExpr::AO__atomic_fetch_sub:
3470   case AtomicExpr::AO__atomic_add_fetch:
3471   case AtomicExpr::AO__atomic_sub_fetch:
3472     IsAddSub = true;
3473     LLVM_FALLTHROUGH;
3474   case AtomicExpr::AO__c11_atomic_fetch_and:
3475   case AtomicExpr::AO__c11_atomic_fetch_or:
3476   case AtomicExpr::AO__c11_atomic_fetch_xor:
3477   case AtomicExpr::AO__opencl_atomic_fetch_and:
3478   case AtomicExpr::AO__opencl_atomic_fetch_or:
3479   case AtomicExpr::AO__opencl_atomic_fetch_xor:
3480   case AtomicExpr::AO__atomic_fetch_and:
3481   case AtomicExpr::AO__atomic_fetch_or:
3482   case AtomicExpr::AO__atomic_fetch_xor:
3483   case AtomicExpr::AO__atomic_fetch_nand:
3484   case AtomicExpr::AO__atomic_and_fetch:
3485   case AtomicExpr::AO__atomic_or_fetch:
3486   case AtomicExpr::AO__atomic_xor_fetch:
3487   case AtomicExpr::AO__atomic_nand_fetch:
3488     Form = Arithmetic;
3489     break;
3490 
3491   case AtomicExpr::AO__atomic_fetch_min:
3492   case AtomicExpr::AO__atomic_fetch_max:
3493     IsMinMax = true;
3494     Form = Arithmetic;
3495     break;
3496 
3497   case AtomicExpr::AO__c11_atomic_exchange:
3498   case AtomicExpr::AO__opencl_atomic_exchange:
3499   case AtomicExpr::AO__atomic_exchange_n:
3500     Form = Xchg;
3501     break;
3502 
3503   case AtomicExpr::AO__atomic_exchange:
3504     Form = GNUXchg;
3505     break;
3506 
3507   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3508   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3509   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3510   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3511     Form = C11CmpXchg;
3512     break;
3513 
3514   case AtomicExpr::AO__atomic_compare_exchange:
3515   case AtomicExpr::AO__atomic_compare_exchange_n:
3516     Form = GNUCmpXchg;
3517     break;
3518   }
3519 
3520   unsigned AdjustedNumArgs = NumArgs[Form];
3521   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3522     ++AdjustedNumArgs;
3523   // Check we have the right number of arguments.
3524   if (TheCall->getNumArgs() < AdjustedNumArgs) {
3525     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3526       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3527       << TheCall->getCallee()->getSourceRange();
3528     return ExprError();
3529   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3530     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3531          diag::err_typecheck_call_too_many_args)
3532       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3533       << TheCall->getCallee()->getSourceRange();
3534     return ExprError();
3535   }
3536 
3537   // Inspect the first argument of the atomic operation.
3538   Expr *Ptr = TheCall->getArg(0);
3539   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3540   if (ConvertedPtr.isInvalid())
3541     return ExprError();
3542 
3543   Ptr = ConvertedPtr.get();
3544   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3545   if (!pointerType) {
3546     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3547       << Ptr->getType() << Ptr->getSourceRange();
3548     return ExprError();
3549   }
3550 
3551   // For a __c11 builtin, this should be a pointer to an _Atomic type.
3552   QualType AtomTy = pointerType->getPointeeType(); // 'A'
3553   QualType ValType = AtomTy; // 'C'
3554   if (IsC11) {
3555     if (!AtomTy->isAtomicType()) {
3556       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3557         << Ptr->getType() << Ptr->getSourceRange();
3558       return ExprError();
3559     }
3560     if (AtomTy.isConstQualified() ||
3561         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3562       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3563           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3564           << Ptr->getSourceRange();
3565       return ExprError();
3566     }
3567     ValType = AtomTy->getAs<AtomicType>()->getValueType();
3568   } else if (Form != Load && Form != LoadCopy) {
3569     if (ValType.isConstQualified()) {
3570       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3571         << Ptr->getType() << Ptr->getSourceRange();
3572       return ExprError();
3573     }
3574   }
3575 
3576   // For an arithmetic operation, the implied arithmetic must be well-formed.
3577   if (Form == Arithmetic) {
3578     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3579     if (IsAddSub && !ValType->isIntegerType()
3580         && !ValType->isPointerType()) {
3581       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3582         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3583       return ExprError();
3584     }
3585     if (IsMinMax) {
3586       const BuiltinType *BT = ValType->getAs<BuiltinType>();
3587       if (!BT || (BT->getKind() != BuiltinType::Int &&
3588                   BT->getKind() != BuiltinType::UInt)) {
3589         Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3590         return ExprError();
3591       }
3592     }
3593     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
3594       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3595         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3596       return ExprError();
3597     }
3598     if (IsC11 && ValType->isPointerType() &&
3599         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3600                             diag::err_incomplete_type)) {
3601       return ExprError();
3602     }
3603   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3604     // For __atomic_*_n operations, the value type must be a scalar integral or
3605     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3606     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3607       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3608     return ExprError();
3609   }
3610 
3611   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3612       !AtomTy->isScalarType()) {
3613     // For GNU atomics, require a trivially-copyable type. This is not part of
3614     // the GNU atomics specification, but we enforce it for sanity.
3615     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3616       << Ptr->getType() << Ptr->getSourceRange();
3617     return ExprError();
3618   }
3619 
3620   switch (ValType.getObjCLifetime()) {
3621   case Qualifiers::OCL_None:
3622   case Qualifiers::OCL_ExplicitNone:
3623     // okay
3624     break;
3625 
3626   case Qualifiers::OCL_Weak:
3627   case Qualifiers::OCL_Strong:
3628   case Qualifiers::OCL_Autoreleasing:
3629     // FIXME: Can this happen? By this point, ValType should be known
3630     // to be trivially copyable.
3631     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3632       << ValType << Ptr->getSourceRange();
3633     return ExprError();
3634   }
3635 
3636   // All atomic operations have an overload which takes a pointer to a volatile
3637   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
3638   // into the result or the other operands. Similarly atomic_load takes a
3639   // pointer to a const 'A'.
3640   ValType.removeLocalVolatile();
3641   ValType.removeLocalConst();
3642   QualType ResultType = ValType;
3643   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3644       Form == Init)
3645     ResultType = Context.VoidTy;
3646   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3647     ResultType = Context.BoolTy;
3648 
3649   // The type of a parameter passed 'by value'. In the GNU atomics, such
3650   // arguments are actually passed as pointers.
3651   QualType ByValType = ValType; // 'CP'
3652   bool IsPassedByAddress = false;
3653   if (!IsC11 && !IsN) {
3654     ByValType = Ptr->getType();
3655     IsPassedByAddress = true;
3656   }
3657 
3658   // The first argument's non-CV pointer type is used to deduce the type of
3659   // subsequent arguments, except for:
3660   //  - weak flag (always converted to bool)
3661   //  - memory order (always converted to int)
3662   //  - scope  (always converted to int)
3663   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3664     QualType Ty;
3665     if (i < NumVals[Form] + 1) {
3666       switch (i) {
3667       case 0:
3668         // The first argument is always a pointer. It has a fixed type.
3669         // It is always dereferenced, a nullptr is undefined.
3670         CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3671         // Nothing else to do: we already know all we want about this pointer.
3672         continue;
3673       case 1:
3674         // The second argument is the non-atomic operand. For arithmetic, this
3675         // is always passed by value, and for a compare_exchange it is always
3676         // passed by address. For the rest, GNU uses by-address and C11 uses
3677         // by-value.
3678         assert(Form != Load);
3679         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3680           Ty = ValType;
3681         else if (Form == Copy || Form == Xchg) {
3682           if (IsPassedByAddress)
3683             // The value pointer is always dereferenced, a nullptr is undefined.
3684             CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3685           Ty = ByValType;
3686         } else if (Form == Arithmetic)
3687           Ty = Context.getPointerDiffType();
3688         else {
3689           Expr *ValArg = TheCall->getArg(i);
3690           // The value pointer is always dereferenced, a nullptr is undefined.
3691           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3692           LangAS AS = LangAS::Default;
3693           // Keep address space of non-atomic pointer type.
3694           if (const PointerType *PtrTy =
3695                   ValArg->getType()->getAs<PointerType>()) {
3696             AS = PtrTy->getPointeeType().getAddressSpace();
3697           }
3698           Ty = Context.getPointerType(
3699               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3700         }
3701         break;
3702       case 2:
3703         // The third argument to compare_exchange / GNU exchange is the desired
3704         // value, either by-value (for the C11 and *_n variant) or as a pointer.
3705         if (IsPassedByAddress)
3706           CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3707         Ty = ByValType;
3708         break;
3709       case 3:
3710         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3711         Ty = Context.BoolTy;
3712         break;
3713       }
3714     } else {
3715       // The order(s) and scope are always converted to int.
3716       Ty = Context.IntTy;
3717     }
3718 
3719     InitializedEntity Entity =
3720         InitializedEntity::InitializeParameter(Context, Ty, false);
3721     ExprResult Arg = TheCall->getArg(i);
3722     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3723     if (Arg.isInvalid())
3724       return true;
3725     TheCall->setArg(i, Arg.get());
3726   }
3727 
3728   // Permute the arguments into a 'consistent' order.
3729   SmallVector<Expr*, 5> SubExprs;
3730   SubExprs.push_back(Ptr);
3731   switch (Form) {
3732   case Init:
3733     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3734     SubExprs.push_back(TheCall->getArg(1)); // Val1
3735     break;
3736   case Load:
3737     SubExprs.push_back(TheCall->getArg(1)); // Order
3738     break;
3739   case LoadCopy:
3740   case Copy:
3741   case Arithmetic:
3742   case Xchg:
3743     SubExprs.push_back(TheCall->getArg(2)); // Order
3744     SubExprs.push_back(TheCall->getArg(1)); // Val1
3745     break;
3746   case GNUXchg:
3747     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3748     SubExprs.push_back(TheCall->getArg(3)); // Order
3749     SubExprs.push_back(TheCall->getArg(1)); // Val1
3750     SubExprs.push_back(TheCall->getArg(2)); // Val2
3751     break;
3752   case C11CmpXchg:
3753     SubExprs.push_back(TheCall->getArg(3)); // Order
3754     SubExprs.push_back(TheCall->getArg(1)); // Val1
3755     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3756     SubExprs.push_back(TheCall->getArg(2)); // Val2
3757     break;
3758   case GNUCmpXchg:
3759     SubExprs.push_back(TheCall->getArg(4)); // Order
3760     SubExprs.push_back(TheCall->getArg(1)); // Val1
3761     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3762     SubExprs.push_back(TheCall->getArg(2)); // Val2
3763     SubExprs.push_back(TheCall->getArg(3)); // Weak
3764     break;
3765   }
3766 
3767   if (SubExprs.size() >= 2 && Form != Init) {
3768     llvm::APSInt Result(32);
3769     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3770         !isValidOrderingForOp(Result.getSExtValue(), Op))
3771       Diag(SubExprs[1]->getLocStart(),
3772            diag::warn_atomic_op_has_invalid_memory_order)
3773           << SubExprs[1]->getSourceRange();
3774   }
3775 
3776   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3777     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3778     llvm::APSInt Result(32);
3779     if (Scope->isIntegerConstantExpr(Result, Context) &&
3780         !ScopeModel->isValid(Result.getZExtValue())) {
3781       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3782           << Scope->getSourceRange();
3783     }
3784     SubExprs.push_back(Scope);
3785   }
3786 
3787   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3788                                             SubExprs, ResultType, Op,
3789                                             TheCall->getRParenLoc());
3790 
3791   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3792        Op == AtomicExpr::AO__c11_atomic_store ||
3793        Op == AtomicExpr::AO__opencl_atomic_load ||
3794        Op == AtomicExpr::AO__opencl_atomic_store ) &&
3795       Context.AtomicUsesUnsupportedLibcall(AE))
3796     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3797         << ((Op == AtomicExpr::AO__c11_atomic_load ||
3798             Op == AtomicExpr::AO__opencl_atomic_load)
3799                 ? 0 : 1);
3800 
3801   return AE;
3802 }
3803 
3804 /// checkBuiltinArgument - Given a call to a builtin function, perform
3805 /// normal type-checking on the given argument, updating the call in
3806 /// place.  This is useful when a builtin function requires custom
3807 /// type-checking for some of its arguments but not necessarily all of
3808 /// them.
3809 ///
3810 /// Returns true on error.
3811 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3812   FunctionDecl *Fn = E->getDirectCallee();
3813   assert(Fn && "builtin call without direct callee!");
3814 
3815   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3816   InitializedEntity Entity =
3817     InitializedEntity::InitializeParameter(S.Context, Param);
3818 
3819   ExprResult Arg = E->getArg(0);
3820   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3821   if (Arg.isInvalid())
3822     return true;
3823 
3824   E->setArg(ArgIndex, Arg.get());
3825   return false;
3826 }
3827 
3828 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3829 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3830 /// type of its first argument.  The main ActOnCallExpr routines have already
3831 /// promoted the types of arguments because all of these calls are prototyped as
3832 /// void(...).
3833 ///
3834 /// This function goes through and does final semantic checking for these
3835 /// builtins,
3836 ExprResult
3837 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3838   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3839   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3840   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3841 
3842   // Ensure that we have at least one argument to do type inference from.
3843   if (TheCall->getNumArgs() < 1) {
3844     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3845       << 0 << 1 << TheCall->getNumArgs()
3846       << TheCall->getCallee()->getSourceRange();
3847     return ExprError();
3848   }
3849 
3850   // Inspect the first argument of the atomic builtin.  This should always be
3851   // a pointer type, whose element is an integral scalar or pointer type.
3852   // Because it is a pointer type, we don't have to worry about any implicit
3853   // casts here.
3854   // FIXME: We don't allow floating point scalars as input.
3855   Expr *FirstArg = TheCall->getArg(0);
3856   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3857   if (FirstArgResult.isInvalid())
3858     return ExprError();
3859   FirstArg = FirstArgResult.get();
3860   TheCall->setArg(0, FirstArg);
3861 
3862   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3863   if (!pointerType) {
3864     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3865       << FirstArg->getType() << FirstArg->getSourceRange();
3866     return ExprError();
3867   }
3868 
3869   QualType ValType = pointerType->getPointeeType();
3870   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3871       !ValType->isBlockPointerType()) {
3872     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3873       << FirstArg->getType() << FirstArg->getSourceRange();
3874     return ExprError();
3875   }
3876 
3877   if (ValType.isConstQualified()) {
3878     Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3879         << FirstArg->getType() << FirstArg->getSourceRange();
3880     return ExprError();
3881   }
3882 
3883   switch (ValType.getObjCLifetime()) {
3884   case Qualifiers::OCL_None:
3885   case Qualifiers::OCL_ExplicitNone:
3886     // okay
3887     break;
3888 
3889   case Qualifiers::OCL_Weak:
3890   case Qualifiers::OCL_Strong:
3891   case Qualifiers::OCL_Autoreleasing:
3892     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3893       << ValType << FirstArg->getSourceRange();
3894     return ExprError();
3895   }
3896 
3897   // Strip any qualifiers off ValType.
3898   ValType = ValType.getUnqualifiedType();
3899 
3900   // The majority of builtins return a value, but a few have special return
3901   // types, so allow them to override appropriately below.
3902   QualType ResultType = ValType;
3903 
3904   // We need to figure out which concrete builtin this maps onto.  For example,
3905   // __sync_fetch_and_add with a 2 byte object turns into
3906   // __sync_fetch_and_add_2.
3907 #define BUILTIN_ROW(x) \
3908   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3909     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3910 
3911   static const unsigned BuiltinIndices[][5] = {
3912     BUILTIN_ROW(__sync_fetch_and_add),
3913     BUILTIN_ROW(__sync_fetch_and_sub),
3914     BUILTIN_ROW(__sync_fetch_and_or),
3915     BUILTIN_ROW(__sync_fetch_and_and),
3916     BUILTIN_ROW(__sync_fetch_and_xor),
3917     BUILTIN_ROW(__sync_fetch_and_nand),
3918 
3919     BUILTIN_ROW(__sync_add_and_fetch),
3920     BUILTIN_ROW(__sync_sub_and_fetch),
3921     BUILTIN_ROW(__sync_and_and_fetch),
3922     BUILTIN_ROW(__sync_or_and_fetch),
3923     BUILTIN_ROW(__sync_xor_and_fetch),
3924     BUILTIN_ROW(__sync_nand_and_fetch),
3925 
3926     BUILTIN_ROW(__sync_val_compare_and_swap),
3927     BUILTIN_ROW(__sync_bool_compare_and_swap),
3928     BUILTIN_ROW(__sync_lock_test_and_set),
3929     BUILTIN_ROW(__sync_lock_release),
3930     BUILTIN_ROW(__sync_swap)
3931   };
3932 #undef BUILTIN_ROW
3933 
3934   // Determine the index of the size.
3935   unsigned SizeIndex;
3936   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3937   case 1: SizeIndex = 0; break;
3938   case 2: SizeIndex = 1; break;
3939   case 4: SizeIndex = 2; break;
3940   case 8: SizeIndex = 3; break;
3941   case 16: SizeIndex = 4; break;
3942   default:
3943     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3944       << FirstArg->getType() << FirstArg->getSourceRange();
3945     return ExprError();
3946   }
3947 
3948   // Each of these builtins has one pointer argument, followed by some number of
3949   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3950   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3951   // as the number of fixed args.
3952   unsigned BuiltinID = FDecl->getBuiltinID();
3953   unsigned BuiltinIndex, NumFixed = 1;
3954   bool WarnAboutSemanticsChange = false;
3955   switch (BuiltinID) {
3956   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3957   case Builtin::BI__sync_fetch_and_add:
3958   case Builtin::BI__sync_fetch_and_add_1:
3959   case Builtin::BI__sync_fetch_and_add_2:
3960   case Builtin::BI__sync_fetch_and_add_4:
3961   case Builtin::BI__sync_fetch_and_add_8:
3962   case Builtin::BI__sync_fetch_and_add_16:
3963     BuiltinIndex = 0;
3964     break;
3965 
3966   case Builtin::BI__sync_fetch_and_sub:
3967   case Builtin::BI__sync_fetch_and_sub_1:
3968   case Builtin::BI__sync_fetch_and_sub_2:
3969   case Builtin::BI__sync_fetch_and_sub_4:
3970   case Builtin::BI__sync_fetch_and_sub_8:
3971   case Builtin::BI__sync_fetch_and_sub_16:
3972     BuiltinIndex = 1;
3973     break;
3974 
3975   case Builtin::BI__sync_fetch_and_or:
3976   case Builtin::BI__sync_fetch_and_or_1:
3977   case Builtin::BI__sync_fetch_and_or_2:
3978   case Builtin::BI__sync_fetch_and_or_4:
3979   case Builtin::BI__sync_fetch_and_or_8:
3980   case Builtin::BI__sync_fetch_and_or_16:
3981     BuiltinIndex = 2;
3982     break;
3983 
3984   case Builtin::BI__sync_fetch_and_and:
3985   case Builtin::BI__sync_fetch_and_and_1:
3986   case Builtin::BI__sync_fetch_and_and_2:
3987   case Builtin::BI__sync_fetch_and_and_4:
3988   case Builtin::BI__sync_fetch_and_and_8:
3989   case Builtin::BI__sync_fetch_and_and_16:
3990     BuiltinIndex = 3;
3991     break;
3992 
3993   case Builtin::BI__sync_fetch_and_xor:
3994   case Builtin::BI__sync_fetch_and_xor_1:
3995   case Builtin::BI__sync_fetch_and_xor_2:
3996   case Builtin::BI__sync_fetch_and_xor_4:
3997   case Builtin::BI__sync_fetch_and_xor_8:
3998   case Builtin::BI__sync_fetch_and_xor_16:
3999     BuiltinIndex = 4;
4000     break;
4001 
4002   case Builtin::BI__sync_fetch_and_nand:
4003   case Builtin::BI__sync_fetch_and_nand_1:
4004   case Builtin::BI__sync_fetch_and_nand_2:
4005   case Builtin::BI__sync_fetch_and_nand_4:
4006   case Builtin::BI__sync_fetch_and_nand_8:
4007   case Builtin::BI__sync_fetch_and_nand_16:
4008     BuiltinIndex = 5;
4009     WarnAboutSemanticsChange = true;
4010     break;
4011 
4012   case Builtin::BI__sync_add_and_fetch:
4013   case Builtin::BI__sync_add_and_fetch_1:
4014   case Builtin::BI__sync_add_and_fetch_2:
4015   case Builtin::BI__sync_add_and_fetch_4:
4016   case Builtin::BI__sync_add_and_fetch_8:
4017   case Builtin::BI__sync_add_and_fetch_16:
4018     BuiltinIndex = 6;
4019     break;
4020 
4021   case Builtin::BI__sync_sub_and_fetch:
4022   case Builtin::BI__sync_sub_and_fetch_1:
4023   case Builtin::BI__sync_sub_and_fetch_2:
4024   case Builtin::BI__sync_sub_and_fetch_4:
4025   case Builtin::BI__sync_sub_and_fetch_8:
4026   case Builtin::BI__sync_sub_and_fetch_16:
4027     BuiltinIndex = 7;
4028     break;
4029 
4030   case Builtin::BI__sync_and_and_fetch:
4031   case Builtin::BI__sync_and_and_fetch_1:
4032   case Builtin::BI__sync_and_and_fetch_2:
4033   case Builtin::BI__sync_and_and_fetch_4:
4034   case Builtin::BI__sync_and_and_fetch_8:
4035   case Builtin::BI__sync_and_and_fetch_16:
4036     BuiltinIndex = 8;
4037     break;
4038 
4039   case Builtin::BI__sync_or_and_fetch:
4040   case Builtin::BI__sync_or_and_fetch_1:
4041   case Builtin::BI__sync_or_and_fetch_2:
4042   case Builtin::BI__sync_or_and_fetch_4:
4043   case Builtin::BI__sync_or_and_fetch_8:
4044   case Builtin::BI__sync_or_and_fetch_16:
4045     BuiltinIndex = 9;
4046     break;
4047 
4048   case Builtin::BI__sync_xor_and_fetch:
4049   case Builtin::BI__sync_xor_and_fetch_1:
4050   case Builtin::BI__sync_xor_and_fetch_2:
4051   case Builtin::BI__sync_xor_and_fetch_4:
4052   case Builtin::BI__sync_xor_and_fetch_8:
4053   case Builtin::BI__sync_xor_and_fetch_16:
4054     BuiltinIndex = 10;
4055     break;
4056 
4057   case Builtin::BI__sync_nand_and_fetch:
4058   case Builtin::BI__sync_nand_and_fetch_1:
4059   case Builtin::BI__sync_nand_and_fetch_2:
4060   case Builtin::BI__sync_nand_and_fetch_4:
4061   case Builtin::BI__sync_nand_and_fetch_8:
4062   case Builtin::BI__sync_nand_and_fetch_16:
4063     BuiltinIndex = 11;
4064     WarnAboutSemanticsChange = true;
4065     break;
4066 
4067   case Builtin::BI__sync_val_compare_and_swap:
4068   case Builtin::BI__sync_val_compare_and_swap_1:
4069   case Builtin::BI__sync_val_compare_and_swap_2:
4070   case Builtin::BI__sync_val_compare_and_swap_4:
4071   case Builtin::BI__sync_val_compare_and_swap_8:
4072   case Builtin::BI__sync_val_compare_and_swap_16:
4073     BuiltinIndex = 12;
4074     NumFixed = 2;
4075     break;
4076 
4077   case Builtin::BI__sync_bool_compare_and_swap:
4078   case Builtin::BI__sync_bool_compare_and_swap_1:
4079   case Builtin::BI__sync_bool_compare_and_swap_2:
4080   case Builtin::BI__sync_bool_compare_and_swap_4:
4081   case Builtin::BI__sync_bool_compare_and_swap_8:
4082   case Builtin::BI__sync_bool_compare_and_swap_16:
4083     BuiltinIndex = 13;
4084     NumFixed = 2;
4085     ResultType = Context.BoolTy;
4086     break;
4087 
4088   case Builtin::BI__sync_lock_test_and_set:
4089   case Builtin::BI__sync_lock_test_and_set_1:
4090   case Builtin::BI__sync_lock_test_and_set_2:
4091   case Builtin::BI__sync_lock_test_and_set_4:
4092   case Builtin::BI__sync_lock_test_and_set_8:
4093   case Builtin::BI__sync_lock_test_and_set_16:
4094     BuiltinIndex = 14;
4095     break;
4096 
4097   case Builtin::BI__sync_lock_release:
4098   case Builtin::BI__sync_lock_release_1:
4099   case Builtin::BI__sync_lock_release_2:
4100   case Builtin::BI__sync_lock_release_4:
4101   case Builtin::BI__sync_lock_release_8:
4102   case Builtin::BI__sync_lock_release_16:
4103     BuiltinIndex = 15;
4104     NumFixed = 0;
4105     ResultType = Context.VoidTy;
4106     break;
4107 
4108   case Builtin::BI__sync_swap:
4109   case Builtin::BI__sync_swap_1:
4110   case Builtin::BI__sync_swap_2:
4111   case Builtin::BI__sync_swap_4:
4112   case Builtin::BI__sync_swap_8:
4113   case Builtin::BI__sync_swap_16:
4114     BuiltinIndex = 16;
4115     break;
4116   }
4117 
4118   // Now that we know how many fixed arguments we expect, first check that we
4119   // have at least that many.
4120   if (TheCall->getNumArgs() < 1+NumFixed) {
4121     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
4122       << 0 << 1+NumFixed << TheCall->getNumArgs()
4123       << TheCall->getCallee()->getSourceRange();
4124     return ExprError();
4125   }
4126 
4127   if (WarnAboutSemanticsChange) {
4128     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
4129       << TheCall->getCallee()->getSourceRange();
4130   }
4131 
4132   // Get the decl for the concrete builtin from this, we can tell what the
4133   // concrete integer type we should convert to is.
4134   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
4135   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
4136   FunctionDecl *NewBuiltinDecl;
4137   if (NewBuiltinID == BuiltinID)
4138     NewBuiltinDecl = FDecl;
4139   else {
4140     // Perform builtin lookup to avoid redeclaring it.
4141     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4142     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
4143     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4144     assert(Res.getFoundDecl());
4145     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
4146     if (!NewBuiltinDecl)
4147       return ExprError();
4148   }
4149 
4150   // The first argument --- the pointer --- has a fixed type; we
4151   // deduce the types of the rest of the arguments accordingly.  Walk
4152   // the remaining arguments, converting them to the deduced value type.
4153   for (unsigned i = 0; i != NumFixed; ++i) {
4154     ExprResult Arg = TheCall->getArg(i+1);
4155 
4156     // GCC does an implicit conversion to the pointer or integer ValType.  This
4157     // can fail in some cases (1i -> int**), check for this error case now.
4158     // Initialize the argument.
4159     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4160                                                    ValType, /*consume*/ false);
4161     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4162     if (Arg.isInvalid())
4163       return ExprError();
4164 
4165     // Okay, we have something that *can* be converted to the right type.  Check
4166     // to see if there is a potentially weird extension going on here.  This can
4167     // happen when you do an atomic operation on something like an char* and
4168     // pass in 42.  The 42 gets converted to char.  This is even more strange
4169     // for things like 45.123 -> char, etc.
4170     // FIXME: Do this check.
4171     TheCall->setArg(i+1, Arg.get());
4172   }
4173 
4174   ASTContext& Context = this->getASTContext();
4175 
4176   // Create a new DeclRefExpr to refer to the new decl.
4177   DeclRefExpr* NewDRE = DeclRefExpr::Create(
4178       Context,
4179       DRE->getQualifierLoc(),
4180       SourceLocation(),
4181       NewBuiltinDecl,
4182       /*enclosing*/ false,
4183       DRE->getLocation(),
4184       Context.BuiltinFnTy,
4185       DRE->getValueKind());
4186 
4187   // Set the callee in the CallExpr.
4188   // FIXME: This loses syntactic information.
4189   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4190   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4191                                               CK_BuiltinFnToFnPtr);
4192   TheCall->setCallee(PromotedCall.get());
4193 
4194   // Change the result type of the call to match the original value type. This
4195   // is arbitrary, but the codegen for these builtins ins design to handle it
4196   // gracefully.
4197   TheCall->setType(ResultType);
4198 
4199   return TheCallResult;
4200 }
4201 
4202 /// SemaBuiltinNontemporalOverloaded - We have a call to
4203 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4204 /// overloaded function based on the pointer type of its last argument.
4205 ///
4206 /// This function goes through and does final semantic checking for these
4207 /// builtins.
4208 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4209   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4210   DeclRefExpr *DRE =
4211       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4212   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4213   unsigned BuiltinID = FDecl->getBuiltinID();
4214   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4215           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4216          "Unexpected nontemporal load/store builtin!");
4217   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4218   unsigned numArgs = isStore ? 2 : 1;
4219 
4220   // Ensure that we have the proper number of arguments.
4221   if (checkArgCount(*this, TheCall, numArgs))
4222     return ExprError();
4223 
4224   // Inspect the last argument of the nontemporal builtin.  This should always
4225   // be a pointer type, from which we imply the type of the memory access.
4226   // Because it is a pointer type, we don't have to worry about any implicit
4227   // casts here.
4228   Expr *PointerArg = TheCall->getArg(numArgs - 1);
4229   ExprResult PointerArgResult =
4230       DefaultFunctionArrayLvalueConversion(PointerArg);
4231 
4232   if (PointerArgResult.isInvalid())
4233     return ExprError();
4234   PointerArg = PointerArgResult.get();
4235   TheCall->setArg(numArgs - 1, PointerArg);
4236 
4237   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4238   if (!pointerType) {
4239     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4240         << PointerArg->getType() << PointerArg->getSourceRange();
4241     return ExprError();
4242   }
4243 
4244   QualType ValType = pointerType->getPointeeType();
4245 
4246   // Strip any qualifiers off ValType.
4247   ValType = ValType.getUnqualifiedType();
4248   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4249       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4250       !ValType->isVectorType()) {
4251     Diag(DRE->getLocStart(),
4252          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4253         << PointerArg->getType() << PointerArg->getSourceRange();
4254     return ExprError();
4255   }
4256 
4257   if (!isStore) {
4258     TheCall->setType(ValType);
4259     return TheCallResult;
4260   }
4261 
4262   ExprResult ValArg = TheCall->getArg(0);
4263   InitializedEntity Entity = InitializedEntity::InitializeParameter(
4264       Context, ValType, /*consume*/ false);
4265   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4266   if (ValArg.isInvalid())
4267     return ExprError();
4268 
4269   TheCall->setArg(0, ValArg.get());
4270   TheCall->setType(Context.VoidTy);
4271   return TheCallResult;
4272 }
4273 
4274 /// CheckObjCString - Checks that the argument to the builtin
4275 /// CFString constructor is correct
4276 /// Note: It might also make sense to do the UTF-16 conversion here (would
4277 /// simplify the backend).
4278 bool Sema::CheckObjCString(Expr *Arg) {
4279   Arg = Arg->IgnoreParenCasts();
4280   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4281 
4282   if (!Literal || !Literal->isAscii()) {
4283     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4284       << Arg->getSourceRange();
4285     return true;
4286   }
4287 
4288   if (Literal->containsNonAsciiOrNull()) {
4289     StringRef String = Literal->getString();
4290     unsigned NumBytes = String.size();
4291     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4292     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4293     llvm::UTF16 *ToPtr = &ToBuf[0];
4294 
4295     llvm::ConversionResult Result =
4296         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4297                                  ToPtr + NumBytes, llvm::strictConversion);
4298     // Check for conversion failure.
4299     if (Result != llvm::conversionOK)
4300       Diag(Arg->getLocStart(),
4301            diag::warn_cfstring_truncated) << Arg->getSourceRange();
4302   }
4303   return false;
4304 }
4305 
4306 /// CheckObjCString - Checks that the format string argument to the os_log()
4307 /// and os_trace() functions is correct, and converts it to const char *.
4308 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4309   Arg = Arg->IgnoreParenCasts();
4310   auto *Literal = dyn_cast<StringLiteral>(Arg);
4311   if (!Literal) {
4312     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4313       Literal = ObjcLiteral->getString();
4314     }
4315   }
4316 
4317   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4318     return ExprError(
4319         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4320         << Arg->getSourceRange());
4321   }
4322 
4323   ExprResult Result(Literal);
4324   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4325   InitializedEntity Entity =
4326       InitializedEntity::InitializeParameter(Context, ResultTy, false);
4327   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4328   return Result;
4329 }
4330 
4331 /// Check that the user is calling the appropriate va_start builtin for the
4332 /// target and calling convention.
4333 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4334   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4335   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
4336   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
4337   bool IsWindows = TT.isOSWindows();
4338   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4339   if (IsX64 || IsAArch64) {
4340     CallingConv CC = CC_C;
4341     if (const FunctionDecl *FD = S.getCurFunctionDecl())
4342       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4343     if (IsMSVAStart) {
4344       // Don't allow this in System V ABI functions.
4345       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
4346         return S.Diag(Fn->getLocStart(),
4347                       diag::err_ms_va_start_used_in_sysv_function);
4348     } else {
4349       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
4350       // On x64 Windows, don't allow this in System V ABI functions.
4351       // (Yes, that means there's no corresponding way to support variadic
4352       // System V ABI functions on Windows.)
4353       if ((IsWindows && CC == CC_X86_64SysV) ||
4354           (!IsWindows && CC == CC_Win64))
4355         return S.Diag(Fn->getLocStart(),
4356                       diag::err_va_start_used_in_wrong_abi_function)
4357                << !IsWindows;
4358     }
4359     return false;
4360   }
4361 
4362   if (IsMSVAStart)
4363     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
4364   return false;
4365 }
4366 
4367 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4368                                              ParmVarDecl **LastParam = nullptr) {
4369   // Determine whether the current function, block, or obj-c method is variadic
4370   // and get its parameter list.
4371   bool IsVariadic = false;
4372   ArrayRef<ParmVarDecl *> Params;
4373   DeclContext *Caller = S.CurContext;
4374   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4375     IsVariadic = Block->isVariadic();
4376     Params = Block->parameters();
4377   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
4378     IsVariadic = FD->isVariadic();
4379     Params = FD->parameters();
4380   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
4381     IsVariadic = MD->isVariadic();
4382     // FIXME: This isn't correct for methods (results in bogus warning).
4383     Params = MD->parameters();
4384   } else if (isa<CapturedDecl>(Caller)) {
4385     // We don't support va_start in a CapturedDecl.
4386     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4387     return true;
4388   } else {
4389     // This must be some other declcontext that parses exprs.
4390     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4391     return true;
4392   }
4393 
4394   if (!IsVariadic) {
4395     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
4396     return true;
4397   }
4398 
4399   if (LastParam)
4400     *LastParam = Params.empty() ? nullptr : Params.back();
4401 
4402   return false;
4403 }
4404 
4405 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4406 /// for validity.  Emit an error and return true on failure; return false
4407 /// on success.
4408 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
4409   Expr *Fn = TheCall->getCallee();
4410 
4411   if (checkVAStartABI(*this, BuiltinID, Fn))
4412     return true;
4413 
4414   if (TheCall->getNumArgs() > 2) {
4415     Diag(TheCall->getArg(2)->getLocStart(),
4416          diag::err_typecheck_call_too_many_args)
4417       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4418       << Fn->getSourceRange()
4419       << SourceRange(TheCall->getArg(2)->getLocStart(),
4420                      (*(TheCall->arg_end()-1))->getLocEnd());
4421     return true;
4422   }
4423 
4424   if (TheCall->getNumArgs() < 2) {
4425     return Diag(TheCall->getLocEnd(),
4426       diag::err_typecheck_call_too_few_args_at_least)
4427       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
4428   }
4429 
4430   // Type-check the first argument normally.
4431   if (checkBuiltinArgument(*this, TheCall, 0))
4432     return true;
4433 
4434   // Check that the current function is variadic, and get its last parameter.
4435   ParmVarDecl *LastParam;
4436   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
4437     return true;
4438 
4439   // Verify that the second argument to the builtin is the last argument of the
4440   // current function or method.
4441   bool SecondArgIsLastNamedArgument = false;
4442   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
4443 
4444   // These are valid if SecondArgIsLastNamedArgument is false after the next
4445   // block.
4446   QualType Type;
4447   SourceLocation ParamLoc;
4448   bool IsCRegister = false;
4449 
4450   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4451     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
4452       SecondArgIsLastNamedArgument = PV == LastParam;
4453 
4454       Type = PV->getType();
4455       ParamLoc = PV->getLocation();
4456       IsCRegister =
4457           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
4458     }
4459   }
4460 
4461   if (!SecondArgIsLastNamedArgument)
4462     Diag(TheCall->getArg(1)->getLocStart(),
4463          diag::warn_second_arg_of_va_start_not_last_named_param);
4464   else if (IsCRegister || Type->isReferenceType() ||
4465            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4466              // Promotable integers are UB, but enumerations need a bit of
4467              // extra checking to see what their promotable type actually is.
4468              if (!Type->isPromotableIntegerType())
4469                return false;
4470              if (!Type->isEnumeralType())
4471                return true;
4472              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4473              return !(ED &&
4474                       Context.typesAreCompatible(ED->getPromotionType(), Type));
4475            }()) {
4476     unsigned Reason = 0;
4477     if (Type->isReferenceType())  Reason = 1;
4478     else if (IsCRegister)         Reason = 2;
4479     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
4480     Diag(ParamLoc, diag::note_parameter_type) << Type;
4481   }
4482 
4483   TheCall->setType(Context.VoidTy);
4484   return false;
4485 }
4486 
4487 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
4488   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4489   //                 const char *named_addr);
4490 
4491   Expr *Func = Call->getCallee();
4492 
4493   if (Call->getNumArgs() < 3)
4494     return Diag(Call->getLocEnd(),
4495                 diag::err_typecheck_call_too_few_args_at_least)
4496            << 0 /*function call*/ << 3 << Call->getNumArgs();
4497 
4498   // Type-check the first argument normally.
4499   if (checkBuiltinArgument(*this, Call, 0))
4500     return true;
4501 
4502   // Check that the current function is variadic.
4503   if (checkVAStartIsInVariadicFunction(*this, Func))
4504     return true;
4505 
4506   // __va_start on Windows does not validate the parameter qualifiers
4507 
4508   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4509   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4510 
4511   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4512   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4513 
4514   const QualType &ConstCharPtrTy =
4515       Context.getPointerType(Context.CharTy.withConst());
4516   if (!Arg1Ty->isPointerType() ||
4517       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4518     Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4519         << Arg1->getType() << ConstCharPtrTy
4520         << 1 /* different class */
4521         << 0 /* qualifier difference */
4522         << 3 /* parameter mismatch */
4523         << 2 << Arg1->getType() << ConstCharPtrTy;
4524 
4525   const QualType SizeTy = Context.getSizeType();
4526   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4527     Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4528         << Arg2->getType() << SizeTy
4529         << 1 /* different class */
4530         << 0 /* qualifier difference */
4531         << 3 /* parameter mismatch */
4532         << 3 << Arg2->getType() << SizeTy;
4533 
4534   return false;
4535 }
4536 
4537 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4538 /// friends.  This is declared to take (...), so we have to check everything.
4539 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4540   if (TheCall->getNumArgs() < 2)
4541     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4542       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4543   if (TheCall->getNumArgs() > 2)
4544     return Diag(TheCall->getArg(2)->getLocStart(),
4545                 diag::err_typecheck_call_too_many_args)
4546       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4547       << SourceRange(TheCall->getArg(2)->getLocStart(),
4548                      (*(TheCall->arg_end()-1))->getLocEnd());
4549 
4550   ExprResult OrigArg0 = TheCall->getArg(0);
4551   ExprResult OrigArg1 = TheCall->getArg(1);
4552 
4553   // Do standard promotions between the two arguments, returning their common
4554   // type.
4555   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4556   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4557     return true;
4558 
4559   // Make sure any conversions are pushed back into the call; this is
4560   // type safe since unordered compare builtins are declared as "_Bool
4561   // foo(...)".
4562   TheCall->setArg(0, OrigArg0.get());
4563   TheCall->setArg(1, OrigArg1.get());
4564 
4565   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4566     return false;
4567 
4568   // If the common type isn't a real floating type, then the arguments were
4569   // invalid for this operation.
4570   if (Res.isNull() || !Res->isRealFloatingType())
4571     return Diag(OrigArg0.get()->getLocStart(),
4572                 diag::err_typecheck_call_invalid_ordered_compare)
4573       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4574       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4575 
4576   return false;
4577 }
4578 
4579 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4580 /// __builtin_isnan and friends.  This is declared to take (...), so we have
4581 /// to check everything. We expect the last argument to be a floating point
4582 /// value.
4583 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4584   if (TheCall->getNumArgs() < NumArgs)
4585     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4586       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4587   if (TheCall->getNumArgs() > NumArgs)
4588     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4589                 diag::err_typecheck_call_too_many_args)
4590       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4591       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4592                      (*(TheCall->arg_end()-1))->getLocEnd());
4593 
4594   Expr *OrigArg = TheCall->getArg(NumArgs-1);
4595 
4596   if (OrigArg->isTypeDependent())
4597     return false;
4598 
4599   // This operation requires a non-_Complex floating-point number.
4600   if (!OrigArg->getType()->isRealFloatingType())
4601     return Diag(OrigArg->getLocStart(),
4602                 diag::err_typecheck_call_invalid_unary_fp)
4603       << OrigArg->getType() << OrigArg->getSourceRange();
4604 
4605   // If this is an implicit conversion from float -> float, double, or
4606   // long double, remove it.
4607   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4608     // Only remove standard FloatCasts, leaving other casts inplace
4609     if (Cast->getCastKind() == CK_FloatingCast) {
4610       Expr *CastArg = Cast->getSubExpr();
4611       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4612         assert(
4613             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4614              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
4615              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
4616             "promotion from float to either float, double, or long double is "
4617             "the only expected cast here");
4618         Cast->setSubExpr(nullptr);
4619         TheCall->setArg(NumArgs-1, CastArg);
4620       }
4621     }
4622   }
4623 
4624   return false;
4625 }
4626 
4627 // Customized Sema Checking for VSX builtins that have the following signature:
4628 // vector [...] builtinName(vector [...], vector [...], const int);
4629 // Which takes the same type of vectors (any legal vector type) for the first
4630 // two arguments and takes compile time constant for the third argument.
4631 // Example builtins are :
4632 // vector double vec_xxpermdi(vector double, vector double, int);
4633 // vector short vec_xxsldwi(vector short, vector short, int);
4634 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4635   unsigned ExpectedNumArgs = 3;
4636   if (TheCall->getNumArgs() < ExpectedNumArgs)
4637     return Diag(TheCall->getLocEnd(),
4638                 diag::err_typecheck_call_too_few_args_at_least)
4639            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
4640            << TheCall->getSourceRange();
4641 
4642   if (TheCall->getNumArgs() > ExpectedNumArgs)
4643     return Diag(TheCall->getLocEnd(),
4644                 diag::err_typecheck_call_too_many_args_at_most)
4645            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4646            << TheCall->getSourceRange();
4647 
4648   // Check the third argument is a compile time constant
4649   llvm::APSInt Value;
4650   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4651     return Diag(TheCall->getLocStart(),
4652                 diag::err_vsx_builtin_nonconstant_argument)
4653            << 3 /* argument index */ << TheCall->getDirectCallee()
4654            << SourceRange(TheCall->getArg(2)->getLocStart(),
4655                           TheCall->getArg(2)->getLocEnd());
4656 
4657   QualType Arg1Ty = TheCall->getArg(0)->getType();
4658   QualType Arg2Ty = TheCall->getArg(1)->getType();
4659 
4660   // Check the type of argument 1 and argument 2 are vectors.
4661   SourceLocation BuiltinLoc = TheCall->getLocStart();
4662   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4663       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4664     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4665            << TheCall->getDirectCallee()
4666            << SourceRange(TheCall->getArg(0)->getLocStart(),
4667                           TheCall->getArg(1)->getLocEnd());
4668   }
4669 
4670   // Check the first two arguments are the same type.
4671   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4672     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4673            << TheCall->getDirectCallee()
4674            << SourceRange(TheCall->getArg(0)->getLocStart(),
4675                           TheCall->getArg(1)->getLocEnd());
4676   }
4677 
4678   // When default clang type checking is turned off and the customized type
4679   // checking is used, the returning type of the function must be explicitly
4680   // set. Otherwise it is _Bool by default.
4681   TheCall->setType(Arg1Ty);
4682 
4683   return false;
4684 }
4685 
4686 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4687 // This is declared to take (...), so we have to check everything.
4688 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4689   if (TheCall->getNumArgs() < 2)
4690     return ExprError(Diag(TheCall->getLocEnd(),
4691                           diag::err_typecheck_call_too_few_args_at_least)
4692                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4693                      << TheCall->getSourceRange());
4694 
4695   // Determine which of the following types of shufflevector we're checking:
4696   // 1) unary, vector mask: (lhs, mask)
4697   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4698   QualType resType = TheCall->getArg(0)->getType();
4699   unsigned numElements = 0;
4700 
4701   if (!TheCall->getArg(0)->isTypeDependent() &&
4702       !TheCall->getArg(1)->isTypeDependent()) {
4703     QualType LHSType = TheCall->getArg(0)->getType();
4704     QualType RHSType = TheCall->getArg(1)->getType();
4705 
4706     if (!LHSType->isVectorType() || !RHSType->isVectorType())
4707       return ExprError(Diag(TheCall->getLocStart(),
4708                             diag::err_vec_builtin_non_vector)
4709                        << TheCall->getDirectCallee()
4710                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4711                                       TheCall->getArg(1)->getLocEnd()));
4712 
4713     numElements = LHSType->getAs<VectorType>()->getNumElements();
4714     unsigned numResElements = TheCall->getNumArgs() - 2;
4715 
4716     // Check to see if we have a call with 2 vector arguments, the unary shuffle
4717     // with mask.  If so, verify that RHS is an integer vector type with the
4718     // same number of elts as lhs.
4719     if (TheCall->getNumArgs() == 2) {
4720       if (!RHSType->hasIntegerRepresentation() ||
4721           RHSType->getAs<VectorType>()->getNumElements() != numElements)
4722         return ExprError(Diag(TheCall->getLocStart(),
4723                               diag::err_vec_builtin_incompatible_vector)
4724                          << TheCall->getDirectCallee()
4725                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4726                                         TheCall->getArg(1)->getLocEnd()));
4727     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4728       return ExprError(Diag(TheCall->getLocStart(),
4729                             diag::err_vec_builtin_incompatible_vector)
4730                        << TheCall->getDirectCallee()
4731                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4732                                       TheCall->getArg(1)->getLocEnd()));
4733     } else if (numElements != numResElements) {
4734       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4735       resType = Context.getVectorType(eltType, numResElements,
4736                                       VectorType::GenericVector);
4737     }
4738   }
4739 
4740   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4741     if (TheCall->getArg(i)->isTypeDependent() ||
4742         TheCall->getArg(i)->isValueDependent())
4743       continue;
4744 
4745     llvm::APSInt Result(32);
4746     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4747       return ExprError(Diag(TheCall->getLocStart(),
4748                             diag::err_shufflevector_nonconstant_argument)
4749                        << TheCall->getArg(i)->getSourceRange());
4750 
4751     // Allow -1 which will be translated to undef in the IR.
4752     if (Result.isSigned() && Result.isAllOnesValue())
4753       continue;
4754 
4755     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4756       return ExprError(Diag(TheCall->getLocStart(),
4757                             diag::err_shufflevector_argument_too_large)
4758                        << TheCall->getArg(i)->getSourceRange());
4759   }
4760 
4761   SmallVector<Expr*, 32> exprs;
4762 
4763   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4764     exprs.push_back(TheCall->getArg(i));
4765     TheCall->setArg(i, nullptr);
4766   }
4767 
4768   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4769                                          TheCall->getCallee()->getLocStart(),
4770                                          TheCall->getRParenLoc());
4771 }
4772 
4773 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4774 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4775                                        SourceLocation BuiltinLoc,
4776                                        SourceLocation RParenLoc) {
4777   ExprValueKind VK = VK_RValue;
4778   ExprObjectKind OK = OK_Ordinary;
4779   QualType DstTy = TInfo->getType();
4780   QualType SrcTy = E->getType();
4781 
4782   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4783     return ExprError(Diag(BuiltinLoc,
4784                           diag::err_convertvector_non_vector)
4785                      << E->getSourceRange());
4786   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4787     return ExprError(Diag(BuiltinLoc,
4788                           diag::err_convertvector_non_vector_type));
4789 
4790   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4791     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4792     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4793     if (SrcElts != DstElts)
4794       return ExprError(Diag(BuiltinLoc,
4795                             diag::err_convertvector_incompatible_vector)
4796                        << E->getSourceRange());
4797   }
4798 
4799   return new (Context)
4800       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4801 }
4802 
4803 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4804 // This is declared to take (const void*, ...) and can take two
4805 // optional constant int args.
4806 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4807   unsigned NumArgs = TheCall->getNumArgs();
4808 
4809   if (NumArgs > 3)
4810     return Diag(TheCall->getLocEnd(),
4811              diag::err_typecheck_call_too_many_args_at_most)
4812              << 0 /*function call*/ << 3 << NumArgs
4813              << TheCall->getSourceRange();
4814 
4815   // Argument 0 is checked for us and the remaining arguments must be
4816   // constant integers.
4817   for (unsigned i = 1; i != NumArgs; ++i)
4818     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4819       return true;
4820 
4821   return false;
4822 }
4823 
4824 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4825 // __assume does not evaluate its arguments, and should warn if its argument
4826 // has side effects.
4827 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4828   Expr *Arg = TheCall->getArg(0);
4829   if (Arg->isInstantiationDependent()) return false;
4830 
4831   if (Arg->HasSideEffects(Context))
4832     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4833       << Arg->getSourceRange()
4834       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4835 
4836   return false;
4837 }
4838 
4839 /// Handle __builtin_alloca_with_align. This is declared
4840 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4841 /// than 8.
4842 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4843   // The alignment must be a constant integer.
4844   Expr *Arg = TheCall->getArg(1);
4845 
4846   // We can't check the value of a dependent argument.
4847   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4848     if (const auto *UE =
4849             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4850       if (UE->getKind() == UETT_AlignOf)
4851         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4852           << Arg->getSourceRange();
4853 
4854     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4855 
4856     if (!Result.isPowerOf2())
4857       return Diag(TheCall->getLocStart(),
4858                   diag::err_alignment_not_power_of_two)
4859            << Arg->getSourceRange();
4860 
4861     if (Result < Context.getCharWidth())
4862       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4863            << (unsigned)Context.getCharWidth()
4864            << Arg->getSourceRange();
4865 
4866     if (Result > std::numeric_limits<int32_t>::max())
4867       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4868            << std::numeric_limits<int32_t>::max()
4869            << Arg->getSourceRange();
4870   }
4871 
4872   return false;
4873 }
4874 
4875 /// Handle __builtin_assume_aligned. This is declared
4876 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4877 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4878   unsigned NumArgs = TheCall->getNumArgs();
4879 
4880   if (NumArgs > 3)
4881     return Diag(TheCall->getLocEnd(),
4882              diag::err_typecheck_call_too_many_args_at_most)
4883              << 0 /*function call*/ << 3 << NumArgs
4884              << TheCall->getSourceRange();
4885 
4886   // The alignment must be a constant integer.
4887   Expr *Arg = TheCall->getArg(1);
4888 
4889   // We can't check the value of a dependent argument.
4890   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4891     llvm::APSInt Result;
4892     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4893       return true;
4894 
4895     if (!Result.isPowerOf2())
4896       return Diag(TheCall->getLocStart(),
4897                   diag::err_alignment_not_power_of_two)
4898            << Arg->getSourceRange();
4899   }
4900 
4901   if (NumArgs > 2) {
4902     ExprResult Arg(TheCall->getArg(2));
4903     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4904       Context.getSizeType(), false);
4905     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4906     if (Arg.isInvalid()) return true;
4907     TheCall->setArg(2, Arg.get());
4908   }
4909 
4910   return false;
4911 }
4912 
4913 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4914   unsigned BuiltinID =
4915       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4916   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4917 
4918   unsigned NumArgs = TheCall->getNumArgs();
4919   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4920   if (NumArgs < NumRequiredArgs) {
4921     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4922            << 0 /* function call */ << NumRequiredArgs << NumArgs
4923            << TheCall->getSourceRange();
4924   }
4925   if (NumArgs >= NumRequiredArgs + 0x100) {
4926     return Diag(TheCall->getLocEnd(),
4927                 diag::err_typecheck_call_too_many_args_at_most)
4928            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4929            << TheCall->getSourceRange();
4930   }
4931   unsigned i = 0;
4932 
4933   // For formatting call, check buffer arg.
4934   if (!IsSizeCall) {
4935     ExprResult Arg(TheCall->getArg(i));
4936     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4937         Context, Context.VoidPtrTy, false);
4938     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4939     if (Arg.isInvalid())
4940       return true;
4941     TheCall->setArg(i, Arg.get());
4942     i++;
4943   }
4944 
4945   // Check string literal arg.
4946   unsigned FormatIdx = i;
4947   {
4948     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4949     if (Arg.isInvalid())
4950       return true;
4951     TheCall->setArg(i, Arg.get());
4952     i++;
4953   }
4954 
4955   // Make sure variadic args are scalar.
4956   unsigned FirstDataArg = i;
4957   while (i < NumArgs) {
4958     ExprResult Arg = DefaultVariadicArgumentPromotion(
4959         TheCall->getArg(i), VariadicFunction, nullptr);
4960     if (Arg.isInvalid())
4961       return true;
4962     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4963     if (ArgSize.getQuantity() >= 0x100) {
4964       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4965              << i << (int)ArgSize.getQuantity() << 0xff
4966              << TheCall->getSourceRange();
4967     }
4968     TheCall->setArg(i, Arg.get());
4969     i++;
4970   }
4971 
4972   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4973   // call to avoid duplicate diagnostics.
4974   if (!IsSizeCall) {
4975     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4976     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4977     bool Success = CheckFormatArguments(
4978         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4979         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4980         CheckedVarArgs);
4981     if (!Success)
4982       return true;
4983   }
4984 
4985   if (IsSizeCall) {
4986     TheCall->setType(Context.getSizeType());
4987   } else {
4988     TheCall->setType(Context.VoidPtrTy);
4989   }
4990   return false;
4991 }
4992 
4993 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4994 /// TheCall is a constant expression.
4995 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4996                                   llvm::APSInt &Result) {
4997   Expr *Arg = TheCall->getArg(ArgNum);
4998   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4999   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5000 
5001   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5002 
5003   if (!Arg->isIntegerConstantExpr(Result, Context))
5004     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
5005                 << FDecl->getDeclName() <<  Arg->getSourceRange();
5006 
5007   return false;
5008 }
5009 
5010 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5011 /// TheCall is a constant expression in the range [Low, High].
5012 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5013                                        int Low, int High, bool RangeIsError) {
5014   llvm::APSInt Result;
5015 
5016   // We can't check the value of a dependent argument.
5017   Expr *Arg = TheCall->getArg(ArgNum);
5018   if (Arg->isTypeDependent() || Arg->isValueDependent())
5019     return false;
5020 
5021   // Check constant-ness first.
5022   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5023     return true;
5024 
5025   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5026     if (RangeIsError)
5027       return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
5028              << Result.toString(10) << Low << High << Arg->getSourceRange();
5029     else
5030       // Defer the warning until we know if the code will be emitted so that
5031       // dead code can ignore this.
5032       DiagRuntimeBehavior(TheCall->getLocStart(), TheCall,
5033                             PDiag(diag::warn_argument_invalid_range)
5034                                 << Result.toString(10) << Low << High
5035                                 << Arg->getSourceRange());
5036   }
5037 
5038   return false;
5039 }
5040 
5041 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5042 /// TheCall is a constant expression is a multiple of Num..
5043 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5044                                           unsigned Num) {
5045   llvm::APSInt Result;
5046 
5047   // We can't check the value of a dependent argument.
5048   Expr *Arg = TheCall->getArg(ArgNum);
5049   if (Arg->isTypeDependent() || Arg->isValueDependent())
5050     return false;
5051 
5052   // Check constant-ness first.
5053   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5054     return true;
5055 
5056   if (Result.getSExtValue() % Num != 0)
5057     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
5058       << Num << Arg->getSourceRange();
5059 
5060   return false;
5061 }
5062 
5063 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5064 /// TheCall is an ARM/AArch64 special register string literal.
5065 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5066                                     int ArgNum, unsigned ExpectedFieldNum,
5067                                     bool AllowName) {
5068   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5069                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5070                       BuiltinID == ARM::BI__builtin_arm_rsr ||
5071                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
5072                       BuiltinID == ARM::BI__builtin_arm_wsr ||
5073                       BuiltinID == ARM::BI__builtin_arm_wsrp;
5074   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5075                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5076                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
5077                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5078                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
5079                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
5080   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5081 
5082   // We can't check the value of a dependent argument.
5083   Expr *Arg = TheCall->getArg(ArgNum);
5084   if (Arg->isTypeDependent() || Arg->isValueDependent())
5085     return false;
5086 
5087   // Check if the argument is a string literal.
5088   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
5089     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
5090            << Arg->getSourceRange();
5091 
5092   // Check the type of special register given.
5093   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
5094   SmallVector<StringRef, 6> Fields;
5095   Reg.split(Fields, ":");
5096 
5097   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
5098     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5099            << Arg->getSourceRange();
5100 
5101   // If the string is the name of a register then we cannot check that it is
5102   // valid here but if the string is of one the forms described in ACLE then we
5103   // can check that the supplied fields are integers and within the valid
5104   // ranges.
5105   if (Fields.size() > 1) {
5106     bool FiveFields = Fields.size() == 5;
5107 
5108     bool ValidString = true;
5109     if (IsARMBuiltin) {
5110       ValidString &= Fields[0].startswith_lower("cp") ||
5111                      Fields[0].startswith_lower("p");
5112       if (ValidString)
5113         Fields[0] =
5114           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
5115 
5116       ValidString &= Fields[2].startswith_lower("c");
5117       if (ValidString)
5118         Fields[2] = Fields[2].drop_front(1);
5119 
5120       if (FiveFields) {
5121         ValidString &= Fields[3].startswith_lower("c");
5122         if (ValidString)
5123           Fields[3] = Fields[3].drop_front(1);
5124       }
5125     }
5126 
5127     SmallVector<int, 5> Ranges;
5128     if (FiveFields)
5129       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
5130     else
5131       Ranges.append({15, 7, 15});
5132 
5133     for (unsigned i=0; i<Fields.size(); ++i) {
5134       int IntField;
5135       ValidString &= !Fields[i].getAsInteger(10, IntField);
5136       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
5137     }
5138 
5139     if (!ValidString)
5140       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5141              << Arg->getSourceRange();
5142   } else if (IsAArch64Builtin && Fields.size() == 1) {
5143     // If the register name is one of those that appear in the condition below
5144     // and the special register builtin being used is one of the write builtins,
5145     // then we require that the argument provided for writing to the register
5146     // is an integer constant expression. This is because it will be lowered to
5147     // an MSR (immediate) instruction, so we need to know the immediate at
5148     // compile time.
5149     if (TheCall->getNumArgs() != 2)
5150       return false;
5151 
5152     std::string RegLower = Reg.lower();
5153     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
5154         RegLower != "pan" && RegLower != "uao")
5155       return false;
5156 
5157     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5158   }
5159 
5160   return false;
5161 }
5162 
5163 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
5164 /// This checks that the target supports __builtin_longjmp and
5165 /// that val is a constant 1.
5166 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
5167   if (!Context.getTargetInfo().hasSjLjLowering())
5168     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
5169              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5170 
5171   Expr *Arg = TheCall->getArg(1);
5172   llvm::APSInt Result;
5173 
5174   // TODO: This is less than ideal. Overload this to take a value.
5175   if (SemaBuiltinConstantArg(TheCall, 1, Result))
5176     return true;
5177 
5178   if (Result != 1)
5179     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
5180              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
5181 
5182   return false;
5183 }
5184 
5185 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5186 /// This checks that the target supports __builtin_setjmp.
5187 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5188   if (!Context.getTargetInfo().hasSjLjLowering())
5189     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
5190              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5191   return false;
5192 }
5193 
5194 namespace {
5195 
5196 class UncoveredArgHandler {
5197   enum { Unknown = -1, AllCovered = -2 };
5198 
5199   signed FirstUncoveredArg = Unknown;
5200   SmallVector<const Expr *, 4> DiagnosticExprs;
5201 
5202 public:
5203   UncoveredArgHandler() = default;
5204 
5205   bool hasUncoveredArg() const {
5206     return (FirstUncoveredArg >= 0);
5207   }
5208 
5209   unsigned getUncoveredArg() const {
5210     assert(hasUncoveredArg() && "no uncovered argument");
5211     return FirstUncoveredArg;
5212   }
5213 
5214   void setAllCovered() {
5215     // A string has been found with all arguments covered, so clear out
5216     // the diagnostics.
5217     DiagnosticExprs.clear();
5218     FirstUncoveredArg = AllCovered;
5219   }
5220 
5221   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5222     assert(NewFirstUncoveredArg >= 0 && "Outside range");
5223 
5224     // Don't update if a previous string covers all arguments.
5225     if (FirstUncoveredArg == AllCovered)
5226       return;
5227 
5228     // UncoveredArgHandler tracks the highest uncovered argument index
5229     // and with it all the strings that match this index.
5230     if (NewFirstUncoveredArg == FirstUncoveredArg)
5231       DiagnosticExprs.push_back(StrExpr);
5232     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5233       DiagnosticExprs.clear();
5234       DiagnosticExprs.push_back(StrExpr);
5235       FirstUncoveredArg = NewFirstUncoveredArg;
5236     }
5237   }
5238 
5239   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5240 };
5241 
5242 enum StringLiteralCheckType {
5243   SLCT_NotALiteral,
5244   SLCT_UncheckedLiteral,
5245   SLCT_CheckedLiteral
5246 };
5247 
5248 } // namespace
5249 
5250 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5251                                      BinaryOperatorKind BinOpKind,
5252                                      bool AddendIsRight) {
5253   unsigned BitWidth = Offset.getBitWidth();
5254   unsigned AddendBitWidth = Addend.getBitWidth();
5255   // There might be negative interim results.
5256   if (Addend.isUnsigned()) {
5257     Addend = Addend.zext(++AddendBitWidth);
5258     Addend.setIsSigned(true);
5259   }
5260   // Adjust the bit width of the APSInts.
5261   if (AddendBitWidth > BitWidth) {
5262     Offset = Offset.sext(AddendBitWidth);
5263     BitWidth = AddendBitWidth;
5264   } else if (BitWidth > AddendBitWidth) {
5265     Addend = Addend.sext(BitWidth);
5266   }
5267 
5268   bool Ov = false;
5269   llvm::APSInt ResOffset = Offset;
5270   if (BinOpKind == BO_Add)
5271     ResOffset = Offset.sadd_ov(Addend, Ov);
5272   else {
5273     assert(AddendIsRight && BinOpKind == BO_Sub &&
5274            "operator must be add or sub with addend on the right");
5275     ResOffset = Offset.ssub_ov(Addend, Ov);
5276   }
5277 
5278   // We add an offset to a pointer here so we should support an offset as big as
5279   // possible.
5280   if (Ov) {
5281     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5282            "index (intermediate) result too big");
5283     Offset = Offset.sext(2 * BitWidth);
5284     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5285     return;
5286   }
5287 
5288   Offset = ResOffset;
5289 }
5290 
5291 namespace {
5292 
5293 // This is a wrapper class around StringLiteral to support offsetted string
5294 // literals as format strings. It takes the offset into account when returning
5295 // the string and its length or the source locations to display notes correctly.
5296 class FormatStringLiteral {
5297   const StringLiteral *FExpr;
5298   int64_t Offset;
5299 
5300  public:
5301   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5302       : FExpr(fexpr), Offset(Offset) {}
5303 
5304   StringRef getString() const {
5305     return FExpr->getString().drop_front(Offset);
5306   }
5307 
5308   unsigned getByteLength() const {
5309     return FExpr->getByteLength() - getCharByteWidth() * Offset;
5310   }
5311 
5312   unsigned getLength() const { return FExpr->getLength() - Offset; }
5313   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5314 
5315   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5316 
5317   QualType getType() const { return FExpr->getType(); }
5318 
5319   bool isAscii() const { return FExpr->isAscii(); }
5320   bool isWide() const { return FExpr->isWide(); }
5321   bool isUTF8() const { return FExpr->isUTF8(); }
5322   bool isUTF16() const { return FExpr->isUTF16(); }
5323   bool isUTF32() const { return FExpr->isUTF32(); }
5324   bool isPascal() const { return FExpr->isPascal(); }
5325 
5326   SourceLocation getLocationOfByte(
5327       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5328       const TargetInfo &Target, unsigned *StartToken = nullptr,
5329       unsigned *StartTokenByteOffset = nullptr) const {
5330     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5331                                     StartToken, StartTokenByteOffset);
5332   }
5333 
5334   SourceLocation getLocStart() const LLVM_READONLY {
5335     return FExpr->getLocStart().getLocWithOffset(Offset);
5336   }
5337 
5338   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5339 };
5340 
5341 }  // namespace
5342 
5343 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
5344                               const Expr *OrigFormatExpr,
5345                               ArrayRef<const Expr *> Args,
5346                               bool HasVAListArg, unsigned format_idx,
5347                               unsigned firstDataArg,
5348                               Sema::FormatStringType Type,
5349                               bool inFunctionCall,
5350                               Sema::VariadicCallType CallType,
5351                               llvm::SmallBitVector &CheckedVarArgs,
5352                               UncoveredArgHandler &UncoveredArg);
5353 
5354 // Determine if an expression is a string literal or constant string.
5355 // If this function returns false on the arguments to a function expecting a
5356 // format string, we will usually need to emit a warning.
5357 // True string literals are then checked by CheckFormatString.
5358 static StringLiteralCheckType
5359 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5360                       bool HasVAListArg, unsigned format_idx,
5361                       unsigned firstDataArg, Sema::FormatStringType Type,
5362                       Sema::VariadicCallType CallType, bool InFunctionCall,
5363                       llvm::SmallBitVector &CheckedVarArgs,
5364                       UncoveredArgHandler &UncoveredArg,
5365                       llvm::APSInt Offset) {
5366  tryAgain:
5367   assert(Offset.isSigned() && "invalid offset");
5368 
5369   if (E->isTypeDependent() || E->isValueDependent())
5370     return SLCT_NotALiteral;
5371 
5372   E = E->IgnoreParenCasts();
5373 
5374   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
5375     // Technically -Wformat-nonliteral does not warn about this case.
5376     // The behavior of printf and friends in this case is implementation
5377     // dependent.  Ideally if the format string cannot be null then
5378     // it should have a 'nonnull' attribute in the function prototype.
5379     return SLCT_UncheckedLiteral;
5380 
5381   switch (E->getStmtClass()) {
5382   case Stmt::BinaryConditionalOperatorClass:
5383   case Stmt::ConditionalOperatorClass: {
5384     // The expression is a literal if both sub-expressions were, and it was
5385     // completely checked only if both sub-expressions were checked.
5386     const AbstractConditionalOperator *C =
5387         cast<AbstractConditionalOperator>(E);
5388 
5389     // Determine whether it is necessary to check both sub-expressions, for
5390     // example, because the condition expression is a constant that can be
5391     // evaluated at compile time.
5392     bool CheckLeft = true, CheckRight = true;
5393 
5394     bool Cond;
5395     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5396       if (Cond)
5397         CheckRight = false;
5398       else
5399         CheckLeft = false;
5400     }
5401 
5402     // We need to maintain the offsets for the right and the left hand side
5403     // separately to check if every possible indexed expression is a valid
5404     // string literal. They might have different offsets for different string
5405     // literals in the end.
5406     StringLiteralCheckType Left;
5407     if (!CheckLeft)
5408       Left = SLCT_UncheckedLiteral;
5409     else {
5410       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5411                                    HasVAListArg, format_idx, firstDataArg,
5412                                    Type, CallType, InFunctionCall,
5413                                    CheckedVarArgs, UncoveredArg, Offset);
5414       if (Left == SLCT_NotALiteral || !CheckRight) {
5415         return Left;
5416       }
5417     }
5418 
5419     StringLiteralCheckType Right =
5420         checkFormatStringExpr(S, C->getFalseExpr(), Args,
5421                               HasVAListArg, format_idx, firstDataArg,
5422                               Type, CallType, InFunctionCall, CheckedVarArgs,
5423                               UncoveredArg, Offset);
5424 
5425     return (CheckLeft && Left < Right) ? Left : Right;
5426   }
5427 
5428   case Stmt::ImplicitCastExprClass:
5429     E = cast<ImplicitCastExpr>(E)->getSubExpr();
5430     goto tryAgain;
5431 
5432   case Stmt::OpaqueValueExprClass:
5433     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5434       E = src;
5435       goto tryAgain;
5436     }
5437     return SLCT_NotALiteral;
5438 
5439   case Stmt::PredefinedExprClass:
5440     // While __func__, etc., are technically not string literals, they
5441     // cannot contain format specifiers and thus are not a security
5442     // liability.
5443     return SLCT_UncheckedLiteral;
5444 
5445   case Stmt::DeclRefExprClass: {
5446     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
5447 
5448     // As an exception, do not flag errors for variables binding to
5449     // const string literals.
5450     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5451       bool isConstant = false;
5452       QualType T = DR->getType();
5453 
5454       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5455         isConstant = AT->getElementType().isConstant(S.Context);
5456       } else if (const PointerType *PT = T->getAs<PointerType>()) {
5457         isConstant = T.isConstant(S.Context) &&
5458                      PT->getPointeeType().isConstant(S.Context);
5459       } else if (T->isObjCObjectPointerType()) {
5460         // In ObjC, there is usually no "const ObjectPointer" type,
5461         // so don't check if the pointee type is constant.
5462         isConstant = T.isConstant(S.Context);
5463       }
5464 
5465       if (isConstant) {
5466         if (const Expr *Init = VD->getAnyInitializer()) {
5467           // Look through initializers like const char c[] = { "foo" }
5468           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5469             if (InitList->isStringLiteralInit())
5470               Init = InitList->getInit(0)->IgnoreParenImpCasts();
5471           }
5472           return checkFormatStringExpr(S, Init, Args,
5473                                        HasVAListArg, format_idx,
5474                                        firstDataArg, Type, CallType,
5475                                        /*InFunctionCall*/ false, CheckedVarArgs,
5476                                        UncoveredArg, Offset);
5477         }
5478       }
5479 
5480       // For vprintf* functions (i.e., HasVAListArg==true), we add a
5481       // special check to see if the format string is a function parameter
5482       // of the function calling the printf function.  If the function
5483       // has an attribute indicating it is a printf-like function, then we
5484       // should suppress warnings concerning non-literals being used in a call
5485       // to a vprintf function.  For example:
5486       //
5487       // void
5488       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5489       //      va_list ap;
5490       //      va_start(ap, fmt);
5491       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
5492       //      ...
5493       // }
5494       if (HasVAListArg) {
5495         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5496           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5497             int PVIndex = PV->getFunctionScopeIndex() + 1;
5498             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
5499               // adjust for implicit parameter
5500               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5501                 if (MD->isInstance())
5502                   ++PVIndex;
5503               // We also check if the formats are compatible.
5504               // We can't pass a 'scanf' string to a 'printf' function.
5505               if (PVIndex == PVFormat->getFormatIdx() &&
5506                   Type == S.GetFormatStringType(PVFormat))
5507                 return SLCT_UncheckedLiteral;
5508             }
5509           }
5510         }
5511       }
5512     }
5513 
5514     return SLCT_NotALiteral;
5515   }
5516 
5517   case Stmt::CallExprClass:
5518   case Stmt::CXXMemberCallExprClass: {
5519     const CallExpr *CE = cast<CallExpr>(E);
5520     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5521       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5522         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
5523         return checkFormatStringExpr(S, Arg, Args,
5524                                      HasVAListArg, format_idx, firstDataArg,
5525                                      Type, CallType, InFunctionCall,
5526                                      CheckedVarArgs, UncoveredArg, Offset);
5527       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5528         unsigned BuiltinID = FD->getBuiltinID();
5529         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5530             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5531           const Expr *Arg = CE->getArg(0);
5532           return checkFormatStringExpr(S, Arg, Args,
5533                                        HasVAListArg, format_idx,
5534                                        firstDataArg, Type, CallType,
5535                                        InFunctionCall, CheckedVarArgs,
5536                                        UncoveredArg, Offset);
5537         }
5538       }
5539     }
5540 
5541     return SLCT_NotALiteral;
5542   }
5543   case Stmt::ObjCMessageExprClass: {
5544     const auto *ME = cast<ObjCMessageExpr>(E);
5545     if (const auto *ND = ME->getMethodDecl()) {
5546       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5547         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
5548         return checkFormatStringExpr(
5549             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5550             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5551       }
5552     }
5553 
5554     return SLCT_NotALiteral;
5555   }
5556   case Stmt::ObjCStringLiteralClass:
5557   case Stmt::StringLiteralClass: {
5558     const StringLiteral *StrE = nullptr;
5559 
5560     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
5561       StrE = ObjCFExpr->getString();
5562     else
5563       StrE = cast<StringLiteral>(E);
5564 
5565     if (StrE) {
5566       if (Offset.isNegative() || Offset > StrE->getLength()) {
5567         // TODO: It would be better to have an explicit warning for out of
5568         // bounds literals.
5569         return SLCT_NotALiteral;
5570       }
5571       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5572       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5573                         firstDataArg, Type, InFunctionCall, CallType,
5574                         CheckedVarArgs, UncoveredArg);
5575       return SLCT_CheckedLiteral;
5576     }
5577 
5578     return SLCT_NotALiteral;
5579   }
5580   case Stmt::BinaryOperatorClass: {
5581     llvm::APSInt LResult;
5582     llvm::APSInt RResult;
5583 
5584     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5585 
5586     // A string literal + an int offset is still a string literal.
5587     if (BinOp->isAdditiveOp()) {
5588       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5589       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5590 
5591       if (LIsInt != RIsInt) {
5592         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5593 
5594         if (LIsInt) {
5595           if (BinOpKind == BO_Add) {
5596             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5597             E = BinOp->getRHS();
5598             goto tryAgain;
5599           }
5600         } else {
5601           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5602           E = BinOp->getLHS();
5603           goto tryAgain;
5604         }
5605       }
5606     }
5607 
5608     return SLCT_NotALiteral;
5609   }
5610   case Stmt::UnaryOperatorClass: {
5611     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5612     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5613     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
5614       llvm::APSInt IndexResult;
5615       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5616         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5617         E = ASE->getBase();
5618         goto tryAgain;
5619       }
5620     }
5621 
5622     return SLCT_NotALiteral;
5623   }
5624 
5625   default:
5626     return SLCT_NotALiteral;
5627   }
5628 }
5629 
5630 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5631   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5632       .Case("scanf", FST_Scanf)
5633       .Cases("printf", "printf0", FST_Printf)
5634       .Cases("NSString", "CFString", FST_NSString)
5635       .Case("strftime", FST_Strftime)
5636       .Case("strfmon", FST_Strfmon)
5637       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5638       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5639       .Case("os_trace", FST_OSLog)
5640       .Case("os_log", FST_OSLog)
5641       .Default(FST_Unknown);
5642 }
5643 
5644 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5645 /// functions) for correct use of format strings.
5646 /// Returns true if a format string has been fully checked.
5647 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5648                                 ArrayRef<const Expr *> Args,
5649                                 bool IsCXXMember,
5650                                 VariadicCallType CallType,
5651                                 SourceLocation Loc, SourceRange Range,
5652                                 llvm::SmallBitVector &CheckedVarArgs) {
5653   FormatStringInfo FSI;
5654   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5655     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5656                                 FSI.FirstDataArg, GetFormatStringType(Format),
5657                                 CallType, Loc, Range, CheckedVarArgs);
5658   return false;
5659 }
5660 
5661 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5662                                 bool HasVAListArg, unsigned format_idx,
5663                                 unsigned firstDataArg, FormatStringType Type,
5664                                 VariadicCallType CallType,
5665                                 SourceLocation Loc, SourceRange Range,
5666                                 llvm::SmallBitVector &CheckedVarArgs) {
5667   // CHECK: printf/scanf-like function is called with no format string.
5668   if (format_idx >= Args.size()) {
5669     Diag(Loc, diag::warn_missing_format_string) << Range;
5670     return false;
5671   }
5672 
5673   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5674 
5675   // CHECK: format string is not a string literal.
5676   //
5677   // Dynamically generated format strings are difficult to
5678   // automatically vet at compile time.  Requiring that format strings
5679   // are string literals: (1) permits the checking of format strings by
5680   // the compiler and thereby (2) can practically remove the source of
5681   // many format string exploits.
5682 
5683   // Format string can be either ObjC string (e.g. @"%d") or
5684   // C string (e.g. "%d")
5685   // ObjC string uses the same format specifiers as C string, so we can use
5686   // the same format string checking logic for both ObjC and C strings.
5687   UncoveredArgHandler UncoveredArg;
5688   StringLiteralCheckType CT =
5689       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5690                             format_idx, firstDataArg, Type, CallType,
5691                             /*IsFunctionCall*/ true, CheckedVarArgs,
5692                             UncoveredArg,
5693                             /*no string offset*/ llvm::APSInt(64, false) = 0);
5694 
5695   // Generate a diagnostic where an uncovered argument is detected.
5696   if (UncoveredArg.hasUncoveredArg()) {
5697     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5698     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5699     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5700   }
5701 
5702   if (CT != SLCT_NotALiteral)
5703     // Literal format string found, check done!
5704     return CT == SLCT_CheckedLiteral;
5705 
5706   // Strftime is particular as it always uses a single 'time' argument,
5707   // so it is safe to pass a non-literal string.
5708   if (Type == FST_Strftime)
5709     return false;
5710 
5711   // Do not emit diag when the string param is a macro expansion and the
5712   // format is either NSString or CFString. This is a hack to prevent
5713   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5714   // which are usually used in place of NS and CF string literals.
5715   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5716   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5717     return false;
5718 
5719   // If there are no arguments specified, warn with -Wformat-security, otherwise
5720   // warn only with -Wformat-nonliteral.
5721   if (Args.size() == firstDataArg) {
5722     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5723       << OrigFormatExpr->getSourceRange();
5724     switch (Type) {
5725     default:
5726       break;
5727     case FST_Kprintf:
5728     case FST_FreeBSDKPrintf:
5729     case FST_Printf:
5730       Diag(FormatLoc, diag::note_format_security_fixit)
5731         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5732       break;
5733     case FST_NSString:
5734       Diag(FormatLoc, diag::note_format_security_fixit)
5735         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5736       break;
5737     }
5738   } else {
5739     Diag(FormatLoc, diag::warn_format_nonliteral)
5740       << OrigFormatExpr->getSourceRange();
5741   }
5742   return false;
5743 }
5744 
5745 namespace {
5746 
5747 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5748 protected:
5749   Sema &S;
5750   const FormatStringLiteral *FExpr;
5751   const Expr *OrigFormatExpr;
5752   const Sema::FormatStringType FSType;
5753   const unsigned FirstDataArg;
5754   const unsigned NumDataArgs;
5755   const char *Beg; // Start of format string.
5756   const bool HasVAListArg;
5757   ArrayRef<const Expr *> Args;
5758   unsigned FormatIdx;
5759   llvm::SmallBitVector CoveredArgs;
5760   bool usesPositionalArgs = false;
5761   bool atFirstArg = true;
5762   bool inFunctionCall;
5763   Sema::VariadicCallType CallType;
5764   llvm::SmallBitVector &CheckedVarArgs;
5765   UncoveredArgHandler &UncoveredArg;
5766 
5767 public:
5768   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5769                      const Expr *origFormatExpr,
5770                      const Sema::FormatStringType type, unsigned firstDataArg,
5771                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5772                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5773                      bool inFunctionCall, Sema::VariadicCallType callType,
5774                      llvm::SmallBitVector &CheckedVarArgs,
5775                      UncoveredArgHandler &UncoveredArg)
5776       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5777         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5778         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5779         inFunctionCall(inFunctionCall), CallType(callType),
5780         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5781     CoveredArgs.resize(numDataArgs);
5782     CoveredArgs.reset();
5783   }
5784 
5785   void DoneProcessing();
5786 
5787   void HandleIncompleteSpecifier(const char *startSpecifier,
5788                                  unsigned specifierLen) override;
5789 
5790   void HandleInvalidLengthModifier(
5791                            const analyze_format_string::FormatSpecifier &FS,
5792                            const analyze_format_string::ConversionSpecifier &CS,
5793                            const char *startSpecifier, unsigned specifierLen,
5794                            unsigned DiagID);
5795 
5796   void HandleNonStandardLengthModifier(
5797                     const analyze_format_string::FormatSpecifier &FS,
5798                     const char *startSpecifier, unsigned specifierLen);
5799 
5800   void HandleNonStandardConversionSpecifier(
5801                     const analyze_format_string::ConversionSpecifier &CS,
5802                     const char *startSpecifier, unsigned specifierLen);
5803 
5804   void HandlePosition(const char *startPos, unsigned posLen) override;
5805 
5806   void HandleInvalidPosition(const char *startSpecifier,
5807                              unsigned specifierLen,
5808                              analyze_format_string::PositionContext p) override;
5809 
5810   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5811 
5812   void HandleNullChar(const char *nullCharacter) override;
5813 
5814   template <typename Range>
5815   static void
5816   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5817                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5818                        bool IsStringLocation, Range StringRange,
5819                        ArrayRef<FixItHint> Fixit = None);
5820 
5821 protected:
5822   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5823                                         const char *startSpec,
5824                                         unsigned specifierLen,
5825                                         const char *csStart, unsigned csLen);
5826 
5827   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5828                                          const char *startSpec,
5829                                          unsigned specifierLen);
5830 
5831   SourceRange getFormatStringRange();
5832   CharSourceRange getSpecifierRange(const char *startSpecifier,
5833                                     unsigned specifierLen);
5834   SourceLocation getLocationOfByte(const char *x);
5835 
5836   const Expr *getDataArg(unsigned i) const;
5837 
5838   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5839                     const analyze_format_string::ConversionSpecifier &CS,
5840                     const char *startSpecifier, unsigned specifierLen,
5841                     unsigned argIndex);
5842 
5843   template <typename Range>
5844   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5845                             bool IsStringLocation, Range StringRange,
5846                             ArrayRef<FixItHint> Fixit = None);
5847 };
5848 
5849 } // namespace
5850 
5851 SourceRange CheckFormatHandler::getFormatStringRange() {
5852   return OrigFormatExpr->getSourceRange();
5853 }
5854 
5855 CharSourceRange CheckFormatHandler::
5856 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5857   SourceLocation Start = getLocationOfByte(startSpecifier);
5858   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5859 
5860   // Advance the end SourceLocation by one due to half-open ranges.
5861   End = End.getLocWithOffset(1);
5862 
5863   return CharSourceRange::getCharRange(Start, End);
5864 }
5865 
5866 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5867   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5868                                   S.getLangOpts(), S.Context.getTargetInfo());
5869 }
5870 
5871 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5872                                                    unsigned specifierLen){
5873   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5874                        getLocationOfByte(startSpecifier),
5875                        /*IsStringLocation*/true,
5876                        getSpecifierRange(startSpecifier, specifierLen));
5877 }
5878 
5879 void CheckFormatHandler::HandleInvalidLengthModifier(
5880     const analyze_format_string::FormatSpecifier &FS,
5881     const analyze_format_string::ConversionSpecifier &CS,
5882     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5883   using namespace analyze_format_string;
5884 
5885   const LengthModifier &LM = FS.getLengthModifier();
5886   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5887 
5888   // See if we know how to fix this length modifier.
5889   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5890   if (FixedLM) {
5891     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5892                          getLocationOfByte(LM.getStart()),
5893                          /*IsStringLocation*/true,
5894                          getSpecifierRange(startSpecifier, specifierLen));
5895 
5896     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5897       << FixedLM->toString()
5898       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5899 
5900   } else {
5901     FixItHint Hint;
5902     if (DiagID == diag::warn_format_nonsensical_length)
5903       Hint = FixItHint::CreateRemoval(LMRange);
5904 
5905     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5906                          getLocationOfByte(LM.getStart()),
5907                          /*IsStringLocation*/true,
5908                          getSpecifierRange(startSpecifier, specifierLen),
5909                          Hint);
5910   }
5911 }
5912 
5913 void CheckFormatHandler::HandleNonStandardLengthModifier(
5914     const analyze_format_string::FormatSpecifier &FS,
5915     const char *startSpecifier, unsigned specifierLen) {
5916   using namespace analyze_format_string;
5917 
5918   const LengthModifier &LM = FS.getLengthModifier();
5919   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5920 
5921   // See if we know how to fix this length modifier.
5922   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5923   if (FixedLM) {
5924     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5925                            << LM.toString() << 0,
5926                          getLocationOfByte(LM.getStart()),
5927                          /*IsStringLocation*/true,
5928                          getSpecifierRange(startSpecifier, specifierLen));
5929 
5930     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5931       << FixedLM->toString()
5932       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5933 
5934   } else {
5935     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5936                            << LM.toString() << 0,
5937                          getLocationOfByte(LM.getStart()),
5938                          /*IsStringLocation*/true,
5939                          getSpecifierRange(startSpecifier, specifierLen));
5940   }
5941 }
5942 
5943 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5944     const analyze_format_string::ConversionSpecifier &CS,
5945     const char *startSpecifier, unsigned specifierLen) {
5946   using namespace analyze_format_string;
5947 
5948   // See if we know how to fix this conversion specifier.
5949   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5950   if (FixedCS) {
5951     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5952                           << CS.toString() << /*conversion specifier*/1,
5953                          getLocationOfByte(CS.getStart()),
5954                          /*IsStringLocation*/true,
5955                          getSpecifierRange(startSpecifier, specifierLen));
5956 
5957     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5958     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5959       << FixedCS->toString()
5960       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5961   } else {
5962     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5963                           << CS.toString() << /*conversion specifier*/1,
5964                          getLocationOfByte(CS.getStart()),
5965                          /*IsStringLocation*/true,
5966                          getSpecifierRange(startSpecifier, specifierLen));
5967   }
5968 }
5969 
5970 void CheckFormatHandler::HandlePosition(const char *startPos,
5971                                         unsigned posLen) {
5972   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5973                                getLocationOfByte(startPos),
5974                                /*IsStringLocation*/true,
5975                                getSpecifierRange(startPos, posLen));
5976 }
5977 
5978 void
5979 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5980                                      analyze_format_string::PositionContext p) {
5981   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5982                          << (unsigned) p,
5983                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5984                        getSpecifierRange(startPos, posLen));
5985 }
5986 
5987 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5988                                             unsigned posLen) {
5989   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5990                                getLocationOfByte(startPos),
5991                                /*IsStringLocation*/true,
5992                                getSpecifierRange(startPos, posLen));
5993 }
5994 
5995 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5996   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5997     // The presence of a null character is likely an error.
5998     EmitFormatDiagnostic(
5999       S.PDiag(diag::warn_printf_format_string_contains_null_char),
6000       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6001       getFormatStringRange());
6002   }
6003 }
6004 
6005 // Note that this may return NULL if there was an error parsing or building
6006 // one of the argument expressions.
6007 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
6008   return Args[FirstDataArg + i];
6009 }
6010 
6011 void CheckFormatHandler::DoneProcessing() {
6012   // Does the number of data arguments exceed the number of
6013   // format conversions in the format string?
6014   if (!HasVAListArg) {
6015       // Find any arguments that weren't covered.
6016     CoveredArgs.flip();
6017     signed notCoveredArg = CoveredArgs.find_first();
6018     if (notCoveredArg >= 0) {
6019       assert((unsigned)notCoveredArg < NumDataArgs);
6020       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6021     } else {
6022       UncoveredArg.setAllCovered();
6023     }
6024   }
6025 }
6026 
6027 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6028                                    const Expr *ArgExpr) {
6029   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
6030          "Invalid state");
6031 
6032   if (!ArgExpr)
6033     return;
6034 
6035   SourceLocation Loc = ArgExpr->getLocStart();
6036 
6037   if (S.getSourceManager().isInSystemMacro(Loc))
6038     return;
6039 
6040   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6041   for (auto E : DiagnosticExprs)
6042     PDiag << E->getSourceRange();
6043 
6044   CheckFormatHandler::EmitFormatDiagnostic(
6045                                   S, IsFunctionCall, DiagnosticExprs[0],
6046                                   PDiag, Loc, /*IsStringLocation*/false,
6047                                   DiagnosticExprs[0]->getSourceRange());
6048 }
6049 
6050 bool
6051 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6052                                                      SourceLocation Loc,
6053                                                      const char *startSpec,
6054                                                      unsigned specifierLen,
6055                                                      const char *csStart,
6056                                                      unsigned csLen) {
6057   bool keepGoing = true;
6058   if (argIndex < NumDataArgs) {
6059     // Consider the argument coverered, even though the specifier doesn't
6060     // make sense.
6061     CoveredArgs.set(argIndex);
6062   }
6063   else {
6064     // If argIndex exceeds the number of data arguments we
6065     // don't issue a warning because that is just a cascade of warnings (and
6066     // they may have intended '%%' anyway). We don't want to continue processing
6067     // the format string after this point, however, as we will like just get
6068     // gibberish when trying to match arguments.
6069     keepGoing = false;
6070   }
6071 
6072   StringRef Specifier(csStart, csLen);
6073 
6074   // If the specifier in non-printable, it could be the first byte of a UTF-8
6075   // sequence. In that case, print the UTF-8 code point. If not, print the byte
6076   // hex value.
6077   std::string CodePointStr;
6078   if (!llvm::sys::locale::isPrint(*csStart)) {
6079     llvm::UTF32 CodePoint;
6080     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6081     const llvm::UTF8 *E =
6082         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6083     llvm::ConversionResult Result =
6084         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
6085 
6086     if (Result != llvm::conversionOK) {
6087       unsigned char FirstChar = *csStart;
6088       CodePoint = (llvm::UTF32)FirstChar;
6089     }
6090 
6091     llvm::raw_string_ostream OS(CodePointStr);
6092     if (CodePoint < 256)
6093       OS << "\\x" << llvm::format("%02x", CodePoint);
6094     else if (CodePoint <= 0xFFFF)
6095       OS << "\\u" << llvm::format("%04x", CodePoint);
6096     else
6097       OS << "\\U" << llvm::format("%08x", CodePoint);
6098     OS.flush();
6099     Specifier = CodePointStr;
6100   }
6101 
6102   EmitFormatDiagnostic(
6103       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6104       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6105 
6106   return keepGoing;
6107 }
6108 
6109 void
6110 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6111                                                       const char *startSpec,
6112                                                       unsigned specifierLen) {
6113   EmitFormatDiagnostic(
6114     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6115     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6116 }
6117 
6118 bool
6119 CheckFormatHandler::CheckNumArgs(
6120   const analyze_format_string::FormatSpecifier &FS,
6121   const analyze_format_string::ConversionSpecifier &CS,
6122   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6123 
6124   if (argIndex >= NumDataArgs) {
6125     PartialDiagnostic PDiag = FS.usesPositionalArg()
6126       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6127            << (argIndex+1) << NumDataArgs)
6128       : S.PDiag(diag::warn_printf_insufficient_data_args);
6129     EmitFormatDiagnostic(
6130       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6131       getSpecifierRange(startSpecifier, specifierLen));
6132 
6133     // Since more arguments than conversion tokens are given, by extension
6134     // all arguments are covered, so mark this as so.
6135     UncoveredArg.setAllCovered();
6136     return false;
6137   }
6138   return true;
6139 }
6140 
6141 template<typename Range>
6142 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6143                                               SourceLocation Loc,
6144                                               bool IsStringLocation,
6145                                               Range StringRange,
6146                                               ArrayRef<FixItHint> FixIt) {
6147   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
6148                        Loc, IsStringLocation, StringRange, FixIt);
6149 }
6150 
6151 /// If the format string is not within the function call, emit a note
6152 /// so that the function call and string are in diagnostic messages.
6153 ///
6154 /// \param InFunctionCall if true, the format string is within the function
6155 /// call and only one diagnostic message will be produced.  Otherwise, an
6156 /// extra note will be emitted pointing to location of the format string.
6157 ///
6158 /// \param ArgumentExpr the expression that is passed as the format string
6159 /// argument in the function call.  Used for getting locations when two
6160 /// diagnostics are emitted.
6161 ///
6162 /// \param PDiag the callee should already have provided any strings for the
6163 /// diagnostic message.  This function only adds locations and fixits
6164 /// to diagnostics.
6165 ///
6166 /// \param Loc primary location for diagnostic.  If two diagnostics are
6167 /// required, one will be at Loc and a new SourceLocation will be created for
6168 /// the other one.
6169 ///
6170 /// \param IsStringLocation if true, Loc points to the format string should be
6171 /// used for the note.  Otherwise, Loc points to the argument list and will
6172 /// be used with PDiag.
6173 ///
6174 /// \param StringRange some or all of the string to highlight.  This is
6175 /// templated so it can accept either a CharSourceRange or a SourceRange.
6176 ///
6177 /// \param FixIt optional fix it hint for the format string.
6178 template <typename Range>
6179 void CheckFormatHandler::EmitFormatDiagnostic(
6180     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6181     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6182     Range StringRange, ArrayRef<FixItHint> FixIt) {
6183   if (InFunctionCall) {
6184     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6185     D << StringRange;
6186     D << FixIt;
6187   } else {
6188     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6189       << ArgumentExpr->getSourceRange();
6190 
6191     const Sema::SemaDiagnosticBuilder &Note =
6192       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6193              diag::note_format_string_defined);
6194 
6195     Note << StringRange;
6196     Note << FixIt;
6197   }
6198 }
6199 
6200 //===--- CHECK: Printf format string checking ------------------------------===//
6201 
6202 namespace {
6203 
6204 class CheckPrintfHandler : public CheckFormatHandler {
6205 public:
6206   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
6207                      const Expr *origFormatExpr,
6208                      const Sema::FormatStringType type, unsigned firstDataArg,
6209                      unsigned numDataArgs, bool isObjC, const char *beg,
6210                      bool hasVAListArg, ArrayRef<const Expr *> Args,
6211                      unsigned formatIdx, bool inFunctionCall,
6212                      Sema::VariadicCallType CallType,
6213                      llvm::SmallBitVector &CheckedVarArgs,
6214                      UncoveredArgHandler &UncoveredArg)
6215       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6216                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6217                            inFunctionCall, CallType, CheckedVarArgs,
6218                            UncoveredArg) {}
6219 
6220   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6221 
6222   /// Returns true if '%@' specifiers are allowed in the format string.
6223   bool allowsObjCArg() const {
6224     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6225            FSType == Sema::FST_OSTrace;
6226   }
6227 
6228   bool HandleInvalidPrintfConversionSpecifier(
6229                                       const analyze_printf::PrintfSpecifier &FS,
6230                                       const char *startSpecifier,
6231                                       unsigned specifierLen) override;
6232 
6233   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6234                              const char *startSpecifier,
6235                              unsigned specifierLen) override;
6236   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6237                        const char *StartSpecifier,
6238                        unsigned SpecifierLen,
6239                        const Expr *E);
6240 
6241   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6242                     const char *startSpecifier, unsigned specifierLen);
6243   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6244                            const analyze_printf::OptionalAmount &Amt,
6245                            unsigned type,
6246                            const char *startSpecifier, unsigned specifierLen);
6247   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6248                   const analyze_printf::OptionalFlag &flag,
6249                   const char *startSpecifier, unsigned specifierLen);
6250   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6251                          const analyze_printf::OptionalFlag &ignoredFlag,
6252                          const analyze_printf::OptionalFlag &flag,
6253                          const char *startSpecifier, unsigned specifierLen);
6254   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
6255                            const Expr *E);
6256 
6257   void HandleEmptyObjCModifierFlag(const char *startFlag,
6258                                    unsigned flagLen) override;
6259 
6260   void HandleInvalidObjCModifierFlag(const char *startFlag,
6261                                             unsigned flagLen) override;
6262 
6263   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6264                                            const char *flagsEnd,
6265                                            const char *conversionPosition)
6266                                              override;
6267 };
6268 
6269 } // namespace
6270 
6271 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6272                                       const analyze_printf::PrintfSpecifier &FS,
6273                                       const char *startSpecifier,
6274                                       unsigned specifierLen) {
6275   const analyze_printf::PrintfConversionSpecifier &CS =
6276     FS.getConversionSpecifier();
6277 
6278   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6279                                           getLocationOfByte(CS.getStart()),
6280                                           startSpecifier, specifierLen,
6281                                           CS.getStart(), CS.getLength());
6282 }
6283 
6284 bool CheckPrintfHandler::HandleAmount(
6285                                const analyze_format_string::OptionalAmount &Amt,
6286                                unsigned k, const char *startSpecifier,
6287                                unsigned specifierLen) {
6288   if (Amt.hasDataArgument()) {
6289     if (!HasVAListArg) {
6290       unsigned argIndex = Amt.getArgIndex();
6291       if (argIndex >= NumDataArgs) {
6292         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6293                                << k,
6294                              getLocationOfByte(Amt.getStart()),
6295                              /*IsStringLocation*/true,
6296                              getSpecifierRange(startSpecifier, specifierLen));
6297         // Don't do any more checking.  We will just emit
6298         // spurious errors.
6299         return false;
6300       }
6301 
6302       // Type check the data argument.  It should be an 'int'.
6303       // Although not in conformance with C99, we also allow the argument to be
6304       // an 'unsigned int' as that is a reasonably safe case.  GCC also
6305       // doesn't emit a warning for that case.
6306       CoveredArgs.set(argIndex);
6307       const Expr *Arg = getDataArg(argIndex);
6308       if (!Arg)
6309         return false;
6310 
6311       QualType T = Arg->getType();
6312 
6313       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6314       assert(AT.isValid());
6315 
6316       if (!AT.matchesType(S.Context, T)) {
6317         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
6318                                << k << AT.getRepresentativeTypeName(S.Context)
6319                                << T << Arg->getSourceRange(),
6320                              getLocationOfByte(Amt.getStart()),
6321                              /*IsStringLocation*/true,
6322                              getSpecifierRange(startSpecifier, specifierLen));
6323         // Don't do any more checking.  We will just emit
6324         // spurious errors.
6325         return false;
6326       }
6327     }
6328   }
6329   return true;
6330 }
6331 
6332 void CheckPrintfHandler::HandleInvalidAmount(
6333                                       const analyze_printf::PrintfSpecifier &FS,
6334                                       const analyze_printf::OptionalAmount &Amt,
6335                                       unsigned type,
6336                                       const char *startSpecifier,
6337                                       unsigned specifierLen) {
6338   const analyze_printf::PrintfConversionSpecifier &CS =
6339     FS.getConversionSpecifier();
6340 
6341   FixItHint fixit =
6342     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6343       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6344                                  Amt.getConstantLength()))
6345       : FixItHint();
6346 
6347   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6348                          << type << CS.toString(),
6349                        getLocationOfByte(Amt.getStart()),
6350                        /*IsStringLocation*/true,
6351                        getSpecifierRange(startSpecifier, specifierLen),
6352                        fixit);
6353 }
6354 
6355 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6356                                     const analyze_printf::OptionalFlag &flag,
6357                                     const char *startSpecifier,
6358                                     unsigned specifierLen) {
6359   // Warn about pointless flag with a fixit removal.
6360   const analyze_printf::PrintfConversionSpecifier &CS =
6361     FS.getConversionSpecifier();
6362   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6363                          << flag.toString() << CS.toString(),
6364                        getLocationOfByte(flag.getPosition()),
6365                        /*IsStringLocation*/true,
6366                        getSpecifierRange(startSpecifier, specifierLen),
6367                        FixItHint::CreateRemoval(
6368                          getSpecifierRange(flag.getPosition(), 1)));
6369 }
6370 
6371 void CheckPrintfHandler::HandleIgnoredFlag(
6372                                 const analyze_printf::PrintfSpecifier &FS,
6373                                 const analyze_printf::OptionalFlag &ignoredFlag,
6374                                 const analyze_printf::OptionalFlag &flag,
6375                                 const char *startSpecifier,
6376                                 unsigned specifierLen) {
6377   // Warn about ignored flag with a fixit removal.
6378   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6379                          << ignoredFlag.toString() << flag.toString(),
6380                        getLocationOfByte(ignoredFlag.getPosition()),
6381                        /*IsStringLocation*/true,
6382                        getSpecifierRange(startSpecifier, specifierLen),
6383                        FixItHint::CreateRemoval(
6384                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
6385 }
6386 
6387 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6388                                                      unsigned flagLen) {
6389   // Warn about an empty flag.
6390   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6391                        getLocationOfByte(startFlag),
6392                        /*IsStringLocation*/true,
6393                        getSpecifierRange(startFlag, flagLen));
6394 }
6395 
6396 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6397                                                        unsigned flagLen) {
6398   // Warn about an invalid flag.
6399   auto Range = getSpecifierRange(startFlag, flagLen);
6400   StringRef flag(startFlag, flagLen);
6401   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6402                       getLocationOfByte(startFlag),
6403                       /*IsStringLocation*/true,
6404                       Range, FixItHint::CreateRemoval(Range));
6405 }
6406 
6407 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6408     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6409     // Warn about using '[...]' without a '@' conversion.
6410     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6411     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6412     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6413                          getLocationOfByte(conversionPosition),
6414                          /*IsStringLocation*/true,
6415                          Range, FixItHint::CreateRemoval(Range));
6416 }
6417 
6418 // Determines if the specified is a C++ class or struct containing
6419 // a member with the specified name and kind (e.g. a CXXMethodDecl named
6420 // "c_str()").
6421 template<typename MemberKind>
6422 static llvm::SmallPtrSet<MemberKind*, 1>
6423 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6424   const RecordType *RT = Ty->getAs<RecordType>();
6425   llvm::SmallPtrSet<MemberKind*, 1> Results;
6426 
6427   if (!RT)
6428     return Results;
6429   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
6430   if (!RD || !RD->getDefinition())
6431     return Results;
6432 
6433   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
6434                  Sema::LookupMemberName);
6435   R.suppressDiagnostics();
6436 
6437   // We just need to include all members of the right kind turned up by the
6438   // filter, at this point.
6439   if (S.LookupQualifiedName(R, RT->getDecl()))
6440     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6441       NamedDecl *decl = (*I)->getUnderlyingDecl();
6442       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6443         Results.insert(FK);
6444     }
6445   return Results;
6446 }
6447 
6448 /// Check if we could call '.c_str()' on an object.
6449 ///
6450 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6451 /// allow the call, or if it would be ambiguous).
6452 bool Sema::hasCStrMethod(const Expr *E) {
6453   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6454 
6455   MethodSet Results =
6456       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6457   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6458        MI != ME; ++MI)
6459     if ((*MI)->getMinRequiredArguments() == 0)
6460       return true;
6461   return false;
6462 }
6463 
6464 // Check if a (w)string was passed when a (w)char* was needed, and offer a
6465 // better diagnostic if so. AT is assumed to be valid.
6466 // Returns true when a c_str() conversion method is found.
6467 bool CheckPrintfHandler::checkForCStrMembers(
6468     const analyze_printf::ArgType &AT, const Expr *E) {
6469   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6470 
6471   MethodSet Results =
6472       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6473 
6474   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6475        MI != ME; ++MI) {
6476     const CXXMethodDecl *Method = *MI;
6477     if (Method->getMinRequiredArguments() == 0 &&
6478         AT.matchesType(S.Context, Method->getReturnType())) {
6479       // FIXME: Suggest parens if the expression needs them.
6480       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
6481       S.Diag(E->getLocStart(), diag::note_printf_c_str)
6482           << "c_str()"
6483           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6484       return true;
6485     }
6486   }
6487 
6488   return false;
6489 }
6490 
6491 bool
6492 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
6493                                             &FS,
6494                                           const char *startSpecifier,
6495                                           unsigned specifierLen) {
6496   using namespace analyze_format_string;
6497   using namespace analyze_printf;
6498 
6499   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
6500 
6501   if (FS.consumesDataArgument()) {
6502     if (atFirstArg) {
6503         atFirstArg = false;
6504         usesPositionalArgs = FS.usesPositionalArg();
6505     }
6506     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6507       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6508                                         startSpecifier, specifierLen);
6509       return false;
6510     }
6511   }
6512 
6513   // First check if the field width, precision, and conversion specifier
6514   // have matching data arguments.
6515   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6516                     startSpecifier, specifierLen)) {
6517     return false;
6518   }
6519 
6520   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6521                     startSpecifier, specifierLen)) {
6522     return false;
6523   }
6524 
6525   if (!CS.consumesDataArgument()) {
6526     // FIXME: Technically specifying a precision or field width here
6527     // makes no sense.  Worth issuing a warning at some point.
6528     return true;
6529   }
6530 
6531   // Consume the argument.
6532   unsigned argIndex = FS.getArgIndex();
6533   if (argIndex < NumDataArgs) {
6534     // The check to see if the argIndex is valid will come later.
6535     // We set the bit here because we may exit early from this
6536     // function if we encounter some other error.
6537     CoveredArgs.set(argIndex);
6538   }
6539 
6540   // FreeBSD kernel extensions.
6541   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6542       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6543     // We need at least two arguments.
6544     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6545       return false;
6546 
6547     // Claim the second argument.
6548     CoveredArgs.set(argIndex + 1);
6549 
6550     // Type check the first argument (int for %b, pointer for %D)
6551     const Expr *Ex = getDataArg(argIndex);
6552     const analyze_printf::ArgType &AT =
6553       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6554         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6555     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6556       EmitFormatDiagnostic(
6557         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6558         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6559         << false << Ex->getSourceRange(),
6560         Ex->getLocStart(), /*IsStringLocation*/false,
6561         getSpecifierRange(startSpecifier, specifierLen));
6562 
6563     // Type check the second argument (char * for both %b and %D)
6564     Ex = getDataArg(argIndex + 1);
6565     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6566     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6567       EmitFormatDiagnostic(
6568         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6569         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6570         << false << Ex->getSourceRange(),
6571         Ex->getLocStart(), /*IsStringLocation*/false,
6572         getSpecifierRange(startSpecifier, specifierLen));
6573 
6574      return true;
6575   }
6576 
6577   // Check for using an Objective-C specific conversion specifier
6578   // in a non-ObjC literal.
6579   if (!allowsObjCArg() && CS.isObjCArg()) {
6580     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6581                                                   specifierLen);
6582   }
6583 
6584   // %P can only be used with os_log.
6585   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6586     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6587                                                   specifierLen);
6588   }
6589 
6590   // %n is not allowed with os_log.
6591   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6592     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6593                          getLocationOfByte(CS.getStart()),
6594                          /*IsStringLocation*/ false,
6595                          getSpecifierRange(startSpecifier, specifierLen));
6596 
6597     return true;
6598   }
6599 
6600   // Only scalars are allowed for os_trace.
6601   if (FSType == Sema::FST_OSTrace &&
6602       (CS.getKind() == ConversionSpecifier::PArg ||
6603        CS.getKind() == ConversionSpecifier::sArg ||
6604        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6605     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6606                                                   specifierLen);
6607   }
6608 
6609   // Check for use of public/private annotation outside of os_log().
6610   if (FSType != Sema::FST_OSLog) {
6611     if (FS.isPublic().isSet()) {
6612       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6613                                << "public",
6614                            getLocationOfByte(FS.isPublic().getPosition()),
6615                            /*IsStringLocation*/ false,
6616                            getSpecifierRange(startSpecifier, specifierLen));
6617     }
6618     if (FS.isPrivate().isSet()) {
6619       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6620                                << "private",
6621                            getLocationOfByte(FS.isPrivate().getPosition()),
6622                            /*IsStringLocation*/ false,
6623                            getSpecifierRange(startSpecifier, specifierLen));
6624     }
6625   }
6626 
6627   // Check for invalid use of field width
6628   if (!FS.hasValidFieldWidth()) {
6629     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6630         startSpecifier, specifierLen);
6631   }
6632 
6633   // Check for invalid use of precision
6634   if (!FS.hasValidPrecision()) {
6635     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6636         startSpecifier, specifierLen);
6637   }
6638 
6639   // Precision is mandatory for %P specifier.
6640   if (CS.getKind() == ConversionSpecifier::PArg &&
6641       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6642     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6643                          getLocationOfByte(startSpecifier),
6644                          /*IsStringLocation*/ false,
6645                          getSpecifierRange(startSpecifier, specifierLen));
6646   }
6647 
6648   // Check each flag does not conflict with any other component.
6649   if (!FS.hasValidThousandsGroupingPrefix())
6650     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6651   if (!FS.hasValidLeadingZeros())
6652     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6653   if (!FS.hasValidPlusPrefix())
6654     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6655   if (!FS.hasValidSpacePrefix())
6656     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6657   if (!FS.hasValidAlternativeForm())
6658     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6659   if (!FS.hasValidLeftJustified())
6660     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6661 
6662   // Check that flags are not ignored by another flag
6663   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6664     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6665         startSpecifier, specifierLen);
6666   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6667     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6668             startSpecifier, specifierLen);
6669 
6670   // Check the length modifier is valid with the given conversion specifier.
6671   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6672     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6673                                 diag::warn_format_nonsensical_length);
6674   else if (!FS.hasStandardLengthModifier())
6675     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6676   else if (!FS.hasStandardLengthConversionCombination())
6677     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6678                                 diag::warn_format_non_standard_conversion_spec);
6679 
6680   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6681     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6682 
6683   // The remaining checks depend on the data arguments.
6684   if (HasVAListArg)
6685     return true;
6686 
6687   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6688     return false;
6689 
6690   const Expr *Arg = getDataArg(argIndex);
6691   if (!Arg)
6692     return true;
6693 
6694   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6695 }
6696 
6697 static bool requiresParensToAddCast(const Expr *E) {
6698   // FIXME: We should have a general way to reason about operator
6699   // precedence and whether parens are actually needed here.
6700   // Take care of a few common cases where they aren't.
6701   const Expr *Inside = E->IgnoreImpCasts();
6702   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6703     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6704 
6705   switch (Inside->getStmtClass()) {
6706   case Stmt::ArraySubscriptExprClass:
6707   case Stmt::CallExprClass:
6708   case Stmt::CharacterLiteralClass:
6709   case Stmt::CXXBoolLiteralExprClass:
6710   case Stmt::DeclRefExprClass:
6711   case Stmt::FloatingLiteralClass:
6712   case Stmt::IntegerLiteralClass:
6713   case Stmt::MemberExprClass:
6714   case Stmt::ObjCArrayLiteralClass:
6715   case Stmt::ObjCBoolLiteralExprClass:
6716   case Stmt::ObjCBoxedExprClass:
6717   case Stmt::ObjCDictionaryLiteralClass:
6718   case Stmt::ObjCEncodeExprClass:
6719   case Stmt::ObjCIvarRefExprClass:
6720   case Stmt::ObjCMessageExprClass:
6721   case Stmt::ObjCPropertyRefExprClass:
6722   case Stmt::ObjCStringLiteralClass:
6723   case Stmt::ObjCSubscriptRefExprClass:
6724   case Stmt::ParenExprClass:
6725   case Stmt::StringLiteralClass:
6726   case Stmt::UnaryOperatorClass:
6727     return false;
6728   default:
6729     return true;
6730   }
6731 }
6732 
6733 static std::pair<QualType, StringRef>
6734 shouldNotPrintDirectly(const ASTContext &Context,
6735                        QualType IntendedTy,
6736                        const Expr *E) {
6737   // Use a 'while' to peel off layers of typedefs.
6738   QualType TyTy = IntendedTy;
6739   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6740     StringRef Name = UserTy->getDecl()->getName();
6741     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6742       .Case("CFIndex", Context.getNSIntegerType())
6743       .Case("NSInteger", Context.getNSIntegerType())
6744       .Case("NSUInteger", Context.getNSUIntegerType())
6745       .Case("SInt32", Context.IntTy)
6746       .Case("UInt32", Context.UnsignedIntTy)
6747       .Default(QualType());
6748 
6749     if (!CastTy.isNull())
6750       return std::make_pair(CastTy, Name);
6751 
6752     TyTy = UserTy->desugar();
6753   }
6754 
6755   // Strip parens if necessary.
6756   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6757     return shouldNotPrintDirectly(Context,
6758                                   PE->getSubExpr()->getType(),
6759                                   PE->getSubExpr());
6760 
6761   // If this is a conditional expression, then its result type is constructed
6762   // via usual arithmetic conversions and thus there might be no necessary
6763   // typedef sugar there.  Recurse to operands to check for NSInteger &
6764   // Co. usage condition.
6765   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6766     QualType TrueTy, FalseTy;
6767     StringRef TrueName, FalseName;
6768 
6769     std::tie(TrueTy, TrueName) =
6770       shouldNotPrintDirectly(Context,
6771                              CO->getTrueExpr()->getType(),
6772                              CO->getTrueExpr());
6773     std::tie(FalseTy, FalseName) =
6774       shouldNotPrintDirectly(Context,
6775                              CO->getFalseExpr()->getType(),
6776                              CO->getFalseExpr());
6777 
6778     if (TrueTy == FalseTy)
6779       return std::make_pair(TrueTy, TrueName);
6780     else if (TrueTy.isNull())
6781       return std::make_pair(FalseTy, FalseName);
6782     else if (FalseTy.isNull())
6783       return std::make_pair(TrueTy, TrueName);
6784   }
6785 
6786   return std::make_pair(QualType(), StringRef());
6787 }
6788 
6789 bool
6790 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6791                                     const char *StartSpecifier,
6792                                     unsigned SpecifierLen,
6793                                     const Expr *E) {
6794   using namespace analyze_format_string;
6795   using namespace analyze_printf;
6796 
6797   // Now type check the data expression that matches the
6798   // format specifier.
6799   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6800   if (!AT.isValid())
6801     return true;
6802 
6803   QualType ExprTy = E->getType();
6804   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6805     ExprTy = TET->getUnderlyingExpr()->getType();
6806   }
6807 
6808   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6809 
6810   if (match == analyze_printf::ArgType::Match) {
6811     return true;
6812   }
6813 
6814   // Look through argument promotions for our error message's reported type.
6815   // This includes the integral and floating promotions, but excludes array
6816   // and function pointer decay; seeing that an argument intended to be a
6817   // string has type 'char [6]' is probably more confusing than 'char *'.
6818   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6819     if (ICE->getCastKind() == CK_IntegralCast ||
6820         ICE->getCastKind() == CK_FloatingCast) {
6821       E = ICE->getSubExpr();
6822       ExprTy = E->getType();
6823 
6824       // Check if we didn't match because of an implicit cast from a 'char'
6825       // or 'short' to an 'int'.  This is done because printf is a varargs
6826       // function.
6827       if (ICE->getType() == S.Context.IntTy ||
6828           ICE->getType() == S.Context.UnsignedIntTy) {
6829         // All further checking is done on the subexpression.
6830         if (AT.matchesType(S.Context, ExprTy))
6831           return true;
6832       }
6833     }
6834   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6835     // Special case for 'a', which has type 'int' in C.
6836     // Note, however, that we do /not/ want to treat multibyte constants like
6837     // 'MooV' as characters! This form is deprecated but still exists.
6838     if (ExprTy == S.Context.IntTy)
6839       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6840         ExprTy = S.Context.CharTy;
6841   }
6842 
6843   // Look through enums to their underlying type.
6844   bool IsEnum = false;
6845   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6846     ExprTy = EnumTy->getDecl()->getIntegerType();
6847     IsEnum = true;
6848   }
6849 
6850   // %C in an Objective-C context prints a unichar, not a wchar_t.
6851   // If the argument is an integer of some kind, believe the %C and suggest
6852   // a cast instead of changing the conversion specifier.
6853   QualType IntendedTy = ExprTy;
6854   if (isObjCContext() &&
6855       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6856     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6857         !ExprTy->isCharType()) {
6858       // 'unichar' is defined as a typedef of unsigned short, but we should
6859       // prefer using the typedef if it is visible.
6860       IntendedTy = S.Context.UnsignedShortTy;
6861 
6862       // While we are here, check if the value is an IntegerLiteral that happens
6863       // to be within the valid range.
6864       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6865         const llvm::APInt &V = IL->getValue();
6866         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6867           return true;
6868       }
6869 
6870       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6871                           Sema::LookupOrdinaryName);
6872       if (S.LookupName(Result, S.getCurScope())) {
6873         NamedDecl *ND = Result.getFoundDecl();
6874         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6875           if (TD->getUnderlyingType() == IntendedTy)
6876             IntendedTy = S.Context.getTypedefType(TD);
6877       }
6878     }
6879   }
6880 
6881   // Special-case some of Darwin's platform-independence types by suggesting
6882   // casts to primitive types that are known to be large enough.
6883   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6884   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6885     QualType CastTy;
6886     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6887     if (!CastTy.isNull()) {
6888       IntendedTy = CastTy;
6889       ShouldNotPrintDirectly = true;
6890     }
6891   }
6892 
6893   // We may be able to offer a FixItHint if it is a supported type.
6894   PrintfSpecifier fixedFS = FS;
6895   bool success =
6896       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6897 
6898   if (success) {
6899     // Get the fix string from the fixed format specifier
6900     SmallString<16> buf;
6901     llvm::raw_svector_ostream os(buf);
6902     fixedFS.toString(os);
6903 
6904     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6905 
6906     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6907       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6908       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6909         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6910       }
6911       // In this case, the specifier is wrong and should be changed to match
6912       // the argument.
6913       EmitFormatDiagnostic(S.PDiag(diag)
6914                                << AT.getRepresentativeTypeName(S.Context)
6915                                << IntendedTy << IsEnum << E->getSourceRange(),
6916                            E->getLocStart(),
6917                            /*IsStringLocation*/ false, SpecRange,
6918                            FixItHint::CreateReplacement(SpecRange, os.str()));
6919     } else {
6920       // The canonical type for formatting this value is different from the
6921       // actual type of the expression. (This occurs, for example, with Darwin's
6922       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6923       // should be printed as 'long' for 64-bit compatibility.)
6924       // Rather than emitting a normal format/argument mismatch, we want to
6925       // add a cast to the recommended type (and correct the format string
6926       // if necessary).
6927       SmallString<16> CastBuf;
6928       llvm::raw_svector_ostream CastFix(CastBuf);
6929       CastFix << "(";
6930       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6931       CastFix << ")";
6932 
6933       SmallVector<FixItHint,4> Hints;
6934       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6935         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6936 
6937       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6938         // If there's already a cast present, just replace it.
6939         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6940         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6941 
6942       } else if (!requiresParensToAddCast(E)) {
6943         // If the expression has high enough precedence,
6944         // just write the C-style cast.
6945         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6946                                                    CastFix.str()));
6947       } else {
6948         // Otherwise, add parens around the expression as well as the cast.
6949         CastFix << "(";
6950         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6951                                                    CastFix.str()));
6952 
6953         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6954         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6955       }
6956 
6957       if (ShouldNotPrintDirectly) {
6958         // The expression has a type that should not be printed directly.
6959         // We extract the name from the typedef because we don't want to show
6960         // the underlying type in the diagnostic.
6961         StringRef Name;
6962         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6963           Name = TypedefTy->getDecl()->getName();
6964         else
6965           Name = CastTyName;
6966         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6967                                << Name << IntendedTy << IsEnum
6968                                << E->getSourceRange(),
6969                              E->getLocStart(), /*IsStringLocation=*/false,
6970                              SpecRange, Hints);
6971       } else {
6972         // In this case, the expression could be printed using a different
6973         // specifier, but we've decided that the specifier is probably correct
6974         // and we should cast instead. Just use the normal warning message.
6975         EmitFormatDiagnostic(
6976           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6977             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6978             << E->getSourceRange(),
6979           E->getLocStart(), /*IsStringLocation*/false,
6980           SpecRange, Hints);
6981       }
6982     }
6983   } else {
6984     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6985                                                    SpecifierLen);
6986     // Since the warning for passing non-POD types to variadic functions
6987     // was deferred until now, we emit a warning for non-POD
6988     // arguments here.
6989     switch (S.isValidVarArgType(ExprTy)) {
6990     case Sema::VAK_Valid:
6991     case Sema::VAK_ValidInCXX11: {
6992       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6993       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6994         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6995       }
6996 
6997       EmitFormatDiagnostic(
6998           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6999                         << IsEnum << CSR << E->getSourceRange(),
7000           E->getLocStart(), /*IsStringLocation*/ false, CSR);
7001       break;
7002     }
7003     case Sema::VAK_Undefined:
7004     case Sema::VAK_MSVCUndefined:
7005       EmitFormatDiagnostic(
7006         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
7007           << S.getLangOpts().CPlusPlus11
7008           << ExprTy
7009           << CallType
7010           << AT.getRepresentativeTypeName(S.Context)
7011           << CSR
7012           << E->getSourceRange(),
7013         E->getLocStart(), /*IsStringLocation*/false, CSR);
7014       checkForCStrMembers(AT, E);
7015       break;
7016 
7017     case Sema::VAK_Invalid:
7018       if (ExprTy->isObjCObjectType())
7019         EmitFormatDiagnostic(
7020           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
7021             << S.getLangOpts().CPlusPlus11
7022             << ExprTy
7023             << CallType
7024             << AT.getRepresentativeTypeName(S.Context)
7025             << CSR
7026             << E->getSourceRange(),
7027           E->getLocStart(), /*IsStringLocation*/false, CSR);
7028       else
7029         // FIXME: If this is an initializer list, suggest removing the braces
7030         // or inserting a cast to the target type.
7031         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
7032           << isa<InitListExpr>(E) << ExprTy << CallType
7033           << AT.getRepresentativeTypeName(S.Context)
7034           << E->getSourceRange();
7035       break;
7036     }
7037 
7038     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7039            "format string specifier index out of range");
7040     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
7041   }
7042 
7043   return true;
7044 }
7045 
7046 //===--- CHECK: Scanf format string checking ------------------------------===//
7047 
7048 namespace {
7049 
7050 class CheckScanfHandler : public CheckFormatHandler {
7051 public:
7052   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
7053                     const Expr *origFormatExpr, Sema::FormatStringType type,
7054                     unsigned firstDataArg, unsigned numDataArgs,
7055                     const char *beg, bool hasVAListArg,
7056                     ArrayRef<const Expr *> Args, unsigned formatIdx,
7057                     bool inFunctionCall, Sema::VariadicCallType CallType,
7058                     llvm::SmallBitVector &CheckedVarArgs,
7059                     UncoveredArgHandler &UncoveredArg)
7060       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7061                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7062                            inFunctionCall, CallType, CheckedVarArgs,
7063                            UncoveredArg) {}
7064 
7065   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7066                             const char *startSpecifier,
7067                             unsigned specifierLen) override;
7068 
7069   bool HandleInvalidScanfConversionSpecifier(
7070           const analyze_scanf::ScanfSpecifier &FS,
7071           const char *startSpecifier,
7072           unsigned specifierLen) override;
7073 
7074   void HandleIncompleteScanList(const char *start, const char *end) override;
7075 };
7076 
7077 } // namespace
7078 
7079 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7080                                                  const char *end) {
7081   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7082                        getLocationOfByte(end), /*IsStringLocation*/true,
7083                        getSpecifierRange(start, end - start));
7084 }
7085 
7086 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7087                                         const analyze_scanf::ScanfSpecifier &FS,
7088                                         const char *startSpecifier,
7089                                         unsigned specifierLen) {
7090   const analyze_scanf::ScanfConversionSpecifier &CS =
7091     FS.getConversionSpecifier();
7092 
7093   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7094                                           getLocationOfByte(CS.getStart()),
7095                                           startSpecifier, specifierLen,
7096                                           CS.getStart(), CS.getLength());
7097 }
7098 
7099 bool CheckScanfHandler::HandleScanfSpecifier(
7100                                        const analyze_scanf::ScanfSpecifier &FS,
7101                                        const char *startSpecifier,
7102                                        unsigned specifierLen) {
7103   using namespace analyze_scanf;
7104   using namespace analyze_format_string;
7105 
7106   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
7107 
7108   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
7109   // be used to decide if we are using positional arguments consistently.
7110   if (FS.consumesDataArgument()) {
7111     if (atFirstArg) {
7112       atFirstArg = false;
7113       usesPositionalArgs = FS.usesPositionalArg();
7114     }
7115     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7116       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7117                                         startSpecifier, specifierLen);
7118       return false;
7119     }
7120   }
7121 
7122   // Check if the field with is non-zero.
7123   const OptionalAmount &Amt = FS.getFieldWidth();
7124   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7125     if (Amt.getConstantAmount() == 0) {
7126       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7127                                                    Amt.getConstantLength());
7128       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7129                            getLocationOfByte(Amt.getStart()),
7130                            /*IsStringLocation*/true, R,
7131                            FixItHint::CreateRemoval(R));
7132     }
7133   }
7134 
7135   if (!FS.consumesDataArgument()) {
7136     // FIXME: Technically specifying a precision or field width here
7137     // makes no sense.  Worth issuing a warning at some point.
7138     return true;
7139   }
7140 
7141   // Consume the argument.
7142   unsigned argIndex = FS.getArgIndex();
7143   if (argIndex < NumDataArgs) {
7144       // The check to see if the argIndex is valid will come later.
7145       // We set the bit here because we may exit early from this
7146       // function if we encounter some other error.
7147     CoveredArgs.set(argIndex);
7148   }
7149 
7150   // Check the length modifier is valid with the given conversion specifier.
7151   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
7152     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7153                                 diag::warn_format_nonsensical_length);
7154   else if (!FS.hasStandardLengthModifier())
7155     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7156   else if (!FS.hasStandardLengthConversionCombination())
7157     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7158                                 diag::warn_format_non_standard_conversion_spec);
7159 
7160   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7161     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7162 
7163   // The remaining checks depend on the data arguments.
7164   if (HasVAListArg)
7165     return true;
7166 
7167   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7168     return false;
7169 
7170   // Check that the argument type matches the format specifier.
7171   const Expr *Ex = getDataArg(argIndex);
7172   if (!Ex)
7173     return true;
7174 
7175   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
7176 
7177   if (!AT.isValid()) {
7178     return true;
7179   }
7180 
7181   analyze_format_string::ArgType::MatchKind match =
7182       AT.matchesType(S.Context, Ex->getType());
7183   if (match == analyze_format_string::ArgType::Match) {
7184     return true;
7185   }
7186 
7187   ScanfSpecifier fixedFS = FS;
7188   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
7189                                  S.getLangOpts(), S.Context);
7190 
7191   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
7192   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
7193     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7194   }
7195 
7196   if (success) {
7197     // Get the fix string from the fixed format specifier.
7198     SmallString<128> buf;
7199     llvm::raw_svector_ostream os(buf);
7200     fixedFS.toString(os);
7201 
7202     EmitFormatDiagnostic(
7203         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
7204                       << Ex->getType() << false << Ex->getSourceRange(),
7205         Ex->getLocStart(),
7206         /*IsStringLocation*/ false,
7207         getSpecifierRange(startSpecifier, specifierLen),
7208         FixItHint::CreateReplacement(
7209             getSpecifierRange(startSpecifier, specifierLen), os.str()));
7210   } else {
7211     EmitFormatDiagnostic(S.PDiag(diag)
7212                              << AT.getRepresentativeTypeName(S.Context)
7213                              << Ex->getType() << false << Ex->getSourceRange(),
7214                          Ex->getLocStart(),
7215                          /*IsStringLocation*/ false,
7216                          getSpecifierRange(startSpecifier, specifierLen));
7217   }
7218 
7219   return true;
7220 }
7221 
7222 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7223                               const Expr *OrigFormatExpr,
7224                               ArrayRef<const Expr *> Args,
7225                               bool HasVAListArg, unsigned format_idx,
7226                               unsigned firstDataArg,
7227                               Sema::FormatStringType Type,
7228                               bool inFunctionCall,
7229                               Sema::VariadicCallType CallType,
7230                               llvm::SmallBitVector &CheckedVarArgs,
7231                               UncoveredArgHandler &UncoveredArg) {
7232   // CHECK: is the format string a wide literal?
7233   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
7234     CheckFormatHandler::EmitFormatDiagnostic(
7235       S, inFunctionCall, Args[format_idx],
7236       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
7237       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
7238     return;
7239   }
7240 
7241   // Str - The format string.  NOTE: this is NOT null-terminated!
7242   StringRef StrRef = FExpr->getString();
7243   const char *Str = StrRef.data();
7244   // Account for cases where the string literal is truncated in a declaration.
7245   const ConstantArrayType *T =
7246     S.Context.getAsConstantArrayType(FExpr->getType());
7247   assert(T && "String literal not of constant array type!");
7248   size_t TypeSize = T->getSize().getZExtValue();
7249   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7250   const unsigned numDataArgs = Args.size() - firstDataArg;
7251 
7252   // Emit a warning if the string literal is truncated and does not contain an
7253   // embedded null character.
7254   if (TypeSize <= StrRef.size() &&
7255       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7256     CheckFormatHandler::EmitFormatDiagnostic(
7257         S, inFunctionCall, Args[format_idx],
7258         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
7259         FExpr->getLocStart(),
7260         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7261     return;
7262   }
7263 
7264   // CHECK: empty format string?
7265   if (StrLen == 0 && numDataArgs > 0) {
7266     CheckFormatHandler::EmitFormatDiagnostic(
7267       S, inFunctionCall, Args[format_idx],
7268       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
7269       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
7270     return;
7271   }
7272 
7273   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
7274       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7275       Type == Sema::FST_OSTrace) {
7276     CheckPrintfHandler H(
7277         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7278         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7279         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7280         CheckedVarArgs, UncoveredArg);
7281 
7282     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
7283                                                   S.getLangOpts(),
7284                                                   S.Context.getTargetInfo(),
7285                                             Type == Sema::FST_FreeBSDKPrintf))
7286       H.DoneProcessing();
7287   } else if (Type == Sema::FST_Scanf) {
7288     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7289                         numDataArgs, Str, HasVAListArg, Args, format_idx,
7290                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
7291 
7292     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
7293                                                  S.getLangOpts(),
7294                                                  S.Context.getTargetInfo()))
7295       H.DoneProcessing();
7296   } // TODO: handle other formats
7297 }
7298 
7299 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7300   // Str - The format string.  NOTE: this is NOT null-terminated!
7301   StringRef StrRef = FExpr->getString();
7302   const char *Str = StrRef.data();
7303   // Account for cases where the string literal is truncated in a declaration.
7304   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7305   assert(T && "String literal not of constant array type!");
7306   size_t TypeSize = T->getSize().getZExtValue();
7307   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7308   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7309                                                          getLangOpts(),
7310                                                          Context.getTargetInfo());
7311 }
7312 
7313 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7314 
7315 // Returns the related absolute value function that is larger, of 0 if one
7316 // does not exist.
7317 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7318   switch (AbsFunction) {
7319   default:
7320     return 0;
7321 
7322   case Builtin::BI__builtin_abs:
7323     return Builtin::BI__builtin_labs;
7324   case Builtin::BI__builtin_labs:
7325     return Builtin::BI__builtin_llabs;
7326   case Builtin::BI__builtin_llabs:
7327     return 0;
7328 
7329   case Builtin::BI__builtin_fabsf:
7330     return Builtin::BI__builtin_fabs;
7331   case Builtin::BI__builtin_fabs:
7332     return Builtin::BI__builtin_fabsl;
7333   case Builtin::BI__builtin_fabsl:
7334     return 0;
7335 
7336   case Builtin::BI__builtin_cabsf:
7337     return Builtin::BI__builtin_cabs;
7338   case Builtin::BI__builtin_cabs:
7339     return Builtin::BI__builtin_cabsl;
7340   case Builtin::BI__builtin_cabsl:
7341     return 0;
7342 
7343   case Builtin::BIabs:
7344     return Builtin::BIlabs;
7345   case Builtin::BIlabs:
7346     return Builtin::BIllabs;
7347   case Builtin::BIllabs:
7348     return 0;
7349 
7350   case Builtin::BIfabsf:
7351     return Builtin::BIfabs;
7352   case Builtin::BIfabs:
7353     return Builtin::BIfabsl;
7354   case Builtin::BIfabsl:
7355     return 0;
7356 
7357   case Builtin::BIcabsf:
7358    return Builtin::BIcabs;
7359   case Builtin::BIcabs:
7360     return Builtin::BIcabsl;
7361   case Builtin::BIcabsl:
7362     return 0;
7363   }
7364 }
7365 
7366 // Returns the argument type of the absolute value function.
7367 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7368                                              unsigned AbsType) {
7369   if (AbsType == 0)
7370     return QualType();
7371 
7372   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7373   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7374   if (Error != ASTContext::GE_None)
7375     return QualType();
7376 
7377   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7378   if (!FT)
7379     return QualType();
7380 
7381   if (FT->getNumParams() != 1)
7382     return QualType();
7383 
7384   return FT->getParamType(0);
7385 }
7386 
7387 // Returns the best absolute value function, or zero, based on type and
7388 // current absolute value function.
7389 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7390                                    unsigned AbsFunctionKind) {
7391   unsigned BestKind = 0;
7392   uint64_t ArgSize = Context.getTypeSize(ArgType);
7393   for (unsigned Kind = AbsFunctionKind; Kind != 0;
7394        Kind = getLargerAbsoluteValueFunction(Kind)) {
7395     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7396     if (Context.getTypeSize(ParamType) >= ArgSize) {
7397       if (BestKind == 0)
7398         BestKind = Kind;
7399       else if (Context.hasSameType(ParamType, ArgType)) {
7400         BestKind = Kind;
7401         break;
7402       }
7403     }
7404   }
7405   return BestKind;
7406 }
7407 
7408 enum AbsoluteValueKind {
7409   AVK_Integer,
7410   AVK_Floating,
7411   AVK_Complex
7412 };
7413 
7414 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7415   if (T->isIntegralOrEnumerationType())
7416     return AVK_Integer;
7417   if (T->isRealFloatingType())
7418     return AVK_Floating;
7419   if (T->isAnyComplexType())
7420     return AVK_Complex;
7421 
7422   llvm_unreachable("Type not integer, floating, or complex");
7423 }
7424 
7425 // Changes the absolute value function to a different type.  Preserves whether
7426 // the function is a builtin.
7427 static unsigned changeAbsFunction(unsigned AbsKind,
7428                                   AbsoluteValueKind ValueKind) {
7429   switch (ValueKind) {
7430   case AVK_Integer:
7431     switch (AbsKind) {
7432     default:
7433       return 0;
7434     case Builtin::BI__builtin_fabsf:
7435     case Builtin::BI__builtin_fabs:
7436     case Builtin::BI__builtin_fabsl:
7437     case Builtin::BI__builtin_cabsf:
7438     case Builtin::BI__builtin_cabs:
7439     case Builtin::BI__builtin_cabsl:
7440       return Builtin::BI__builtin_abs;
7441     case Builtin::BIfabsf:
7442     case Builtin::BIfabs:
7443     case Builtin::BIfabsl:
7444     case Builtin::BIcabsf:
7445     case Builtin::BIcabs:
7446     case Builtin::BIcabsl:
7447       return Builtin::BIabs;
7448     }
7449   case AVK_Floating:
7450     switch (AbsKind) {
7451     default:
7452       return 0;
7453     case Builtin::BI__builtin_abs:
7454     case Builtin::BI__builtin_labs:
7455     case Builtin::BI__builtin_llabs:
7456     case Builtin::BI__builtin_cabsf:
7457     case Builtin::BI__builtin_cabs:
7458     case Builtin::BI__builtin_cabsl:
7459       return Builtin::BI__builtin_fabsf;
7460     case Builtin::BIabs:
7461     case Builtin::BIlabs:
7462     case Builtin::BIllabs:
7463     case Builtin::BIcabsf:
7464     case Builtin::BIcabs:
7465     case Builtin::BIcabsl:
7466       return Builtin::BIfabsf;
7467     }
7468   case AVK_Complex:
7469     switch (AbsKind) {
7470     default:
7471       return 0;
7472     case Builtin::BI__builtin_abs:
7473     case Builtin::BI__builtin_labs:
7474     case Builtin::BI__builtin_llabs:
7475     case Builtin::BI__builtin_fabsf:
7476     case Builtin::BI__builtin_fabs:
7477     case Builtin::BI__builtin_fabsl:
7478       return Builtin::BI__builtin_cabsf;
7479     case Builtin::BIabs:
7480     case Builtin::BIlabs:
7481     case Builtin::BIllabs:
7482     case Builtin::BIfabsf:
7483     case Builtin::BIfabs:
7484     case Builtin::BIfabsl:
7485       return Builtin::BIcabsf;
7486     }
7487   }
7488   llvm_unreachable("Unable to convert function");
7489 }
7490 
7491 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
7492   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7493   if (!FnInfo)
7494     return 0;
7495 
7496   switch (FDecl->getBuiltinID()) {
7497   default:
7498     return 0;
7499   case Builtin::BI__builtin_abs:
7500   case Builtin::BI__builtin_fabs:
7501   case Builtin::BI__builtin_fabsf:
7502   case Builtin::BI__builtin_fabsl:
7503   case Builtin::BI__builtin_labs:
7504   case Builtin::BI__builtin_llabs:
7505   case Builtin::BI__builtin_cabs:
7506   case Builtin::BI__builtin_cabsf:
7507   case Builtin::BI__builtin_cabsl:
7508   case Builtin::BIabs:
7509   case Builtin::BIlabs:
7510   case Builtin::BIllabs:
7511   case Builtin::BIfabs:
7512   case Builtin::BIfabsf:
7513   case Builtin::BIfabsl:
7514   case Builtin::BIcabs:
7515   case Builtin::BIcabsf:
7516   case Builtin::BIcabsl:
7517     return FDecl->getBuiltinID();
7518   }
7519   llvm_unreachable("Unknown Builtin type");
7520 }
7521 
7522 // If the replacement is valid, emit a note with replacement function.
7523 // Additionally, suggest including the proper header if not already included.
7524 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
7525                             unsigned AbsKind, QualType ArgType) {
7526   bool EmitHeaderHint = true;
7527   const char *HeaderName = nullptr;
7528   const char *FunctionName = nullptr;
7529   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7530     FunctionName = "std::abs";
7531     if (ArgType->isIntegralOrEnumerationType()) {
7532       HeaderName = "cstdlib";
7533     } else if (ArgType->isRealFloatingType()) {
7534       HeaderName = "cmath";
7535     } else {
7536       llvm_unreachable("Invalid Type");
7537     }
7538 
7539     // Lookup all std::abs
7540     if (NamespaceDecl *Std = S.getStdNamespace()) {
7541       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
7542       R.suppressDiagnostics();
7543       S.LookupQualifiedName(R, Std);
7544 
7545       for (const auto *I : R) {
7546         const FunctionDecl *FDecl = nullptr;
7547         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7548           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7549         } else {
7550           FDecl = dyn_cast<FunctionDecl>(I);
7551         }
7552         if (!FDecl)
7553           continue;
7554 
7555         // Found std::abs(), check that they are the right ones.
7556         if (FDecl->getNumParams() != 1)
7557           continue;
7558 
7559         // Check that the parameter type can handle the argument.
7560         QualType ParamType = FDecl->getParamDecl(0)->getType();
7561         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7562             S.Context.getTypeSize(ArgType) <=
7563                 S.Context.getTypeSize(ParamType)) {
7564           // Found a function, don't need the header hint.
7565           EmitHeaderHint = false;
7566           break;
7567         }
7568       }
7569     }
7570   } else {
7571     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
7572     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7573 
7574     if (HeaderName) {
7575       DeclarationName DN(&S.Context.Idents.get(FunctionName));
7576       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7577       R.suppressDiagnostics();
7578       S.LookupName(R, S.getCurScope());
7579 
7580       if (R.isSingleResult()) {
7581         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7582         if (FD && FD->getBuiltinID() == AbsKind) {
7583           EmitHeaderHint = false;
7584         } else {
7585           return;
7586         }
7587       } else if (!R.empty()) {
7588         return;
7589       }
7590     }
7591   }
7592 
7593   S.Diag(Loc, diag::note_replace_abs_function)
7594       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7595 
7596   if (!HeaderName)
7597     return;
7598 
7599   if (!EmitHeaderHint)
7600     return;
7601 
7602   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7603                                                     << FunctionName;
7604 }
7605 
7606 template <std::size_t StrLen>
7607 static bool IsStdFunction(const FunctionDecl *FDecl,
7608                           const char (&Str)[StrLen]) {
7609   if (!FDecl)
7610     return false;
7611   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7612     return false;
7613   if (!FDecl->isInStdNamespace())
7614     return false;
7615 
7616   return true;
7617 }
7618 
7619 // Warn when using the wrong abs() function.
7620 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7621                                       const FunctionDecl *FDecl) {
7622   if (Call->getNumArgs() != 1)
7623     return;
7624 
7625   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7626   bool IsStdAbs = IsStdFunction(FDecl, "abs");
7627   if (AbsKind == 0 && !IsStdAbs)
7628     return;
7629 
7630   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7631   QualType ParamType = Call->getArg(0)->getType();
7632 
7633   // Unsigned types cannot be negative.  Suggest removing the absolute value
7634   // function call.
7635   if (ArgType->isUnsignedIntegerType()) {
7636     const char *FunctionName =
7637         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7638     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7639     Diag(Call->getExprLoc(), diag::note_remove_abs)
7640         << FunctionName
7641         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7642     return;
7643   }
7644 
7645   // Taking the absolute value of a pointer is very suspicious, they probably
7646   // wanted to index into an array, dereference a pointer, call a function, etc.
7647   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7648     unsigned DiagType = 0;
7649     if (ArgType->isFunctionType())
7650       DiagType = 1;
7651     else if (ArgType->isArrayType())
7652       DiagType = 2;
7653 
7654     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7655     return;
7656   }
7657 
7658   // std::abs has overloads which prevent most of the absolute value problems
7659   // from occurring.
7660   if (IsStdAbs)
7661     return;
7662 
7663   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7664   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7665 
7666   // The argument and parameter are the same kind.  Check if they are the right
7667   // size.
7668   if (ArgValueKind == ParamValueKind) {
7669     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7670       return;
7671 
7672     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7673     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7674         << FDecl << ArgType << ParamType;
7675 
7676     if (NewAbsKind == 0)
7677       return;
7678 
7679     emitReplacement(*this, Call->getExprLoc(),
7680                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7681     return;
7682   }
7683 
7684   // ArgValueKind != ParamValueKind
7685   // The wrong type of absolute value function was used.  Attempt to find the
7686   // proper one.
7687   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7688   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7689   if (NewAbsKind == 0)
7690     return;
7691 
7692   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7693       << FDecl << ParamValueKind << ArgValueKind;
7694 
7695   emitReplacement(*this, Call->getExprLoc(),
7696                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7697 }
7698 
7699 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7700 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7701                                 const FunctionDecl *FDecl) {
7702   if (!Call || !FDecl) return;
7703 
7704   // Ignore template specializations and macros.
7705   if (inTemplateInstantiation()) return;
7706   if (Call->getExprLoc().isMacroID()) return;
7707 
7708   // Only care about the one template argument, two function parameter std::max
7709   if (Call->getNumArgs() != 2) return;
7710   if (!IsStdFunction(FDecl, "max")) return;
7711   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7712   if (!ArgList) return;
7713   if (ArgList->size() != 1) return;
7714 
7715   // Check that template type argument is unsigned integer.
7716   const auto& TA = ArgList->get(0);
7717   if (TA.getKind() != TemplateArgument::Type) return;
7718   QualType ArgType = TA.getAsType();
7719   if (!ArgType->isUnsignedIntegerType()) return;
7720 
7721   // See if either argument is a literal zero.
7722   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7723     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7724     if (!MTE) return false;
7725     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7726     if (!Num) return false;
7727     if (Num->getValue() != 0) return false;
7728     return true;
7729   };
7730 
7731   const Expr *FirstArg = Call->getArg(0);
7732   const Expr *SecondArg = Call->getArg(1);
7733   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7734   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7735 
7736   // Only warn when exactly one argument is zero.
7737   if (IsFirstArgZero == IsSecondArgZero) return;
7738 
7739   SourceRange FirstRange = FirstArg->getSourceRange();
7740   SourceRange SecondRange = SecondArg->getSourceRange();
7741 
7742   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7743 
7744   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7745       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7746 
7747   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7748   SourceRange RemovalRange;
7749   if (IsFirstArgZero) {
7750     RemovalRange = SourceRange(FirstRange.getBegin(),
7751                                SecondRange.getBegin().getLocWithOffset(-1));
7752   } else {
7753     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7754                                SecondRange.getEnd());
7755   }
7756 
7757   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7758         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7759         << FixItHint::CreateRemoval(RemovalRange);
7760 }
7761 
7762 //===--- CHECK: Standard memory functions ---------------------------------===//
7763 
7764 /// Takes the expression passed to the size_t parameter of functions
7765 /// such as memcmp, strncat, etc and warns if it's a comparison.
7766 ///
7767 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7768 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7769                                            IdentifierInfo *FnName,
7770                                            SourceLocation FnLoc,
7771                                            SourceLocation RParenLoc) {
7772   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7773   if (!Size)
7774     return false;
7775 
7776   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7777   if (!Size->isComparisonOp() && !Size->isLogicalOp())
7778     return false;
7779 
7780   SourceRange SizeRange = Size->getSourceRange();
7781   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7782       << SizeRange << FnName;
7783   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7784       << FnName << FixItHint::CreateInsertion(
7785                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7786       << FixItHint::CreateRemoval(RParenLoc);
7787   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7788       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7789       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7790                                     ")");
7791 
7792   return true;
7793 }
7794 
7795 /// Determine whether the given type is or contains a dynamic class type
7796 /// (e.g., whether it has a vtable).
7797 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7798                                                      bool &IsContained) {
7799   // Look through array types while ignoring qualifiers.
7800   const Type *Ty = T->getBaseElementTypeUnsafe();
7801   IsContained = false;
7802 
7803   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7804   RD = RD ? RD->getDefinition() : nullptr;
7805   if (!RD || RD->isInvalidDecl())
7806     return nullptr;
7807 
7808   if (RD->isDynamicClass())
7809     return RD;
7810 
7811   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7812   // It's impossible for a class to transitively contain itself by value, so
7813   // infinite recursion is impossible.
7814   for (auto *FD : RD->fields()) {
7815     bool SubContained;
7816     if (const CXXRecordDecl *ContainedRD =
7817             getContainedDynamicClass(FD->getType(), SubContained)) {
7818       IsContained = true;
7819       return ContainedRD;
7820     }
7821   }
7822 
7823   return nullptr;
7824 }
7825 
7826 /// If E is a sizeof expression, returns its argument expression,
7827 /// otherwise returns NULL.
7828 static const Expr *getSizeOfExprArg(const Expr *E) {
7829   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7830       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7831     if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
7832       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7833 
7834   return nullptr;
7835 }
7836 
7837 /// If E is a sizeof expression, returns its argument type.
7838 static QualType getSizeOfArgType(const Expr *E) {
7839   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7840       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7841     if (SizeOf->getKind() == UETT_SizeOf)
7842       return SizeOf->getTypeOfArgument();
7843 
7844   return QualType();
7845 }
7846 
7847 namespace {
7848 
7849 struct SearchNonTrivialToInitializeField
7850     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7851   using Super =
7852       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7853 
7854   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7855 
7856   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7857                      SourceLocation SL) {
7858     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7859       asDerived().visitArray(PDIK, AT, SL);
7860       return;
7861     }
7862 
7863     Super::visitWithKind(PDIK, FT, SL);
7864   }
7865 
7866   void visitARCStrong(QualType FT, SourceLocation SL) {
7867     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7868   }
7869   void visitARCWeak(QualType FT, SourceLocation SL) {
7870     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7871   }
7872   void visitStruct(QualType FT, SourceLocation SL) {
7873     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7874       visit(FD->getType(), FD->getLocation());
7875   }
7876   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7877                   const ArrayType *AT, SourceLocation SL) {
7878     visit(getContext().getBaseElementType(AT), SL);
7879   }
7880   void visitTrivial(QualType FT, SourceLocation SL) {}
7881 
7882   static void diag(QualType RT, const Expr *E, Sema &S) {
7883     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7884   }
7885 
7886   ASTContext &getContext() { return S.getASTContext(); }
7887 
7888   const Expr *E;
7889   Sema &S;
7890 };
7891 
7892 struct SearchNonTrivialToCopyField
7893     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7894   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7895 
7896   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7897 
7898   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7899                      SourceLocation SL) {
7900     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7901       asDerived().visitArray(PCK, AT, SL);
7902       return;
7903     }
7904 
7905     Super::visitWithKind(PCK, FT, SL);
7906   }
7907 
7908   void visitARCStrong(QualType FT, SourceLocation SL) {
7909     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7910   }
7911   void visitARCWeak(QualType FT, SourceLocation SL) {
7912     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7913   }
7914   void visitStruct(QualType FT, SourceLocation SL) {
7915     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7916       visit(FD->getType(), FD->getLocation());
7917   }
7918   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7919                   SourceLocation SL) {
7920     visit(getContext().getBaseElementType(AT), SL);
7921   }
7922   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7923                 SourceLocation SL) {}
7924   void visitTrivial(QualType FT, SourceLocation SL) {}
7925   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7926 
7927   static void diag(QualType RT, const Expr *E, Sema &S) {
7928     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7929   }
7930 
7931   ASTContext &getContext() { return S.getASTContext(); }
7932 
7933   const Expr *E;
7934   Sema &S;
7935 };
7936 
7937 }
7938 
7939 /// Check for dangerous or invalid arguments to memset().
7940 ///
7941 /// This issues warnings on known problematic, dangerous or unspecified
7942 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7943 /// function calls.
7944 ///
7945 /// \param Call The call expression to diagnose.
7946 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7947                                    unsigned BId,
7948                                    IdentifierInfo *FnName) {
7949   assert(BId != 0);
7950 
7951   // It is possible to have a non-standard definition of memset.  Validate
7952   // we have enough arguments, and if not, abort further checking.
7953   unsigned ExpectedNumArgs =
7954       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7955   if (Call->getNumArgs() < ExpectedNumArgs)
7956     return;
7957 
7958   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7959                       BId == Builtin::BIstrndup ? 1 : 2);
7960   unsigned LenArg =
7961       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7962   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7963 
7964   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7965                                      Call->getLocStart(), Call->getRParenLoc()))
7966     return;
7967 
7968   // We have special checking when the length is a sizeof expression.
7969   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7970   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7971   llvm::FoldingSetNodeID SizeOfArgID;
7972 
7973   // Although widely used, 'bzero' is not a standard function. Be more strict
7974   // with the argument types before allowing diagnostics and only allow the
7975   // form bzero(ptr, sizeof(...)).
7976   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7977   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7978     return;
7979 
7980   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7981     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7982     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7983 
7984     QualType DestTy = Dest->getType();
7985     QualType PointeeTy;
7986     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7987       PointeeTy = DestPtrTy->getPointeeType();
7988 
7989       // Never warn about void type pointers. This can be used to suppress
7990       // false positives.
7991       if (PointeeTy->isVoidType())
7992         continue;
7993 
7994       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7995       // actually comparing the expressions for equality. Because computing the
7996       // expression IDs can be expensive, we only do this if the diagnostic is
7997       // enabled.
7998       if (SizeOfArg &&
7999           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
8000                            SizeOfArg->getExprLoc())) {
8001         // We only compute IDs for expressions if the warning is enabled, and
8002         // cache the sizeof arg's ID.
8003         if (SizeOfArgID == llvm::FoldingSetNodeID())
8004           SizeOfArg->Profile(SizeOfArgID, Context, true);
8005         llvm::FoldingSetNodeID DestID;
8006         Dest->Profile(DestID, Context, true);
8007         if (DestID == SizeOfArgID) {
8008           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
8009           //       over sizeof(src) as well.
8010           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
8011           StringRef ReadableName = FnName->getName();
8012 
8013           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
8014             if (UnaryOp->getOpcode() == UO_AddrOf)
8015               ActionIdx = 1; // If its an address-of operator, just remove it.
8016           if (!PointeeTy->isIncompleteType() &&
8017               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
8018             ActionIdx = 2; // If the pointee's size is sizeof(char),
8019                            // suggest an explicit length.
8020 
8021           // If the function is defined as a builtin macro, do not show macro
8022           // expansion.
8023           SourceLocation SL = SizeOfArg->getExprLoc();
8024           SourceRange DSR = Dest->getSourceRange();
8025           SourceRange SSR = SizeOfArg->getSourceRange();
8026           SourceManager &SM = getSourceManager();
8027 
8028           if (SM.isMacroArgExpansion(SL)) {
8029             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
8030             SL = SM.getSpellingLoc(SL);
8031             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
8032                              SM.getSpellingLoc(DSR.getEnd()));
8033             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
8034                              SM.getSpellingLoc(SSR.getEnd()));
8035           }
8036 
8037           DiagRuntimeBehavior(SL, SizeOfArg,
8038                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
8039                                 << ReadableName
8040                                 << PointeeTy
8041                                 << DestTy
8042                                 << DSR
8043                                 << SSR);
8044           DiagRuntimeBehavior(SL, SizeOfArg,
8045                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
8046                                 << ActionIdx
8047                                 << SSR);
8048 
8049           break;
8050         }
8051       }
8052 
8053       // Also check for cases where the sizeof argument is the exact same
8054       // type as the memory argument, and where it points to a user-defined
8055       // record type.
8056       if (SizeOfArgTy != QualType()) {
8057         if (PointeeTy->isRecordType() &&
8058             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
8059           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
8060                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
8061                                 << FnName << SizeOfArgTy << ArgIdx
8062                                 << PointeeTy << Dest->getSourceRange()
8063                                 << LenExpr->getSourceRange());
8064           break;
8065         }
8066       }
8067     } else if (DestTy->isArrayType()) {
8068       PointeeTy = DestTy;
8069     }
8070 
8071     if (PointeeTy == QualType())
8072       continue;
8073 
8074     // Always complain about dynamic classes.
8075     bool IsContained;
8076     if (const CXXRecordDecl *ContainedRD =
8077             getContainedDynamicClass(PointeeTy, IsContained)) {
8078 
8079       unsigned OperationType = 0;
8080       // "overwritten" if we're warning about the destination for any call
8081       // but memcmp; otherwise a verb appropriate to the call.
8082       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
8083         if (BId == Builtin::BImemcpy)
8084           OperationType = 1;
8085         else if(BId == Builtin::BImemmove)
8086           OperationType = 2;
8087         else if (BId == Builtin::BImemcmp)
8088           OperationType = 3;
8089       }
8090 
8091       DiagRuntimeBehavior(
8092         Dest->getExprLoc(), Dest,
8093         PDiag(diag::warn_dyn_class_memaccess)
8094           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
8095           << FnName << IsContained << ContainedRD << OperationType
8096           << Call->getCallee()->getSourceRange());
8097     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
8098              BId != Builtin::BImemset)
8099       DiagRuntimeBehavior(
8100         Dest->getExprLoc(), Dest,
8101         PDiag(diag::warn_arc_object_memaccess)
8102           << ArgIdx << FnName << PointeeTy
8103           << Call->getCallee()->getSourceRange());
8104     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
8105       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
8106           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
8107         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8108                             PDiag(diag::warn_cstruct_memaccess)
8109                                 << ArgIdx << FnName << PointeeTy << 0);
8110         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
8111       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
8112                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
8113         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8114                             PDiag(diag::warn_cstruct_memaccess)
8115                                 << ArgIdx << FnName << PointeeTy << 1);
8116         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
8117       } else {
8118         continue;
8119       }
8120     } else
8121       continue;
8122 
8123     DiagRuntimeBehavior(
8124       Dest->getExprLoc(), Dest,
8125       PDiag(diag::note_bad_memaccess_silence)
8126         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
8127     break;
8128   }
8129 }
8130 
8131 // A little helper routine: ignore addition and subtraction of integer literals.
8132 // This intentionally does not ignore all integer constant expressions because
8133 // we don't want to remove sizeof().
8134 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
8135   Ex = Ex->IgnoreParenCasts();
8136 
8137   while (true) {
8138     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
8139     if (!BO || !BO->isAdditiveOp())
8140       break;
8141 
8142     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
8143     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
8144 
8145     if (isa<IntegerLiteral>(RHS))
8146       Ex = LHS;
8147     else if (isa<IntegerLiteral>(LHS))
8148       Ex = RHS;
8149     else
8150       break;
8151   }
8152 
8153   return Ex;
8154 }
8155 
8156 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
8157                                                       ASTContext &Context) {
8158   // Only handle constant-sized or VLAs, but not flexible members.
8159   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
8160     // Only issue the FIXIT for arrays of size > 1.
8161     if (CAT->getSize().getSExtValue() <= 1)
8162       return false;
8163   } else if (!Ty->isVariableArrayType()) {
8164     return false;
8165   }
8166   return true;
8167 }
8168 
8169 // Warn if the user has made the 'size' argument to strlcpy or strlcat
8170 // be the size of the source, instead of the destination.
8171 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
8172                                     IdentifierInfo *FnName) {
8173 
8174   // Don't crash if the user has the wrong number of arguments
8175   unsigned NumArgs = Call->getNumArgs();
8176   if ((NumArgs != 3) && (NumArgs != 4))
8177     return;
8178 
8179   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
8180   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
8181   const Expr *CompareWithSrc = nullptr;
8182 
8183   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
8184                                      Call->getLocStart(), Call->getRParenLoc()))
8185     return;
8186 
8187   // Look for 'strlcpy(dst, x, sizeof(x))'
8188   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8189     CompareWithSrc = Ex;
8190   else {
8191     // Look for 'strlcpy(dst, x, strlen(x))'
8192     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
8193       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
8194           SizeCall->getNumArgs() == 1)
8195         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
8196     }
8197   }
8198 
8199   if (!CompareWithSrc)
8200     return;
8201 
8202   // Determine if the argument to sizeof/strlen is equal to the source
8203   // argument.  In principle there's all kinds of things you could do
8204   // here, for instance creating an == expression and evaluating it with
8205   // EvaluateAsBooleanCondition, but this uses a more direct technique:
8206   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8207   if (!SrcArgDRE)
8208     return;
8209 
8210   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8211   if (!CompareWithSrcDRE ||
8212       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8213     return;
8214 
8215   const Expr *OriginalSizeArg = Call->getArg(2);
8216   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8217     << OriginalSizeArg->getSourceRange() << FnName;
8218 
8219   // Output a FIXIT hint if the destination is an array (rather than a
8220   // pointer to an array).  This could be enhanced to handle some
8221   // pointers if we know the actual size, like if DstArg is 'array+2'
8222   // we could say 'sizeof(array)-2'.
8223   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
8224   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
8225     return;
8226 
8227   SmallString<128> sizeString;
8228   llvm::raw_svector_ostream OS(sizeString);
8229   OS << "sizeof(";
8230   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
8231   OS << ")";
8232 
8233   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8234     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8235                                     OS.str());
8236 }
8237 
8238 /// Check if two expressions refer to the same declaration.
8239 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8240   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8241     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8242       return D1->getDecl() == D2->getDecl();
8243   return false;
8244 }
8245 
8246 static const Expr *getStrlenExprArg(const Expr *E) {
8247   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8248     const FunctionDecl *FD = CE->getDirectCallee();
8249     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
8250       return nullptr;
8251     return CE->getArg(0)->IgnoreParenCasts();
8252   }
8253   return nullptr;
8254 }
8255 
8256 // Warn on anti-patterns as the 'size' argument to strncat.
8257 // The correct size argument should look like following:
8258 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8259 void Sema::CheckStrncatArguments(const CallExpr *CE,
8260                                  IdentifierInfo *FnName) {
8261   // Don't crash if the user has the wrong number of arguments.
8262   if (CE->getNumArgs() < 3)
8263     return;
8264   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8265   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8266   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8267 
8268   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8269                                      CE->getRParenLoc()))
8270     return;
8271 
8272   // Identify common expressions, which are wrongly used as the size argument
8273   // to strncat and may lead to buffer overflows.
8274   unsigned PatternType = 0;
8275   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8276     // - sizeof(dst)
8277     if (referToTheSameDecl(SizeOfArg, DstArg))
8278       PatternType = 1;
8279     // - sizeof(src)
8280     else if (referToTheSameDecl(SizeOfArg, SrcArg))
8281       PatternType = 2;
8282   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8283     if (BE->getOpcode() == BO_Sub) {
8284       const Expr *L = BE->getLHS()->IgnoreParenCasts();
8285       const Expr *R = BE->getRHS()->IgnoreParenCasts();
8286       // - sizeof(dst) - strlen(dst)
8287       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8288           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8289         PatternType = 1;
8290       // - sizeof(src) - (anything)
8291       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8292         PatternType = 2;
8293     }
8294   }
8295 
8296   if (PatternType == 0)
8297     return;
8298 
8299   // Generate the diagnostic.
8300   SourceLocation SL = LenArg->getLocStart();
8301   SourceRange SR = LenArg->getSourceRange();
8302   SourceManager &SM = getSourceManager();
8303 
8304   // If the function is defined as a builtin macro, do not show macro expansion.
8305   if (SM.isMacroArgExpansion(SL)) {
8306     SL = SM.getSpellingLoc(SL);
8307     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8308                      SM.getSpellingLoc(SR.getEnd()));
8309   }
8310 
8311   // Check if the destination is an array (rather than a pointer to an array).
8312   QualType DstTy = DstArg->getType();
8313   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8314                                                                     Context);
8315   if (!isKnownSizeArray) {
8316     if (PatternType == 1)
8317       Diag(SL, diag::warn_strncat_wrong_size) << SR;
8318     else
8319       Diag(SL, diag::warn_strncat_src_size) << SR;
8320     return;
8321   }
8322 
8323   if (PatternType == 1)
8324     Diag(SL, diag::warn_strncat_large_size) << SR;
8325   else
8326     Diag(SL, diag::warn_strncat_src_size) << SR;
8327 
8328   SmallString<128> sizeString;
8329   llvm::raw_svector_ostream OS(sizeString);
8330   OS << "sizeof(";
8331   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
8332   OS << ") - ";
8333   OS << "strlen(";
8334   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
8335   OS << ") - 1";
8336 
8337   Diag(SL, diag::note_strncat_wrong_size)
8338     << FixItHint::CreateReplacement(SR, OS.str());
8339 }
8340 
8341 //===--- CHECK: Return Address of Stack Variable --------------------------===//
8342 
8343 static const Expr *EvalVal(const Expr *E,
8344                            SmallVectorImpl<const DeclRefExpr *> &refVars,
8345                            const Decl *ParentDecl);
8346 static const Expr *EvalAddr(const Expr *E,
8347                             SmallVectorImpl<const DeclRefExpr *> &refVars,
8348                             const Decl *ParentDecl);
8349 
8350 /// CheckReturnStackAddr - Check if a return statement returns the address
8351 ///   of a stack variable.
8352 static void
8353 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8354                      SourceLocation ReturnLoc) {
8355   const Expr *stackE = nullptr;
8356   SmallVector<const DeclRefExpr *, 8> refVars;
8357 
8358   // Perform checking for returned stack addresses, local blocks,
8359   // label addresses or references to temporaries.
8360   if (lhsType->isPointerType() ||
8361       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
8362     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
8363   } else if (lhsType->isReferenceType()) {
8364     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
8365   }
8366 
8367   if (!stackE)
8368     return; // Nothing suspicious was found.
8369 
8370   // Parameters are initialized in the calling scope, so taking the address
8371   // of a parameter reference doesn't need a warning.
8372   for (auto *DRE : refVars)
8373     if (isa<ParmVarDecl>(DRE->getDecl()))
8374       return;
8375 
8376   SourceLocation diagLoc;
8377   SourceRange diagRange;
8378   if (refVars.empty()) {
8379     diagLoc = stackE->getLocStart();
8380     diagRange = stackE->getSourceRange();
8381   } else {
8382     // We followed through a reference variable. 'stackE' contains the
8383     // problematic expression but we will warn at the return statement pointing
8384     // at the reference variable. We will later display the "trail" of
8385     // reference variables using notes.
8386     diagLoc = refVars[0]->getLocStart();
8387     diagRange = refVars[0]->getSourceRange();
8388   }
8389 
8390   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8391     // address of local var
8392     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
8393      << DR->getDecl()->getDeclName() << diagRange;
8394   } else if (isa<BlockExpr>(stackE)) { // local block.
8395     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
8396   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
8397     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
8398   } else { // local temporary.
8399     // If there is an LValue->RValue conversion, then the value of the
8400     // reference type is used, not the reference.
8401     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8402       if (ICE->getCastKind() == CK_LValueToRValue) {
8403         return;
8404       }
8405     }
8406     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8407      << lhsType->isReferenceType() << diagRange;
8408   }
8409 
8410   // Display the "trail" of reference variables that we followed until we
8411   // found the problematic expression using notes.
8412   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
8413     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
8414     // If this var binds to another reference var, show the range of the next
8415     // var, otherwise the var binds to the problematic expression, in which case
8416     // show the range of the expression.
8417     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8418                                     : stackE->getSourceRange();
8419     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8420         << VD->getDeclName() << range;
8421   }
8422 }
8423 
8424 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8425 ///  check if the expression in a return statement evaluates to an address
8426 ///  to a location on the stack, a local block, an address of a label, or a
8427 ///  reference to local temporary. The recursion is used to traverse the
8428 ///  AST of the return expression, with recursion backtracking when we
8429 ///  encounter a subexpression that (1) clearly does not lead to one of the
8430 ///  above problematic expressions (2) is something we cannot determine leads to
8431 ///  a problematic expression based on such local checking.
8432 ///
8433 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
8434 ///  the expression that they point to. Such variables are added to the
8435 ///  'refVars' vector so that we know what the reference variable "trail" was.
8436 ///
8437 ///  EvalAddr processes expressions that are pointers that are used as
8438 ///  references (and not L-values).  EvalVal handles all other values.
8439 ///  At the base case of the recursion is a check for the above problematic
8440 ///  expressions.
8441 ///
8442 ///  This implementation handles:
8443 ///
8444 ///   * pointer-to-pointer casts
8445 ///   * implicit conversions from array references to pointers
8446 ///   * taking the address of fields
8447 ///   * arbitrary interplay between "&" and "*" operators
8448 ///   * pointer arithmetic from an address of a stack variable
8449 ///   * taking the address of an array element where the array is on the stack
8450 static const Expr *EvalAddr(const Expr *E,
8451                             SmallVectorImpl<const DeclRefExpr *> &refVars,
8452                             const Decl *ParentDecl) {
8453   if (E->isTypeDependent())
8454     return nullptr;
8455 
8456   // We should only be called for evaluating pointer expressions.
8457   assert((E->getType()->isAnyPointerType() ||
8458           E->getType()->isBlockPointerType() ||
8459           E->getType()->isObjCQualifiedIdType()) &&
8460          "EvalAddr only works on pointers");
8461 
8462   E = E->IgnoreParens();
8463 
8464   // Our "symbolic interpreter" is just a dispatch off the currently
8465   // viewed AST node.  We then recursively traverse the AST by calling
8466   // EvalAddr and EvalVal appropriately.
8467   switch (E->getStmtClass()) {
8468   case Stmt::DeclRefExprClass: {
8469     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8470 
8471     // If we leave the immediate function, the lifetime isn't about to end.
8472     if (DR->refersToEnclosingVariableOrCapture())
8473       return nullptr;
8474 
8475     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
8476       // If this is a reference variable, follow through to the expression that
8477       // it points to.
8478       if (V->hasLocalStorage() &&
8479           V->getType()->isReferenceType() && V->hasInit()) {
8480         // Add the reference variable to the "trail".
8481         refVars.push_back(DR);
8482         return EvalAddr(V->getInit(), refVars, ParentDecl);
8483       }
8484 
8485     return nullptr;
8486   }
8487 
8488   case Stmt::UnaryOperatorClass: {
8489     // The only unary operator that make sense to handle here
8490     // is AddrOf.  All others don't make sense as pointers.
8491     const UnaryOperator *U = cast<UnaryOperator>(E);
8492 
8493     if (U->getOpcode() == UO_AddrOf)
8494       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
8495     return nullptr;
8496   }
8497 
8498   case Stmt::BinaryOperatorClass: {
8499     // Handle pointer arithmetic.  All other binary operators are not valid
8500     // in this context.
8501     const BinaryOperator *B = cast<BinaryOperator>(E);
8502     BinaryOperatorKind op = B->getOpcode();
8503 
8504     if (op != BO_Add && op != BO_Sub)
8505       return nullptr;
8506 
8507     const Expr *Base = B->getLHS();
8508 
8509     // Determine which argument is the real pointer base.  It could be
8510     // the RHS argument instead of the LHS.
8511     if (!Base->getType()->isPointerType())
8512       Base = B->getRHS();
8513 
8514     assert(Base->getType()->isPointerType());
8515     return EvalAddr(Base, refVars, ParentDecl);
8516   }
8517 
8518   // For conditional operators we need to see if either the LHS or RHS are
8519   // valid DeclRefExpr*s.  If one of them is valid, we return it.
8520   case Stmt::ConditionalOperatorClass: {
8521     const ConditionalOperator *C = cast<ConditionalOperator>(E);
8522 
8523     // Handle the GNU extension for missing LHS.
8524     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
8525     if (const Expr *LHSExpr = C->getLHS()) {
8526       // In C++, we can have a throw-expression, which has 'void' type.
8527       if (!LHSExpr->getType()->isVoidType())
8528         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
8529           return LHS;
8530     }
8531 
8532     // In C++, we can have a throw-expression, which has 'void' type.
8533     if (C->getRHS()->getType()->isVoidType())
8534       return nullptr;
8535 
8536     return EvalAddr(C->getRHS(), refVars, ParentDecl);
8537   }
8538 
8539   case Stmt::BlockExprClass:
8540     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
8541       return E; // local block.
8542     return nullptr;
8543 
8544   case Stmt::AddrLabelExprClass:
8545     return E; // address of label.
8546 
8547   case Stmt::ExprWithCleanupsClass:
8548     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8549                     ParentDecl);
8550 
8551   // For casts, we need to handle conversions from arrays to
8552   // pointer values, and pointer-to-pointer conversions.
8553   case Stmt::ImplicitCastExprClass:
8554   case Stmt::CStyleCastExprClass:
8555   case Stmt::CXXFunctionalCastExprClass:
8556   case Stmt::ObjCBridgedCastExprClass:
8557   case Stmt::CXXStaticCastExprClass:
8558   case Stmt::CXXDynamicCastExprClass:
8559   case Stmt::CXXConstCastExprClass:
8560   case Stmt::CXXReinterpretCastExprClass: {
8561     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
8562     switch (cast<CastExpr>(E)->getCastKind()) {
8563     case CK_LValueToRValue:
8564     case CK_NoOp:
8565     case CK_BaseToDerived:
8566     case CK_DerivedToBase:
8567     case CK_UncheckedDerivedToBase:
8568     case CK_Dynamic:
8569     case CK_CPointerToObjCPointerCast:
8570     case CK_BlockPointerToObjCPointerCast:
8571     case CK_AnyPointerToBlockPointerCast:
8572       return EvalAddr(SubExpr, refVars, ParentDecl);
8573 
8574     case CK_ArrayToPointerDecay:
8575       return EvalVal(SubExpr, refVars, ParentDecl);
8576 
8577     case CK_BitCast:
8578       if (SubExpr->getType()->isAnyPointerType() ||
8579           SubExpr->getType()->isBlockPointerType() ||
8580           SubExpr->getType()->isObjCQualifiedIdType())
8581         return EvalAddr(SubExpr, refVars, ParentDecl);
8582       else
8583         return nullptr;
8584 
8585     default:
8586       return nullptr;
8587     }
8588   }
8589 
8590   case Stmt::MaterializeTemporaryExprClass:
8591     if (const Expr *Result =
8592             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8593                      refVars, ParentDecl))
8594       return Result;
8595     return E;
8596 
8597   // Everything else: we simply don't reason about them.
8598   default:
8599     return nullptr;
8600   }
8601 }
8602 
8603 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
8604 ///   See the comments for EvalAddr for more details.
8605 static const Expr *EvalVal(const Expr *E,
8606                            SmallVectorImpl<const DeclRefExpr *> &refVars,
8607                            const Decl *ParentDecl) {
8608   do {
8609     // We should only be called for evaluating non-pointer expressions, or
8610     // expressions with a pointer type that are not used as references but
8611     // instead
8612     // are l-values (e.g., DeclRefExpr with a pointer type).
8613 
8614     // Our "symbolic interpreter" is just a dispatch off the currently
8615     // viewed AST node.  We then recursively traverse the AST by calling
8616     // EvalAddr and EvalVal appropriately.
8617 
8618     E = E->IgnoreParens();
8619     switch (E->getStmtClass()) {
8620     case Stmt::ImplicitCastExprClass: {
8621       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8622       if (IE->getValueKind() == VK_LValue) {
8623         E = IE->getSubExpr();
8624         continue;
8625       }
8626       return nullptr;
8627     }
8628 
8629     case Stmt::ExprWithCleanupsClass:
8630       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8631                      ParentDecl);
8632 
8633     case Stmt::DeclRefExprClass: {
8634       // When we hit a DeclRefExpr we are looking at code that refers to a
8635       // variable's name. If it's not a reference variable we check if it has
8636       // local storage within the function, and if so, return the expression.
8637       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8638 
8639       // If we leave the immediate function, the lifetime isn't about to end.
8640       if (DR->refersToEnclosingVariableOrCapture())
8641         return nullptr;
8642 
8643       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8644         // Check if it refers to itself, e.g. "int& i = i;".
8645         if (V == ParentDecl)
8646           return DR;
8647 
8648         if (V->hasLocalStorage()) {
8649           if (!V->getType()->isReferenceType())
8650             return DR;
8651 
8652           // Reference variable, follow through to the expression that
8653           // it points to.
8654           if (V->hasInit()) {
8655             // Add the reference variable to the "trail".
8656             refVars.push_back(DR);
8657             return EvalVal(V->getInit(), refVars, V);
8658           }
8659         }
8660       }
8661 
8662       return nullptr;
8663     }
8664 
8665     case Stmt::UnaryOperatorClass: {
8666       // The only unary operator that make sense to handle here
8667       // is Deref.  All others don't resolve to a "name."  This includes
8668       // handling all sorts of rvalues passed to a unary operator.
8669       const UnaryOperator *U = cast<UnaryOperator>(E);
8670 
8671       if (U->getOpcode() == UO_Deref)
8672         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
8673 
8674       return nullptr;
8675     }
8676 
8677     case Stmt::ArraySubscriptExprClass: {
8678       // Array subscripts are potential references to data on the stack.  We
8679       // retrieve the DeclRefExpr* for the array variable if it indeed
8680       // has local storage.
8681       const auto *ASE = cast<ArraySubscriptExpr>(E);
8682       if (ASE->isTypeDependent())
8683         return nullptr;
8684       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8685     }
8686 
8687     case Stmt::OMPArraySectionExprClass: {
8688       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8689                       ParentDecl);
8690     }
8691 
8692     case Stmt::ConditionalOperatorClass: {
8693       // For conditional operators we need to see if either the LHS or RHS are
8694       // non-NULL Expr's.  If one is non-NULL, we return it.
8695       const ConditionalOperator *C = cast<ConditionalOperator>(E);
8696 
8697       // Handle the GNU extension for missing LHS.
8698       if (const Expr *LHSExpr = C->getLHS()) {
8699         // In C++, we can have a throw-expression, which has 'void' type.
8700         if (!LHSExpr->getType()->isVoidType())
8701           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8702             return LHS;
8703       }
8704 
8705       // In C++, we can have a throw-expression, which has 'void' type.
8706       if (C->getRHS()->getType()->isVoidType())
8707         return nullptr;
8708 
8709       return EvalVal(C->getRHS(), refVars, ParentDecl);
8710     }
8711 
8712     // Accesses to members are potential references to data on the stack.
8713     case Stmt::MemberExprClass: {
8714       const MemberExpr *M = cast<MemberExpr>(E);
8715 
8716       // Check for indirect access.  We only want direct field accesses.
8717       if (M->isArrow())
8718         return nullptr;
8719 
8720       // Check whether the member type is itself a reference, in which case
8721       // we're not going to refer to the member, but to what the member refers
8722       // to.
8723       if (M->getMemberDecl()->getType()->isReferenceType())
8724         return nullptr;
8725 
8726       return EvalVal(M->getBase(), refVars, ParentDecl);
8727     }
8728 
8729     case Stmt::MaterializeTemporaryExprClass:
8730       if (const Expr *Result =
8731               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8732                       refVars, ParentDecl))
8733         return Result;
8734       return E;
8735 
8736     default:
8737       // Check that we don't return or take the address of a reference to a
8738       // temporary. This is only useful in C++.
8739       if (!E->isTypeDependent() && E->isRValue())
8740         return E;
8741 
8742       // Everything else: we simply don't reason about them.
8743       return nullptr;
8744     }
8745   } while (true);
8746 }
8747 
8748 void
8749 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8750                          SourceLocation ReturnLoc,
8751                          bool isObjCMethod,
8752                          const AttrVec *Attrs,
8753                          const FunctionDecl *FD) {
8754   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8755 
8756   // Check if the return value is null but should not be.
8757   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8758        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8759       CheckNonNullExpr(*this, RetValExp))
8760     Diag(ReturnLoc, diag::warn_null_ret)
8761       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8762 
8763   // C++11 [basic.stc.dynamic.allocation]p4:
8764   //   If an allocation function declared with a non-throwing
8765   //   exception-specification fails to allocate storage, it shall return
8766   //   a null pointer. Any other allocation function that fails to allocate
8767   //   storage shall indicate failure only by throwing an exception [...]
8768   if (FD) {
8769     OverloadedOperatorKind Op = FD->getOverloadedOperator();
8770     if (Op == OO_New || Op == OO_Array_New) {
8771       const FunctionProtoType *Proto
8772         = FD->getType()->castAs<FunctionProtoType>();
8773       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
8774           CheckNonNullExpr(*this, RetValExp))
8775         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8776           << FD << getLangOpts().CPlusPlus11;
8777     }
8778   }
8779 }
8780 
8781 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8782 
8783 /// Check for comparisons of floating point operands using != and ==.
8784 /// Issue a warning if these are no self-comparisons, as they are not likely
8785 /// to do what the programmer intended.
8786 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8787   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8788   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8789 
8790   // Special case: check for x == x (which is OK).
8791   // Do not emit warnings for such cases.
8792   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8793     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8794       if (DRL->getDecl() == DRR->getDecl())
8795         return;
8796 
8797   // Special case: check for comparisons against literals that can be exactly
8798   //  represented by APFloat.  In such cases, do not emit a warning.  This
8799   //  is a heuristic: often comparison against such literals are used to
8800   //  detect if a value in a variable has not changed.  This clearly can
8801   //  lead to false negatives.
8802   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8803     if (FLL->isExact())
8804       return;
8805   } else
8806     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8807       if (FLR->isExact())
8808         return;
8809 
8810   // Check for comparisons with builtin types.
8811   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8812     if (CL->getBuiltinCallee())
8813       return;
8814 
8815   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8816     if (CR->getBuiltinCallee())
8817       return;
8818 
8819   // Emit the diagnostic.
8820   Diag(Loc, diag::warn_floatingpoint_eq)
8821     << LHS->getSourceRange() << RHS->getSourceRange();
8822 }
8823 
8824 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8825 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8826 
8827 namespace {
8828 
8829 /// Structure recording the 'active' range of an integer-valued
8830 /// expression.
8831 struct IntRange {
8832   /// The number of bits active in the int.
8833   unsigned Width;
8834 
8835   /// True if the int is known not to have negative values.
8836   bool NonNegative;
8837 
8838   IntRange(unsigned Width, bool NonNegative)
8839       : Width(Width), NonNegative(NonNegative) {}
8840 
8841   /// Returns the range of the bool type.
8842   static IntRange forBoolType() {
8843     return IntRange(1, true);
8844   }
8845 
8846   /// Returns the range of an opaque value of the given integral type.
8847   static IntRange forValueOfType(ASTContext &C, QualType T) {
8848     return forValueOfCanonicalType(C,
8849                           T->getCanonicalTypeInternal().getTypePtr());
8850   }
8851 
8852   /// Returns the range of an opaque value of a canonical integral type.
8853   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8854     assert(T->isCanonicalUnqualified());
8855 
8856     if (const VectorType *VT = dyn_cast<VectorType>(T))
8857       T = VT->getElementType().getTypePtr();
8858     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8859       T = CT->getElementType().getTypePtr();
8860     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8861       T = AT->getValueType().getTypePtr();
8862 
8863     if (!C.getLangOpts().CPlusPlus) {
8864       // For enum types in C code, use the underlying datatype.
8865       if (const EnumType *ET = dyn_cast<EnumType>(T))
8866         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8867     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8868       // For enum types in C++, use the known bit width of the enumerators.
8869       EnumDecl *Enum = ET->getDecl();
8870       // In C++11, enums can have a fixed underlying type. Use this type to
8871       // compute the range.
8872       if (Enum->isFixed()) {
8873         return IntRange(C.getIntWidth(QualType(T, 0)),
8874                         !ET->isSignedIntegerOrEnumerationType());
8875       }
8876 
8877       unsigned NumPositive = Enum->getNumPositiveBits();
8878       unsigned NumNegative = Enum->getNumNegativeBits();
8879 
8880       if (NumNegative == 0)
8881         return IntRange(NumPositive, true/*NonNegative*/);
8882       else
8883         return IntRange(std::max(NumPositive + 1, NumNegative),
8884                         false/*NonNegative*/);
8885     }
8886 
8887     const BuiltinType *BT = cast<BuiltinType>(T);
8888     assert(BT->isInteger());
8889 
8890     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8891   }
8892 
8893   /// Returns the "target" range of a canonical integral type, i.e.
8894   /// the range of values expressible in the type.
8895   ///
8896   /// This matches forValueOfCanonicalType except that enums have the
8897   /// full range of their type, not the range of their enumerators.
8898   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8899     assert(T->isCanonicalUnqualified());
8900 
8901     if (const VectorType *VT = dyn_cast<VectorType>(T))
8902       T = VT->getElementType().getTypePtr();
8903     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8904       T = CT->getElementType().getTypePtr();
8905     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8906       T = AT->getValueType().getTypePtr();
8907     if (const EnumType *ET = dyn_cast<EnumType>(T))
8908       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8909 
8910     const BuiltinType *BT = cast<BuiltinType>(T);
8911     assert(BT->isInteger());
8912 
8913     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8914   }
8915 
8916   /// Returns the supremum of two ranges: i.e. their conservative merge.
8917   static IntRange join(IntRange L, IntRange R) {
8918     return IntRange(std::max(L.Width, R.Width),
8919                     L.NonNegative && R.NonNegative);
8920   }
8921 
8922   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8923   static IntRange meet(IntRange L, IntRange R) {
8924     return IntRange(std::min(L.Width, R.Width),
8925                     L.NonNegative || R.NonNegative);
8926   }
8927 };
8928 
8929 } // namespace
8930 
8931 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8932                               unsigned MaxWidth) {
8933   if (value.isSigned() && value.isNegative())
8934     return IntRange(value.getMinSignedBits(), false);
8935 
8936   if (value.getBitWidth() > MaxWidth)
8937     value = value.trunc(MaxWidth);
8938 
8939   // isNonNegative() just checks the sign bit without considering
8940   // signedness.
8941   return IntRange(value.getActiveBits(), true);
8942 }
8943 
8944 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8945                               unsigned MaxWidth) {
8946   if (result.isInt())
8947     return GetValueRange(C, result.getInt(), MaxWidth);
8948 
8949   if (result.isVector()) {
8950     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8951     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8952       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8953       R = IntRange::join(R, El);
8954     }
8955     return R;
8956   }
8957 
8958   if (result.isComplexInt()) {
8959     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8960     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8961     return IntRange::join(R, I);
8962   }
8963 
8964   // This can happen with lossless casts to intptr_t of "based" lvalues.
8965   // Assume it might use arbitrary bits.
8966   // FIXME: The only reason we need to pass the type in here is to get
8967   // the sign right on this one case.  It would be nice if APValue
8968   // preserved this.
8969   assert(result.isLValue() || result.isAddrLabelDiff());
8970   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8971 }
8972 
8973 static QualType GetExprType(const Expr *E) {
8974   QualType Ty = E->getType();
8975   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8976     Ty = AtomicRHS->getValueType();
8977   return Ty;
8978 }
8979 
8980 /// Pseudo-evaluate the given integer expression, estimating the
8981 /// range of values it might take.
8982 ///
8983 /// \param MaxWidth - the width to which the value will be truncated
8984 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8985   E = E->IgnoreParens();
8986 
8987   // Try a full evaluation first.
8988   Expr::EvalResult result;
8989   if (E->EvaluateAsRValue(result, C))
8990     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8991 
8992   // I think we only want to look through implicit casts here; if the
8993   // user has an explicit widening cast, we should treat the value as
8994   // being of the new, wider type.
8995   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8996     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8997       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8998 
8999     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9000 
9001     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9002                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9003 
9004     // Assume that non-integer casts can span the full range of the type.
9005     if (!isIntegerCast)
9006       return OutputTypeRange;
9007 
9008     IntRange SubRange
9009       = GetExprRange(C, CE->getSubExpr(),
9010                      std::min(MaxWidth, OutputTypeRange.Width));
9011 
9012     // Bail out if the subexpr's range is as wide as the cast type.
9013     if (SubRange.Width >= OutputTypeRange.Width)
9014       return OutputTypeRange;
9015 
9016     // Otherwise, we take the smaller width, and we're non-negative if
9017     // either the output type or the subexpr is.
9018     return IntRange(SubRange.Width,
9019                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9020   }
9021 
9022   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9023     // If we can fold the condition, just take that operand.
9024     bool CondResult;
9025     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9026       return GetExprRange(C, CondResult ? CO->getTrueExpr()
9027                                         : CO->getFalseExpr(),
9028                           MaxWidth);
9029 
9030     // Otherwise, conservatively merge.
9031     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9032     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9033     return IntRange::join(L, R);
9034   }
9035 
9036   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9037     switch (BO->getOpcode()) {
9038     case BO_Cmp:
9039       llvm_unreachable("builtin <=> should have class type");
9040 
9041     // Boolean-valued operations are single-bit and positive.
9042     case BO_LAnd:
9043     case BO_LOr:
9044     case BO_LT:
9045     case BO_GT:
9046     case BO_LE:
9047     case BO_GE:
9048     case BO_EQ:
9049     case BO_NE:
9050       return IntRange::forBoolType();
9051 
9052     // The type of the assignments is the type of the LHS, so the RHS
9053     // is not necessarily the same type.
9054     case BO_MulAssign:
9055     case BO_DivAssign:
9056     case BO_RemAssign:
9057     case BO_AddAssign:
9058     case BO_SubAssign:
9059     case BO_XorAssign:
9060     case BO_OrAssign:
9061       // TODO: bitfields?
9062       return IntRange::forValueOfType(C, GetExprType(E));
9063 
9064     // Simple assignments just pass through the RHS, which will have
9065     // been coerced to the LHS type.
9066     case BO_Assign:
9067       // TODO: bitfields?
9068       return GetExprRange(C, BO->getRHS(), MaxWidth);
9069 
9070     // Operations with opaque sources are black-listed.
9071     case BO_PtrMemD:
9072     case BO_PtrMemI:
9073       return IntRange::forValueOfType(C, GetExprType(E));
9074 
9075     // Bitwise-and uses the *infinum* of the two source ranges.
9076     case BO_And:
9077     case BO_AndAssign:
9078       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9079                             GetExprRange(C, BO->getRHS(), MaxWidth));
9080 
9081     // Left shift gets black-listed based on a judgement call.
9082     case BO_Shl:
9083       // ...except that we want to treat '1 << (blah)' as logically
9084       // positive.  It's an important idiom.
9085       if (IntegerLiteral *I
9086             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9087         if (I->getValue() == 1) {
9088           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9089           return IntRange(R.Width, /*NonNegative*/ true);
9090         }
9091       }
9092       LLVM_FALLTHROUGH;
9093 
9094     case BO_ShlAssign:
9095       return IntRange::forValueOfType(C, GetExprType(E));
9096 
9097     // Right shift by a constant can narrow its left argument.
9098     case BO_Shr:
9099     case BO_ShrAssign: {
9100       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9101 
9102       // If the shift amount is a positive constant, drop the width by
9103       // that much.
9104       llvm::APSInt shift;
9105       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9106           shift.isNonNegative()) {
9107         unsigned zext = shift.getZExtValue();
9108         if (zext >= L.Width)
9109           L.Width = (L.NonNegative ? 0 : 1);
9110         else
9111           L.Width -= zext;
9112       }
9113 
9114       return L;
9115     }
9116 
9117     // Comma acts as its right operand.
9118     case BO_Comma:
9119       return GetExprRange(C, BO->getRHS(), MaxWidth);
9120 
9121     // Black-list pointer subtractions.
9122     case BO_Sub:
9123       if (BO->getLHS()->getType()->isPointerType())
9124         return IntRange::forValueOfType(C, GetExprType(E));
9125       break;
9126 
9127     // The width of a division result is mostly determined by the size
9128     // of the LHS.
9129     case BO_Div: {
9130       // Don't 'pre-truncate' the operands.
9131       unsigned opWidth = C.getIntWidth(GetExprType(E));
9132       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9133 
9134       // If the divisor is constant, use that.
9135       llvm::APSInt divisor;
9136       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9137         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9138         if (log2 >= L.Width)
9139           L.Width = (L.NonNegative ? 0 : 1);
9140         else
9141           L.Width = std::min(L.Width - log2, MaxWidth);
9142         return L;
9143       }
9144 
9145       // Otherwise, just use the LHS's width.
9146       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9147       return IntRange(L.Width, L.NonNegative && R.NonNegative);
9148     }
9149 
9150     // The result of a remainder can't be larger than the result of
9151     // either side.
9152     case BO_Rem: {
9153       // Don't 'pre-truncate' the operands.
9154       unsigned opWidth = C.getIntWidth(GetExprType(E));
9155       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9156       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9157 
9158       IntRange meet = IntRange::meet(L, R);
9159       meet.Width = std::min(meet.Width, MaxWidth);
9160       return meet;
9161     }
9162 
9163     // The default behavior is okay for these.
9164     case BO_Mul:
9165     case BO_Add:
9166     case BO_Xor:
9167     case BO_Or:
9168       break;
9169     }
9170 
9171     // The default case is to treat the operation as if it were closed
9172     // on the narrowest type that encompasses both operands.
9173     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9174     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9175     return IntRange::join(L, R);
9176   }
9177 
9178   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9179     switch (UO->getOpcode()) {
9180     // Boolean-valued operations are white-listed.
9181     case UO_LNot:
9182       return IntRange::forBoolType();
9183 
9184     // Operations with opaque sources are black-listed.
9185     case UO_Deref:
9186     case UO_AddrOf: // should be impossible
9187       return IntRange::forValueOfType(C, GetExprType(E));
9188 
9189     default:
9190       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9191     }
9192   }
9193 
9194   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
9195     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9196 
9197   if (const auto *BitField = E->getSourceBitField())
9198     return IntRange(BitField->getBitWidthValue(C),
9199                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
9200 
9201   return IntRange::forValueOfType(C, GetExprType(E));
9202 }
9203 
9204 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
9205   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
9206 }
9207 
9208 /// Checks whether the given value, which currently has the given
9209 /// source semantics, has the same value when coerced through the
9210 /// target semantics.
9211 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9212                                  const llvm::fltSemantics &Src,
9213                                  const llvm::fltSemantics &Tgt) {
9214   llvm::APFloat truncated = value;
9215 
9216   bool ignored;
9217   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9218   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9219 
9220   return truncated.bitwiseIsEqual(value);
9221 }
9222 
9223 /// Checks whether the given value, which currently has the given
9224 /// source semantics, has the same value when coerced through the
9225 /// target semantics.
9226 ///
9227 /// The value might be a vector of floats (or a complex number).
9228 static bool IsSameFloatAfterCast(const APValue &value,
9229                                  const llvm::fltSemantics &Src,
9230                                  const llvm::fltSemantics &Tgt) {
9231   if (value.isFloat())
9232     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9233 
9234   if (value.isVector()) {
9235     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9236       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9237         return false;
9238     return true;
9239   }
9240 
9241   assert(value.isComplexFloat());
9242   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9243           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9244 }
9245 
9246 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
9247 
9248 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
9249   // Suppress cases where we are comparing against an enum constant.
9250   if (const DeclRefExpr *DR =
9251       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9252     if (isa<EnumConstantDecl>(DR->getDecl()))
9253       return true;
9254 
9255   // Suppress cases where the '0' value is expanded from a macro.
9256   if (E->getLocStart().isMacroID())
9257     return true;
9258 
9259   return false;
9260 }
9261 
9262 static bool isKnownToHaveUnsignedValue(Expr *E) {
9263   return E->getType()->isIntegerType() &&
9264          (!E->getType()->isSignedIntegerType() ||
9265           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9266 }
9267 
9268 namespace {
9269 /// The promoted range of values of a type. In general this has the
9270 /// following structure:
9271 ///
9272 ///     |-----------| . . . |-----------|
9273 ///     ^           ^       ^           ^
9274 ///    Min       HoleMin  HoleMax      Max
9275 ///
9276 /// ... where there is only a hole if a signed type is promoted to unsigned
9277 /// (in which case Min and Max are the smallest and largest representable
9278 /// values).
9279 struct PromotedRange {
9280   // Min, or HoleMax if there is a hole.
9281   llvm::APSInt PromotedMin;
9282   // Max, or HoleMin if there is a hole.
9283   llvm::APSInt PromotedMax;
9284 
9285   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9286     if (R.Width == 0)
9287       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9288     else if (R.Width >= BitWidth && !Unsigned) {
9289       // Promotion made the type *narrower*. This happens when promoting
9290       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9291       // Treat all values of 'signed int' as being in range for now.
9292       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9293       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9294     } else {
9295       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9296                         .extOrTrunc(BitWidth);
9297       PromotedMin.setIsUnsigned(Unsigned);
9298 
9299       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9300                         .extOrTrunc(BitWidth);
9301       PromotedMax.setIsUnsigned(Unsigned);
9302     }
9303   }
9304 
9305   // Determine whether this range is contiguous (has no hole).
9306   bool isContiguous() const { return PromotedMin <= PromotedMax; }
9307 
9308   // Where a constant value is within the range.
9309   enum ComparisonResult {
9310     LT = 0x1,
9311     LE = 0x2,
9312     GT = 0x4,
9313     GE = 0x8,
9314     EQ = 0x10,
9315     NE = 0x20,
9316     InRangeFlag = 0x40,
9317 
9318     Less = LE | LT | NE,
9319     Min = LE | InRangeFlag,
9320     InRange = InRangeFlag,
9321     Max = GE | InRangeFlag,
9322     Greater = GE | GT | NE,
9323 
9324     OnlyValue = LE | GE | EQ | InRangeFlag,
9325     InHole = NE
9326   };
9327 
9328   ComparisonResult compare(const llvm::APSInt &Value) const {
9329     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9330            Value.isUnsigned() == PromotedMin.isUnsigned());
9331     if (!isContiguous()) {
9332       assert(Value.isUnsigned() && "discontiguous range for signed compare");
9333       if (Value.isMinValue()) return Min;
9334       if (Value.isMaxValue()) return Max;
9335       if (Value >= PromotedMin) return InRange;
9336       if (Value <= PromotedMax) return InRange;
9337       return InHole;
9338     }
9339 
9340     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9341     case -1: return Less;
9342     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9343     case 1:
9344       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9345       case -1: return InRange;
9346       case 0: return Max;
9347       case 1: return Greater;
9348       }
9349     }
9350 
9351     llvm_unreachable("impossible compare result");
9352   }
9353 
9354   static llvm::Optional<StringRef>
9355   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9356     if (Op == BO_Cmp) {
9357       ComparisonResult LTFlag = LT, GTFlag = GT;
9358       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9359 
9360       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9361       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9362       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9363       return llvm::None;
9364     }
9365 
9366     ComparisonResult TrueFlag, FalseFlag;
9367     if (Op == BO_EQ) {
9368       TrueFlag = EQ;
9369       FalseFlag = NE;
9370     } else if (Op == BO_NE) {
9371       TrueFlag = NE;
9372       FalseFlag = EQ;
9373     } else {
9374       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9375         TrueFlag = LT;
9376         FalseFlag = GE;
9377       } else {
9378         TrueFlag = GT;
9379         FalseFlag = LE;
9380       }
9381       if (Op == BO_GE || Op == BO_LE)
9382         std::swap(TrueFlag, FalseFlag);
9383     }
9384     if (R & TrueFlag)
9385       return StringRef("true");
9386     if (R & FalseFlag)
9387       return StringRef("false");
9388     return llvm::None;
9389   }
9390 };
9391 }
9392 
9393 static bool HasEnumType(Expr *E) {
9394   // Strip off implicit integral promotions.
9395   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9396     if (ICE->getCastKind() != CK_IntegralCast &&
9397         ICE->getCastKind() != CK_NoOp)
9398       break;
9399     E = ICE->getSubExpr();
9400   }
9401 
9402   return E->getType()->isEnumeralType();
9403 }
9404 
9405 static int classifyConstantValue(Expr *Constant) {
9406   // The values of this enumeration are used in the diagnostics
9407   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9408   enum ConstantValueKind {
9409     Miscellaneous = 0,
9410     LiteralTrue,
9411     LiteralFalse
9412   };
9413   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9414     return BL->getValue() ? ConstantValueKind::LiteralTrue
9415                           : ConstantValueKind::LiteralFalse;
9416   return ConstantValueKind::Miscellaneous;
9417 }
9418 
9419 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9420                                         Expr *Constant, Expr *Other,
9421                                         const llvm::APSInt &Value,
9422                                         bool RhsConstant) {
9423   if (S.inTemplateInstantiation())
9424     return false;
9425 
9426   Expr *OriginalOther = Other;
9427 
9428   Constant = Constant->IgnoreParenImpCasts();
9429   Other = Other->IgnoreParenImpCasts();
9430 
9431   // Suppress warnings on tautological comparisons between values of the same
9432   // enumeration type. There are only two ways we could warn on this:
9433   //  - If the constant is outside the range of representable values of
9434   //    the enumeration. In such a case, we should warn about the cast
9435   //    to enumeration type, not about the comparison.
9436   //  - If the constant is the maximum / minimum in-range value. For an
9437   //    enumeratin type, such comparisons can be meaningful and useful.
9438   if (Constant->getType()->isEnumeralType() &&
9439       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9440     return false;
9441 
9442   // TODO: Investigate using GetExprRange() to get tighter bounds
9443   // on the bit ranges.
9444   QualType OtherT = Other->getType();
9445   if (const auto *AT = OtherT->getAs<AtomicType>())
9446     OtherT = AT->getValueType();
9447   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9448 
9449   // Whether we're treating Other as being a bool because of the form of
9450   // expression despite it having another type (typically 'int' in C).
9451   bool OtherIsBooleanDespiteType =
9452       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9453   if (OtherIsBooleanDespiteType)
9454     OtherRange = IntRange::forBoolType();
9455 
9456   // Determine the promoted range of the other type and see if a comparison of
9457   // the constant against that range is tautological.
9458   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9459                                    Value.isUnsigned());
9460   auto Cmp = OtherPromotedRange.compare(Value);
9461   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9462   if (!Result)
9463     return false;
9464 
9465   // Suppress the diagnostic for an in-range comparison if the constant comes
9466   // from a macro or enumerator. We don't want to diagnose
9467   //
9468   //   some_long_value <= INT_MAX
9469   //
9470   // when sizeof(int) == sizeof(long).
9471   bool InRange = Cmp & PromotedRange::InRangeFlag;
9472   if (InRange && IsEnumConstOrFromMacro(S, Constant))
9473     return false;
9474 
9475   // If this is a comparison to an enum constant, include that
9476   // constant in the diagnostic.
9477   const EnumConstantDecl *ED = nullptr;
9478   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9479     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9480 
9481   // Should be enough for uint128 (39 decimal digits)
9482   SmallString<64> PrettySourceValue;
9483   llvm::raw_svector_ostream OS(PrettySourceValue);
9484   if (ED)
9485     OS << '\'' << *ED << "' (" << Value << ")";
9486   else
9487     OS << Value;
9488 
9489   // FIXME: We use a somewhat different formatting for the in-range cases and
9490   // cases involving boolean values for historical reasons. We should pick a
9491   // consistent way of presenting these diagnostics.
9492   if (!InRange || Other->isKnownToHaveBooleanValue()) {
9493     S.DiagRuntimeBehavior(
9494       E->getOperatorLoc(), E,
9495       S.PDiag(!InRange ? diag::warn_out_of_range_compare
9496                        : diag::warn_tautological_bool_compare)
9497           << OS.str() << classifyConstantValue(Constant)
9498           << OtherT << OtherIsBooleanDespiteType << *Result
9499           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9500   } else {
9501     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9502                         ? (HasEnumType(OriginalOther)
9503                                ? diag::warn_unsigned_enum_always_true_comparison
9504                                : diag::warn_unsigned_always_true_comparison)
9505                         : diag::warn_tautological_constant_compare;
9506 
9507     S.Diag(E->getOperatorLoc(), Diag)
9508         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9509         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9510   }
9511 
9512   return true;
9513 }
9514 
9515 /// Analyze the operands of the given comparison.  Implements the
9516 /// fallback case from AnalyzeComparison.
9517 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
9518   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9519   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9520 }
9521 
9522 /// Implements -Wsign-compare.
9523 ///
9524 /// \param E the binary operator to check for warnings
9525 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
9526   // The type the comparison is being performed in.
9527   QualType T = E->getLHS()->getType();
9528 
9529   // Only analyze comparison operators where both sides have been converted to
9530   // the same type.
9531   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9532     return AnalyzeImpConvsInComparison(S, E);
9533 
9534   // Don't analyze value-dependent comparisons directly.
9535   if (E->isValueDependent())
9536     return AnalyzeImpConvsInComparison(S, E);
9537 
9538   Expr *LHS = E->getLHS();
9539   Expr *RHS = E->getRHS();
9540 
9541   if (T->isIntegralType(S.Context)) {
9542     llvm::APSInt RHSValue;
9543     llvm::APSInt LHSValue;
9544 
9545     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9546     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
9547 
9548     // We don't care about expressions whose result is a constant.
9549     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9550       return AnalyzeImpConvsInComparison(S, E);
9551 
9552     // We only care about expressions where just one side is literal
9553     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9554       // Is the constant on the RHS or LHS?
9555       const bool RhsConstant = IsRHSIntegralLiteral;
9556       Expr *Const = RhsConstant ? RHS : LHS;
9557       Expr *Other = RhsConstant ? LHS : RHS;
9558       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9559 
9560       // Check whether an integer constant comparison results in a value
9561       // of 'true' or 'false'.
9562       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9563         return AnalyzeImpConvsInComparison(S, E);
9564     }
9565   }
9566 
9567   if (!T->hasUnsignedIntegerRepresentation()) {
9568     // We don't do anything special if this isn't an unsigned integral
9569     // comparison:  we're only interested in integral comparisons, and
9570     // signed comparisons only happen in cases we don't care to warn about.
9571     return AnalyzeImpConvsInComparison(S, E);
9572   }
9573 
9574   LHS = LHS->IgnoreParenImpCasts();
9575   RHS = RHS->IgnoreParenImpCasts();
9576 
9577   if (!S.getLangOpts().CPlusPlus) {
9578     // Avoid warning about comparison of integers with different signs when
9579     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9580     // the type of `E`.
9581     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9582       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9583     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9584       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9585   }
9586 
9587   // Check to see if one of the (unmodified) operands is of different
9588   // signedness.
9589   Expr *signedOperand, *unsignedOperand;
9590   if (LHS->getType()->hasSignedIntegerRepresentation()) {
9591     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
9592            "unsigned comparison between two signed integer expressions?");
9593     signedOperand = LHS;
9594     unsignedOperand = RHS;
9595   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9596     signedOperand = RHS;
9597     unsignedOperand = LHS;
9598   } else {
9599     return AnalyzeImpConvsInComparison(S, E);
9600   }
9601 
9602   // Otherwise, calculate the effective range of the signed operand.
9603   IntRange signedRange = GetExprRange(S.Context, signedOperand);
9604 
9605   // Go ahead and analyze implicit conversions in the operands.  Note
9606   // that we skip the implicit conversions on both sides.
9607   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9608   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
9609 
9610   // If the signed range is non-negative, -Wsign-compare won't fire.
9611   if (signedRange.NonNegative)
9612     return;
9613 
9614   // For (in)equality comparisons, if the unsigned operand is a
9615   // constant which cannot collide with a overflowed signed operand,
9616   // then reinterpreting the signed operand as unsigned will not
9617   // change the result of the comparison.
9618   if (E->isEqualityOp()) {
9619     unsigned comparisonWidth = S.Context.getIntWidth(T);
9620     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
9621 
9622     // We should never be unable to prove that the unsigned operand is
9623     // non-negative.
9624     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9625 
9626     if (unsignedRange.Width < comparisonWidth)
9627       return;
9628   }
9629 
9630   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9631     S.PDiag(diag::warn_mixed_sign_comparison)
9632       << LHS->getType() << RHS->getType()
9633       << LHS->getSourceRange() << RHS->getSourceRange());
9634 }
9635 
9636 /// Analyzes an attempt to assign the given value to a bitfield.
9637 ///
9638 /// Returns true if there was something fishy about the attempt.
9639 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9640                                       SourceLocation InitLoc) {
9641   assert(Bitfield->isBitField());
9642   if (Bitfield->isInvalidDecl())
9643     return false;
9644 
9645   // White-list bool bitfields.
9646   QualType BitfieldType = Bitfield->getType();
9647   if (BitfieldType->isBooleanType())
9648      return false;
9649 
9650   if (BitfieldType->isEnumeralType()) {
9651     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9652     // If the underlying enum type was not explicitly specified as an unsigned
9653     // type and the enum contain only positive values, MSVC++ will cause an
9654     // inconsistency by storing this as a signed type.
9655     if (S.getLangOpts().CPlusPlus11 &&
9656         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9657         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9658         BitfieldEnumDecl->getNumNegativeBits() == 0) {
9659       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9660         << BitfieldEnumDecl->getNameAsString();
9661     }
9662   }
9663 
9664   if (Bitfield->getType()->isBooleanType())
9665     return false;
9666 
9667   // Ignore value- or type-dependent expressions.
9668   if (Bitfield->getBitWidth()->isValueDependent() ||
9669       Bitfield->getBitWidth()->isTypeDependent() ||
9670       Init->isValueDependent() ||
9671       Init->isTypeDependent())
9672     return false;
9673 
9674   Expr *OriginalInit = Init->IgnoreParenImpCasts();
9675   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
9676 
9677   llvm::APSInt Value;
9678   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9679                                    Expr::SE_AllowSideEffects)) {
9680     // The RHS is not constant.  If the RHS has an enum type, make sure the
9681     // bitfield is wide enough to hold all the values of the enum without
9682     // truncation.
9683     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9684       EnumDecl *ED = EnumTy->getDecl();
9685       bool SignedBitfield = BitfieldType->isSignedIntegerType();
9686 
9687       // Enum types are implicitly signed on Windows, so check if there are any
9688       // negative enumerators to see if the enum was intended to be signed or
9689       // not.
9690       bool SignedEnum = ED->getNumNegativeBits() > 0;
9691 
9692       // Check for surprising sign changes when assigning enum values to a
9693       // bitfield of different signedness.  If the bitfield is signed and we
9694       // have exactly the right number of bits to store this unsigned enum,
9695       // suggest changing the enum to an unsigned type. This typically happens
9696       // on Windows where unfixed enums always use an underlying type of 'int'.
9697       unsigned DiagID = 0;
9698       if (SignedEnum && !SignedBitfield) {
9699         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9700       } else if (SignedBitfield && !SignedEnum &&
9701                  ED->getNumPositiveBits() == FieldWidth) {
9702         DiagID = diag::warn_signed_bitfield_enum_conversion;
9703       }
9704 
9705       if (DiagID) {
9706         S.Diag(InitLoc, DiagID) << Bitfield << ED;
9707         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9708         SourceRange TypeRange =
9709             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9710         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9711             << SignedEnum << TypeRange;
9712       }
9713 
9714       // Compute the required bitwidth. If the enum has negative values, we need
9715       // one more bit than the normal number of positive bits to represent the
9716       // sign bit.
9717       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9718                                                   ED->getNumNegativeBits())
9719                                        : ED->getNumPositiveBits();
9720 
9721       // Check the bitwidth.
9722       if (BitsNeeded > FieldWidth) {
9723         Expr *WidthExpr = Bitfield->getBitWidth();
9724         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9725             << Bitfield << ED;
9726         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9727             << BitsNeeded << ED << WidthExpr->getSourceRange();
9728       }
9729     }
9730 
9731     return false;
9732   }
9733 
9734   unsigned OriginalWidth = Value.getBitWidth();
9735 
9736   if (!Value.isSigned() || Value.isNegative())
9737     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9738       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9739         OriginalWidth = Value.getMinSignedBits();
9740 
9741   if (OriginalWidth <= FieldWidth)
9742     return false;
9743 
9744   // Compute the value which the bitfield will contain.
9745   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9746   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9747 
9748   // Check whether the stored value is equal to the original value.
9749   TruncatedValue = TruncatedValue.extend(OriginalWidth);
9750   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9751     return false;
9752 
9753   // Special-case bitfields of width 1: booleans are naturally 0/1, and
9754   // therefore don't strictly fit into a signed bitfield of width 1.
9755   if (FieldWidth == 1 && Value == 1)
9756     return false;
9757 
9758   std::string PrettyValue = Value.toString(10);
9759   std::string PrettyTrunc = TruncatedValue.toString(10);
9760 
9761   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9762     << PrettyValue << PrettyTrunc << OriginalInit->getType()
9763     << Init->getSourceRange();
9764 
9765   return true;
9766 }
9767 
9768 /// Analyze the given simple or compound assignment for warning-worthy
9769 /// operations.
9770 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9771   // Just recurse on the LHS.
9772   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9773 
9774   // We want to recurse on the RHS as normal unless we're assigning to
9775   // a bitfield.
9776   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9777     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9778                                   E->getOperatorLoc())) {
9779       // Recurse, ignoring any implicit conversions on the RHS.
9780       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9781                                         E->getOperatorLoc());
9782     }
9783   }
9784 
9785   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9786 }
9787 
9788 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9789 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9790                             SourceLocation CContext, unsigned diag,
9791                             bool pruneControlFlow = false) {
9792   if (pruneControlFlow) {
9793     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9794                           S.PDiag(diag)
9795                             << SourceType << T << E->getSourceRange()
9796                             << SourceRange(CContext));
9797     return;
9798   }
9799   S.Diag(E->getExprLoc(), diag)
9800     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9801 }
9802 
9803 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9804 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9805                             SourceLocation CContext,
9806                             unsigned diag, bool pruneControlFlow = false) {
9807   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9808 }
9809 
9810 /// Analyze the given compound assignment for the possible losing of
9811 /// floating-point precision.
9812 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9813   assert(isa<CompoundAssignOperator>(E) &&
9814          "Must be compound assignment operation");
9815   // Recurse on the LHS and RHS in here
9816   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9817   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9818 
9819   // Now check the outermost expression
9820   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9821   const auto *RBT = cast<CompoundAssignOperator>(E)
9822                         ->getComputationResultType()
9823                         ->getAs<BuiltinType>();
9824 
9825   // If both source and target are floating points.
9826   if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9827     // Builtin FP kinds are ordered by increasing FP rank.
9828     if (ResultBT->getKind() < RBT->getKind())
9829       // We don't want to warn for system macro.
9830       if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9831         // warn about dropping FP rank.
9832         DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9833                         E->getOperatorLoc(),
9834                         diag::warn_impcast_float_result_precision);
9835 }
9836 
9837 /// Diagnose an implicit cast from a floating point value to an integer value.
9838 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9839                                     SourceLocation CContext) {
9840   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9841   const bool PruneWarnings = S.inTemplateInstantiation();
9842 
9843   Expr *InnerE = E->IgnoreParenImpCasts();
9844   // We also want to warn on, e.g., "int i = -1.234"
9845   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9846     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9847       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9848 
9849   const bool IsLiteral =
9850       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9851 
9852   llvm::APFloat Value(0.0);
9853   bool IsConstant =
9854     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9855   if (!IsConstant) {
9856     return DiagnoseImpCast(S, E, T, CContext,
9857                            diag::warn_impcast_float_integer, PruneWarnings);
9858   }
9859 
9860   bool isExact = false;
9861 
9862   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9863                             T->hasUnsignedIntegerRepresentation());
9864   llvm::APFloat::opStatus Result = Value.convertToInteger(
9865       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9866 
9867   if (Result == llvm::APFloat::opOK && isExact) {
9868     if (IsLiteral) return;
9869     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9870                            PruneWarnings);
9871   }
9872 
9873   // Conversion of a floating-point value to a non-bool integer where the
9874   // integral part cannot be represented by the integer type is undefined.
9875   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9876     return DiagnoseImpCast(
9877         S, E, T, CContext,
9878         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
9879                   : diag::warn_impcast_float_to_integer_out_of_range,
9880         PruneWarnings);
9881 
9882   unsigned DiagID = 0;
9883   if (IsLiteral) {
9884     // Warn on floating point literal to integer.
9885     DiagID = diag::warn_impcast_literal_float_to_integer;
9886   } else if (IntegerValue == 0) {
9887     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
9888       return DiagnoseImpCast(S, E, T, CContext,
9889                              diag::warn_impcast_float_integer, PruneWarnings);
9890     }
9891     // Warn on non-zero to zero conversion.
9892     DiagID = diag::warn_impcast_float_to_integer_zero;
9893   } else {
9894     if (IntegerValue.isUnsigned()) {
9895       if (!IntegerValue.isMaxValue()) {
9896         return DiagnoseImpCast(S, E, T, CContext,
9897                                diag::warn_impcast_float_integer, PruneWarnings);
9898       }
9899     } else {  // IntegerValue.isSigned()
9900       if (!IntegerValue.isMaxSignedValue() &&
9901           !IntegerValue.isMinSignedValue()) {
9902         return DiagnoseImpCast(S, E, T, CContext,
9903                                diag::warn_impcast_float_integer, PruneWarnings);
9904       }
9905     }
9906     // Warn on evaluatable floating point expression to integer conversion.
9907     DiagID = diag::warn_impcast_float_to_integer;
9908   }
9909 
9910   // FIXME: Force the precision of the source value down so we don't print
9911   // digits which are usually useless (we don't really care here if we
9912   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9913   // would automatically print the shortest representation, but it's a bit
9914   // tricky to implement.
9915   SmallString<16> PrettySourceValue;
9916   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9917   precision = (precision * 59 + 195) / 196;
9918   Value.toString(PrettySourceValue, precision);
9919 
9920   SmallString<16> PrettyTargetValue;
9921   if (IsBool)
9922     PrettyTargetValue = Value.isZero() ? "false" : "true";
9923   else
9924     IntegerValue.toString(PrettyTargetValue);
9925 
9926   if (PruneWarnings) {
9927     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9928                           S.PDiag(DiagID)
9929                               << E->getType() << T.getUnqualifiedType()
9930                               << PrettySourceValue << PrettyTargetValue
9931                               << E->getSourceRange() << SourceRange(CContext));
9932   } else {
9933     S.Diag(E->getExprLoc(), DiagID)
9934         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9935         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9936   }
9937 }
9938 
9939 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9940                                       IntRange Range) {
9941   if (!Range.Width) return "0";
9942 
9943   llvm::APSInt ValueInRange = Value;
9944   ValueInRange.setIsSigned(!Range.NonNegative);
9945   ValueInRange = ValueInRange.trunc(Range.Width);
9946   return ValueInRange.toString(10);
9947 }
9948 
9949 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9950   if (!isa<ImplicitCastExpr>(Ex))
9951     return false;
9952 
9953   Expr *InnerE = Ex->IgnoreParenImpCasts();
9954   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9955   const Type *Source =
9956     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9957   if (Target->isDependentType())
9958     return false;
9959 
9960   const BuiltinType *FloatCandidateBT =
9961     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9962   const Type *BoolCandidateType = ToBool ? Target : Source;
9963 
9964   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9965           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9966 }
9967 
9968 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9969                                              SourceLocation CC) {
9970   unsigned NumArgs = TheCall->getNumArgs();
9971   for (unsigned i = 0; i < NumArgs; ++i) {
9972     Expr *CurrA = TheCall->getArg(i);
9973     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9974       continue;
9975 
9976     bool IsSwapped = ((i > 0) &&
9977         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9978     IsSwapped |= ((i < (NumArgs - 1)) &&
9979         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9980     if (IsSwapped) {
9981       // Warn on this floating-point to bool conversion.
9982       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9983                       CurrA->getType(), CC,
9984                       diag::warn_impcast_floating_point_to_bool);
9985     }
9986   }
9987 }
9988 
9989 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9990                                    SourceLocation CC) {
9991   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9992                         E->getExprLoc()))
9993     return;
9994 
9995   // Don't warn on functions which have return type nullptr_t.
9996   if (isa<CallExpr>(E))
9997     return;
9998 
9999   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10000   const Expr::NullPointerConstantKind NullKind =
10001       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10002   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10003     return;
10004 
10005   // Return if target type is a safe conversion.
10006   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10007       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10008     return;
10009 
10010   SourceLocation Loc = E->getSourceRange().getBegin();
10011 
10012   // Venture through the macro stacks to get to the source of macro arguments.
10013   // The new location is a better location than the complete location that was
10014   // passed in.
10015   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10016   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10017 
10018   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10019   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10020     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10021         Loc, S.SourceMgr, S.getLangOpts());
10022     if (MacroName == "NULL")
10023       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10024   }
10025 
10026   // Only warn if the null and context location are in the same macro expansion.
10027   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10028     return;
10029 
10030   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10031       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10032       << FixItHint::CreateReplacement(Loc,
10033                                       S.getFixItZeroLiteralForType(T, Loc));
10034 }
10035 
10036 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10037                                   ObjCArrayLiteral *ArrayLiteral);
10038 
10039 static void
10040 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10041                            ObjCDictionaryLiteral *DictionaryLiteral);
10042 
10043 /// Check a single element within a collection literal against the
10044 /// target element type.
10045 static void checkObjCCollectionLiteralElement(Sema &S,
10046                                               QualType TargetElementType,
10047                                               Expr *Element,
10048                                               unsigned ElementKind) {
10049   // Skip a bitcast to 'id' or qualified 'id'.
10050   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10051     if (ICE->getCastKind() == CK_BitCast &&
10052         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10053       Element = ICE->getSubExpr();
10054   }
10055 
10056   QualType ElementType = Element->getType();
10057   ExprResult ElementResult(Element);
10058   if (ElementType->getAs<ObjCObjectPointerType>() &&
10059       S.CheckSingleAssignmentConstraints(TargetElementType,
10060                                          ElementResult,
10061                                          false, false)
10062         != Sema::Compatible) {
10063     S.Diag(Element->getLocStart(),
10064            diag::warn_objc_collection_literal_element)
10065       << ElementType << ElementKind << TargetElementType
10066       << Element->getSourceRange();
10067   }
10068 
10069   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10070     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10071   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10072     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10073 }
10074 
10075 /// Check an Objective-C array literal being converted to the given
10076 /// target type.
10077 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10078                                   ObjCArrayLiteral *ArrayLiteral) {
10079   if (!S.NSArrayDecl)
10080     return;
10081 
10082   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10083   if (!TargetObjCPtr)
10084     return;
10085 
10086   if (TargetObjCPtr->isUnspecialized() ||
10087       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10088         != S.NSArrayDecl->getCanonicalDecl())
10089     return;
10090 
10091   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10092   if (TypeArgs.size() != 1)
10093     return;
10094 
10095   QualType TargetElementType = TypeArgs[0];
10096   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10097     checkObjCCollectionLiteralElement(S, TargetElementType,
10098                                       ArrayLiteral->getElement(I),
10099                                       0);
10100   }
10101 }
10102 
10103 /// Check an Objective-C dictionary literal being converted to the given
10104 /// target type.
10105 static void
10106 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10107                            ObjCDictionaryLiteral *DictionaryLiteral) {
10108   if (!S.NSDictionaryDecl)
10109     return;
10110 
10111   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10112   if (!TargetObjCPtr)
10113     return;
10114 
10115   if (TargetObjCPtr->isUnspecialized() ||
10116       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10117         != S.NSDictionaryDecl->getCanonicalDecl())
10118     return;
10119 
10120   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10121   if (TypeArgs.size() != 2)
10122     return;
10123 
10124   QualType TargetKeyType = TypeArgs[0];
10125   QualType TargetObjectType = TypeArgs[1];
10126   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10127     auto Element = DictionaryLiteral->getKeyValueElement(I);
10128     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10129     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10130   }
10131 }
10132 
10133 // Helper function to filter out cases for constant width constant conversion.
10134 // Don't warn on char array initialization or for non-decimal values.
10135 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10136                                           SourceLocation CC) {
10137   // If initializing from a constant, and the constant starts with '0',
10138   // then it is a binary, octal, or hexadecimal.  Allow these constants
10139   // to fill all the bits, even if there is a sign change.
10140   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10141     const char FirstLiteralCharacter =
10142         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
10143     if (FirstLiteralCharacter == '0')
10144       return false;
10145   }
10146 
10147   // If the CC location points to a '{', and the type is char, then assume
10148   // assume it is an array initialization.
10149   if (CC.isValid() && T->isCharType()) {
10150     const char FirstContextCharacter =
10151         S.getSourceManager().getCharacterData(CC)[0];
10152     if (FirstContextCharacter == '{')
10153       return false;
10154   }
10155 
10156   return true;
10157 }
10158 
10159 static void
10160 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10161                         bool *ICContext = nullptr) {
10162   if (E->isTypeDependent() || E->isValueDependent()) return;
10163 
10164   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10165   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10166   if (Source == Target) return;
10167   if (Target->isDependentType()) return;
10168 
10169   // If the conversion context location is invalid don't complain. We also
10170   // don't want to emit a warning if the issue occurs from the expansion of
10171   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10172   // delay this check as long as possible. Once we detect we are in that
10173   // scenario, we just return.
10174   if (CC.isInvalid())
10175     return;
10176 
10177   // Diagnose implicit casts to bool.
10178   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10179     if (isa<StringLiteral>(E))
10180       // Warn on string literal to bool.  Checks for string literals in logical
10181       // and expressions, for instance, assert(0 && "error here"), are
10182       // prevented by a check in AnalyzeImplicitConversions().
10183       return DiagnoseImpCast(S, E, T, CC,
10184                              diag::warn_impcast_string_literal_to_bool);
10185     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10186         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10187       // This covers the literal expressions that evaluate to Objective-C
10188       // objects.
10189       return DiagnoseImpCast(S, E, T, CC,
10190                              diag::warn_impcast_objective_c_literal_to_bool);
10191     }
10192     if (Source->isPointerType() || Source->canDecayToPointerType()) {
10193       // Warn on pointer to bool conversion that is always true.
10194       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10195                                      SourceRange(CC));
10196     }
10197   }
10198 
10199   // Check implicit casts from Objective-C collection literals to specialized
10200   // collection types, e.g., NSArray<NSString *> *.
10201   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10202     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10203   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10204     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10205 
10206   // Strip vector types.
10207   if (isa<VectorType>(Source)) {
10208     if (!isa<VectorType>(Target)) {
10209       if (S.SourceMgr.isInSystemMacro(CC))
10210         return;
10211       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
10212     }
10213 
10214     // If the vector cast is cast between two vectors of the same size, it is
10215     // a bitcast, not a conversion.
10216     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10217       return;
10218 
10219     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10220     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10221   }
10222   if (auto VecTy = dyn_cast<VectorType>(Target))
10223     Target = VecTy->getElementType().getTypePtr();
10224 
10225   // Strip complex types.
10226   if (isa<ComplexType>(Source)) {
10227     if (!isa<ComplexType>(Target)) {
10228       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
10229         return;
10230 
10231       return DiagnoseImpCast(S, E, T, CC,
10232                              S.getLangOpts().CPlusPlus
10233                                  ? diag::err_impcast_complex_scalar
10234                                  : diag::warn_impcast_complex_scalar);
10235     }
10236 
10237     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10238     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10239   }
10240 
10241   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10242   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10243 
10244   // If the source is floating point...
10245   if (SourceBT && SourceBT->isFloatingPoint()) {
10246     // ...and the target is floating point...
10247     if (TargetBT && TargetBT->isFloatingPoint()) {
10248       // ...then warn if we're dropping FP rank.
10249 
10250       // Builtin FP kinds are ordered by increasing FP rank.
10251       if (SourceBT->getKind() > TargetBT->getKind()) {
10252         // Don't warn about float constants that are precisely
10253         // representable in the target type.
10254         Expr::EvalResult result;
10255         if (E->EvaluateAsRValue(result, S.Context)) {
10256           // Value might be a float, a float vector, or a float complex.
10257           if (IsSameFloatAfterCast(result.Val,
10258                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10259                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
10260             return;
10261         }
10262 
10263         if (S.SourceMgr.isInSystemMacro(CC))
10264           return;
10265 
10266         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
10267       }
10268       // ... or possibly if we're increasing rank, too
10269       else if (TargetBT->getKind() > SourceBT->getKind()) {
10270         if (S.SourceMgr.isInSystemMacro(CC))
10271           return;
10272 
10273         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
10274       }
10275       return;
10276     }
10277 
10278     // If the target is integral, always warn.
10279     if (TargetBT && TargetBT->isInteger()) {
10280       if (S.SourceMgr.isInSystemMacro(CC))
10281         return;
10282 
10283       DiagnoseFloatingImpCast(S, E, T, CC);
10284     }
10285 
10286     // Detect the case where a call result is converted from floating-point to
10287     // to bool, and the final argument to the call is converted from bool, to
10288     // discover this typo:
10289     //
10290     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
10291     //
10292     // FIXME: This is an incredibly special case; is there some more general
10293     // way to detect this class of misplaced-parentheses bug?
10294     if (Target->isBooleanType() && isa<CallExpr>(E)) {
10295       // Check last argument of function call to see if it is an
10296       // implicit cast from a type matching the type the result
10297       // is being cast to.
10298       CallExpr *CEx = cast<CallExpr>(E);
10299       if (unsigned NumArgs = CEx->getNumArgs()) {
10300         Expr *LastA = CEx->getArg(NumArgs - 1);
10301         Expr *InnerE = LastA->IgnoreParenImpCasts();
10302         if (isa<ImplicitCastExpr>(LastA) &&
10303             InnerE->getType()->isBooleanType()) {
10304           // Warn on this floating-point to bool conversion
10305           DiagnoseImpCast(S, E, T, CC,
10306                           diag::warn_impcast_floating_point_to_bool);
10307         }
10308       }
10309     }
10310     return;
10311   }
10312 
10313   DiagnoseNullConversion(S, E, T, CC);
10314 
10315   S.DiscardMisalignedMemberAddress(Target, E);
10316 
10317   if (!Source->isIntegerType() || !Target->isIntegerType())
10318     return;
10319 
10320   // TODO: remove this early return once the false positives for constant->bool
10321   // in templates, macros, etc, are reduced or removed.
10322   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10323     return;
10324 
10325   IntRange SourceRange = GetExprRange(S.Context, E);
10326   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
10327 
10328   if (SourceRange.Width > TargetRange.Width) {
10329     // If the source is a constant, use a default-on diagnostic.
10330     // TODO: this should happen for bitfield stores, too.
10331     llvm::APSInt Value(32);
10332     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
10333       if (S.SourceMgr.isInSystemMacro(CC))
10334         return;
10335 
10336       std::string PrettySourceValue = Value.toString(10);
10337       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
10338 
10339       S.DiagRuntimeBehavior(E->getExprLoc(), E,
10340         S.PDiag(diag::warn_impcast_integer_precision_constant)
10341             << PrettySourceValue << PrettyTargetValue
10342             << E->getType() << T << E->getSourceRange()
10343             << clang::SourceRange(CC));
10344       return;
10345     }
10346 
10347     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10348     if (S.SourceMgr.isInSystemMacro(CC))
10349       return;
10350 
10351     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
10352       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10353                              /* pruneControlFlow */ true);
10354     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
10355   }
10356 
10357   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10358       SourceRange.NonNegative && Source->isSignedIntegerType()) {
10359     // Warn when doing a signed to signed conversion, warn if the positive
10360     // source value is exactly the width of the target type, which will
10361     // cause a negative value to be stored.
10362 
10363     llvm::APSInt Value;
10364     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10365         !S.SourceMgr.isInSystemMacro(CC)) {
10366       if (isSameWidthConstantConversion(S, E, T, CC)) {
10367         std::string PrettySourceValue = Value.toString(10);
10368         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
10369 
10370         S.DiagRuntimeBehavior(
10371             E->getExprLoc(), E,
10372             S.PDiag(diag::warn_impcast_integer_precision_constant)
10373                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10374                 << E->getSourceRange() << clang::SourceRange(CC));
10375         return;
10376       }
10377     }
10378 
10379     // Fall through for non-constants to give a sign conversion warning.
10380   }
10381 
10382   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10383       (!TargetRange.NonNegative && SourceRange.NonNegative &&
10384        SourceRange.Width == TargetRange.Width)) {
10385     if (S.SourceMgr.isInSystemMacro(CC))
10386       return;
10387 
10388     unsigned DiagID = diag::warn_impcast_integer_sign;
10389 
10390     // Traditionally, gcc has warned about this under -Wsign-compare.
10391     // We also want to warn about it in -Wconversion.
10392     // So if -Wconversion is off, use a completely identical diagnostic
10393     // in the sign-compare group.
10394     // The conditional-checking code will
10395     if (ICContext) {
10396       DiagID = diag::warn_impcast_integer_sign_conditional;
10397       *ICContext = true;
10398     }
10399 
10400     return DiagnoseImpCast(S, E, T, CC, DiagID);
10401   }
10402 
10403   // Diagnose conversions between different enumeration types.
10404   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10405   // type, to give us better diagnostics.
10406   QualType SourceType = E->getType();
10407   if (!S.getLangOpts().CPlusPlus) {
10408     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10409       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10410         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10411         SourceType = S.Context.getTypeDeclType(Enum);
10412         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10413       }
10414   }
10415 
10416   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10417     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
10418       if (SourceEnum->getDecl()->hasNameForLinkage() &&
10419           TargetEnum->getDecl()->hasNameForLinkage() &&
10420           SourceEnum != TargetEnum) {
10421         if (S.SourceMgr.isInSystemMacro(CC))
10422           return;
10423 
10424         return DiagnoseImpCast(S, E, SourceType, T, CC,
10425                                diag::warn_impcast_different_enum_types);
10426       }
10427 }
10428 
10429 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10430                                      SourceLocation CC, QualType T);
10431 
10432 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10433                                     SourceLocation CC, bool &ICContext) {
10434   E = E->IgnoreParenImpCasts();
10435 
10436   if (isa<ConditionalOperator>(E))
10437     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
10438 
10439   AnalyzeImplicitConversions(S, E, CC);
10440   if (E->getType() != T)
10441     return CheckImplicitConversion(S, E, T, CC, &ICContext);
10442 }
10443 
10444 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10445                                      SourceLocation CC, QualType T) {
10446   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
10447 
10448   bool Suspicious = false;
10449   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10450   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
10451 
10452   // If -Wconversion would have warned about either of the candidates
10453   // for a signedness conversion to the context type...
10454   if (!Suspicious) return;
10455 
10456   // ...but it's currently ignored...
10457   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
10458     return;
10459 
10460   // ...then check whether it would have warned about either of the
10461   // candidates for a signedness conversion to the condition type.
10462   if (E->getType() == T) return;
10463 
10464   Suspicious = false;
10465   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10466                           E->getType(), CC, &Suspicious);
10467   if (!Suspicious)
10468     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
10469                             E->getType(), CC, &Suspicious);
10470 }
10471 
10472 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10473 /// Input argument E is a logical expression.
10474 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
10475   if (S.getLangOpts().Bool)
10476     return;
10477   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10478 }
10479 
10480 /// AnalyzeImplicitConversions - Find and report any interesting
10481 /// implicit conversions in the given expression.  There are a couple
10482 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
10483 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10484                                        SourceLocation CC) {
10485   QualType T = OrigE->getType();
10486   Expr *E = OrigE->IgnoreParenImpCasts();
10487 
10488   if (E->isTypeDependent() || E->isValueDependent())
10489     return;
10490 
10491   // For conditional operators, we analyze the arguments as if they
10492   // were being fed directly into the output.
10493   if (isa<ConditionalOperator>(E)) {
10494     ConditionalOperator *CO = cast<ConditionalOperator>(E);
10495     CheckConditionalOperator(S, CO, CC, T);
10496     return;
10497   }
10498 
10499   // Check implicit argument conversions for function calls.
10500   if (CallExpr *Call = dyn_cast<CallExpr>(E))
10501     CheckImplicitArgumentConversions(S, Call, CC);
10502 
10503   // Go ahead and check any implicit conversions we might have skipped.
10504   // The non-canonical typecheck is just an optimization;
10505   // CheckImplicitConversion will filter out dead implicit conversions.
10506   if (E->getType() != T)
10507     CheckImplicitConversion(S, E, T, CC);
10508 
10509   // Now continue drilling into this expression.
10510 
10511   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10512     // The bound subexpressions in a PseudoObjectExpr are not reachable
10513     // as transitive children.
10514     // FIXME: Use a more uniform representation for this.
10515     for (auto *SE : POE->semantics())
10516       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10517         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
10518   }
10519 
10520   // Skip past explicit casts.
10521   if (isa<ExplicitCastExpr>(E)) {
10522     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
10523     return AnalyzeImplicitConversions(S, E, CC);
10524   }
10525 
10526   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10527     // Do a somewhat different check with comparison operators.
10528     if (BO->isComparisonOp())
10529       return AnalyzeComparison(S, BO);
10530 
10531     // And with simple assignments.
10532     if (BO->getOpcode() == BO_Assign)
10533       return AnalyzeAssignment(S, BO);
10534     // And with compound assignments.
10535     if (BO->isAssignmentOp())
10536       return AnalyzeCompoundAssignment(S, BO);
10537   }
10538 
10539   // These break the otherwise-useful invariant below.  Fortunately,
10540   // we don't really need to recurse into them, because any internal
10541   // expressions should have been analyzed already when they were
10542   // built into statements.
10543   if (isa<StmtExpr>(E)) return;
10544 
10545   // Don't descend into unevaluated contexts.
10546   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
10547 
10548   // Now just recurse over the expression's children.
10549   CC = E->getExprLoc();
10550   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
10551   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
10552   for (Stmt *SubStmt : E->children()) {
10553     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
10554     if (!ChildExpr)
10555       continue;
10556 
10557     if (IsLogicalAndOperator &&
10558         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
10559       // Ignore checking string literals that are in logical and operators.
10560       // This is a common pattern for asserts.
10561       continue;
10562     AnalyzeImplicitConversions(S, ChildExpr, CC);
10563   }
10564 
10565   if (BO && BO->isLogicalOp()) {
10566     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10567     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
10568       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
10569 
10570     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10571     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
10572       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
10573   }
10574 
10575   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10576     if (U->getOpcode() == UO_LNot)
10577       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
10578 }
10579 
10580 /// Diagnose integer type and any valid implicit conversion to it.
10581 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10582   // Taking into account implicit conversions,
10583   // allow any integer.
10584   if (!E->getType()->isIntegerType()) {
10585     S.Diag(E->getLocStart(),
10586            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10587     return true;
10588   }
10589   // Potentially emit standard warnings for implicit conversions if enabled
10590   // using -Wconversion.
10591   CheckImplicitConversion(S, E, IntT, E->getLocStart());
10592   return false;
10593 }
10594 
10595 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10596 // Returns true when emitting a warning about taking the address of a reference.
10597 static bool CheckForReference(Sema &SemaRef, const Expr *E,
10598                               const PartialDiagnostic &PD) {
10599   E = E->IgnoreParenImpCasts();
10600 
10601   const FunctionDecl *FD = nullptr;
10602 
10603   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10604     if (!DRE->getDecl()->getType()->isReferenceType())
10605       return false;
10606   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10607     if (!M->getMemberDecl()->getType()->isReferenceType())
10608       return false;
10609   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
10610     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
10611       return false;
10612     FD = Call->getDirectCallee();
10613   } else {
10614     return false;
10615   }
10616 
10617   SemaRef.Diag(E->getExprLoc(), PD);
10618 
10619   // If possible, point to location of function.
10620   if (FD) {
10621     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10622   }
10623 
10624   return true;
10625 }
10626 
10627 // Returns true if the SourceLocation is expanded from any macro body.
10628 // Returns false if the SourceLocation is invalid, is from not in a macro
10629 // expansion, or is from expanded from a top-level macro argument.
10630 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10631   if (Loc.isInvalid())
10632     return false;
10633 
10634   while (Loc.isMacroID()) {
10635     if (SM.isMacroBodyExpansion(Loc))
10636       return true;
10637     Loc = SM.getImmediateMacroCallerLoc(Loc);
10638   }
10639 
10640   return false;
10641 }
10642 
10643 /// Diagnose pointers that are always non-null.
10644 /// \param E the expression containing the pointer
10645 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10646 /// compared to a null pointer
10647 /// \param IsEqual True when the comparison is equal to a null pointer
10648 /// \param Range Extra SourceRange to highlight in the diagnostic
10649 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10650                                         Expr::NullPointerConstantKind NullKind,
10651                                         bool IsEqual, SourceRange Range) {
10652   if (!E)
10653     return;
10654 
10655   // Don't warn inside macros.
10656   if (E->getExprLoc().isMacroID()) {
10657     const SourceManager &SM = getSourceManager();
10658     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10659         IsInAnyMacroBody(SM, Range.getBegin()))
10660       return;
10661   }
10662   E = E->IgnoreImpCasts();
10663 
10664   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10665 
10666   if (isa<CXXThisExpr>(E)) {
10667     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10668                                 : diag::warn_this_bool_conversion;
10669     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10670     return;
10671   }
10672 
10673   bool IsAddressOf = false;
10674 
10675   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10676     if (UO->getOpcode() != UO_AddrOf)
10677       return;
10678     IsAddressOf = true;
10679     E = UO->getSubExpr();
10680   }
10681 
10682   if (IsAddressOf) {
10683     unsigned DiagID = IsCompare
10684                           ? diag::warn_address_of_reference_null_compare
10685                           : diag::warn_address_of_reference_bool_conversion;
10686     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10687                                          << IsEqual;
10688     if (CheckForReference(*this, E, PD)) {
10689       return;
10690     }
10691   }
10692 
10693   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10694     bool IsParam = isa<NonNullAttr>(NonnullAttr);
10695     std::string Str;
10696     llvm::raw_string_ostream S(Str);
10697     E->printPretty(S, nullptr, getPrintingPolicy());
10698     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10699                                 : diag::warn_cast_nonnull_to_bool;
10700     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10701       << E->getSourceRange() << Range << IsEqual;
10702     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10703   };
10704 
10705   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10706   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10707     if (auto *Callee = Call->getDirectCallee()) {
10708       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10709         ComplainAboutNonnullParamOrCall(A);
10710         return;
10711       }
10712     }
10713   }
10714 
10715   // Expect to find a single Decl.  Skip anything more complicated.
10716   ValueDecl *D = nullptr;
10717   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10718     D = R->getDecl();
10719   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10720     D = M->getMemberDecl();
10721   }
10722 
10723   // Weak Decls can be null.
10724   if (!D || D->isWeak())
10725     return;
10726 
10727   // Check for parameter decl with nonnull attribute
10728   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10729     if (getCurFunction() &&
10730         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10731       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10732         ComplainAboutNonnullParamOrCall(A);
10733         return;
10734       }
10735 
10736       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10737         auto ParamIter = llvm::find(FD->parameters(), PV);
10738         assert(ParamIter != FD->param_end());
10739         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10740 
10741         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10742           if (!NonNull->args_size()) {
10743               ComplainAboutNonnullParamOrCall(NonNull);
10744               return;
10745           }
10746 
10747           for (const ParamIdx &ArgNo : NonNull->args()) {
10748             if (ArgNo.getASTIndex() == ParamNo) {
10749               ComplainAboutNonnullParamOrCall(NonNull);
10750               return;
10751             }
10752           }
10753         }
10754       }
10755     }
10756   }
10757 
10758   QualType T = D->getType();
10759   const bool IsArray = T->isArrayType();
10760   const bool IsFunction = T->isFunctionType();
10761 
10762   // Address of function is used to silence the function warning.
10763   if (IsAddressOf && IsFunction) {
10764     return;
10765   }
10766 
10767   // Found nothing.
10768   if (!IsAddressOf && !IsFunction && !IsArray)
10769     return;
10770 
10771   // Pretty print the expression for the diagnostic.
10772   std::string Str;
10773   llvm::raw_string_ostream S(Str);
10774   E->printPretty(S, nullptr, getPrintingPolicy());
10775 
10776   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10777                               : diag::warn_impcast_pointer_to_bool;
10778   enum {
10779     AddressOf,
10780     FunctionPointer,
10781     ArrayPointer
10782   } DiagType;
10783   if (IsAddressOf)
10784     DiagType = AddressOf;
10785   else if (IsFunction)
10786     DiagType = FunctionPointer;
10787   else if (IsArray)
10788     DiagType = ArrayPointer;
10789   else
10790     llvm_unreachable("Could not determine diagnostic.");
10791   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10792                                 << Range << IsEqual;
10793 
10794   if (!IsFunction)
10795     return;
10796 
10797   // Suggest '&' to silence the function warning.
10798   Diag(E->getExprLoc(), diag::note_function_warning_silence)
10799       << FixItHint::CreateInsertion(E->getLocStart(), "&");
10800 
10801   // Check to see if '()' fixit should be emitted.
10802   QualType ReturnType;
10803   UnresolvedSet<4> NonTemplateOverloads;
10804   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10805   if (ReturnType.isNull())
10806     return;
10807 
10808   if (IsCompare) {
10809     // There are two cases here.  If there is null constant, the only suggest
10810     // for a pointer return type.  If the null is 0, then suggest if the return
10811     // type is a pointer or an integer type.
10812     if (!ReturnType->isPointerType()) {
10813       if (NullKind == Expr::NPCK_ZeroExpression ||
10814           NullKind == Expr::NPCK_ZeroLiteral) {
10815         if (!ReturnType->isIntegerType())
10816           return;
10817       } else {
10818         return;
10819       }
10820     }
10821   } else { // !IsCompare
10822     // For function to bool, only suggest if the function pointer has bool
10823     // return type.
10824     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10825       return;
10826   }
10827   Diag(E->getExprLoc(), diag::note_function_to_function_call)
10828       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10829 }
10830 
10831 /// Diagnoses "dangerous" implicit conversions within the given
10832 /// expression (which is a full expression).  Implements -Wconversion
10833 /// and -Wsign-compare.
10834 ///
10835 /// \param CC the "context" location of the implicit conversion, i.e.
10836 ///   the most location of the syntactic entity requiring the implicit
10837 ///   conversion
10838 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10839   // Don't diagnose in unevaluated contexts.
10840   if (isUnevaluatedContext())
10841     return;
10842 
10843   // Don't diagnose for value- or type-dependent expressions.
10844   if (E->isTypeDependent() || E->isValueDependent())
10845     return;
10846 
10847   // Check for array bounds violations in cases where the check isn't triggered
10848   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10849   // ArraySubscriptExpr is on the RHS of a variable initialization.
10850   CheckArrayAccess(E);
10851 
10852   // This is not the right CC for (e.g.) a variable initialization.
10853   AnalyzeImplicitConversions(*this, E, CC);
10854 }
10855 
10856 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10857 /// Input argument E is a logical expression.
10858 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10859   ::CheckBoolLikeConversion(*this, E, CC);
10860 }
10861 
10862 /// Diagnose when expression is an integer constant expression and its evaluation
10863 /// results in integer overflow
10864 void Sema::CheckForIntOverflow (Expr *E) {
10865   // Use a work list to deal with nested struct initializers.
10866   SmallVector<Expr *, 2> Exprs(1, E);
10867 
10868   do {
10869     Expr *OriginalE = Exprs.pop_back_val();
10870     Expr *E = OriginalE->IgnoreParenCasts();
10871 
10872     if (isa<BinaryOperator>(E)) {
10873       E->EvaluateForOverflow(Context);
10874       continue;
10875     }
10876 
10877     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
10878       Exprs.append(InitList->inits().begin(), InitList->inits().end());
10879     else if (isa<ObjCBoxedExpr>(OriginalE))
10880       E->EvaluateForOverflow(Context);
10881     else if (auto Call = dyn_cast<CallExpr>(E))
10882       Exprs.append(Call->arg_begin(), Call->arg_end());
10883     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10884       Exprs.append(Message->arg_begin(), Message->arg_end());
10885   } while (!Exprs.empty());
10886 }
10887 
10888 namespace {
10889 
10890 /// Visitor for expressions which looks for unsequenced operations on the
10891 /// same object.
10892 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10893   using Base = EvaluatedExprVisitor<SequenceChecker>;
10894 
10895   /// A tree of sequenced regions within an expression. Two regions are
10896   /// unsequenced if one is an ancestor or a descendent of the other. When we
10897   /// finish processing an expression with sequencing, such as a comma
10898   /// expression, we fold its tree nodes into its parent, since they are
10899   /// unsequenced with respect to nodes we will visit later.
10900   class SequenceTree {
10901     struct Value {
10902       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10903       unsigned Parent : 31;
10904       unsigned Merged : 1;
10905     };
10906     SmallVector<Value, 8> Values;
10907 
10908   public:
10909     /// A region within an expression which may be sequenced with respect
10910     /// to some other region.
10911     class Seq {
10912       friend class SequenceTree;
10913 
10914       unsigned Index = 0;
10915 
10916       explicit Seq(unsigned N) : Index(N) {}
10917 
10918     public:
10919       Seq() = default;
10920     };
10921 
10922     SequenceTree() { Values.push_back(Value(0)); }
10923     Seq root() const { return Seq(0); }
10924 
10925     /// Create a new sequence of operations, which is an unsequenced
10926     /// subset of \p Parent. This sequence of operations is sequenced with
10927     /// respect to other children of \p Parent.
10928     Seq allocate(Seq Parent) {
10929       Values.push_back(Value(Parent.Index));
10930       return Seq(Values.size() - 1);
10931     }
10932 
10933     /// Merge a sequence of operations into its parent.
10934     void merge(Seq S) {
10935       Values[S.Index].Merged = true;
10936     }
10937 
10938     /// Determine whether two operations are unsequenced. This operation
10939     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10940     /// should have been merged into its parent as appropriate.
10941     bool isUnsequenced(Seq Cur, Seq Old) {
10942       unsigned C = representative(Cur.Index);
10943       unsigned Target = representative(Old.Index);
10944       while (C >= Target) {
10945         if (C == Target)
10946           return true;
10947         C = Values[C].Parent;
10948       }
10949       return false;
10950     }
10951 
10952   private:
10953     /// Pick a representative for a sequence.
10954     unsigned representative(unsigned K) {
10955       if (Values[K].Merged)
10956         // Perform path compression as we go.
10957         return Values[K].Parent = representative(Values[K].Parent);
10958       return K;
10959     }
10960   };
10961 
10962   /// An object for which we can track unsequenced uses.
10963   using Object = NamedDecl *;
10964 
10965   /// Different flavors of object usage which we track. We only track the
10966   /// least-sequenced usage of each kind.
10967   enum UsageKind {
10968     /// A read of an object. Multiple unsequenced reads are OK.
10969     UK_Use,
10970 
10971     /// A modification of an object which is sequenced before the value
10972     /// computation of the expression, such as ++n in C++.
10973     UK_ModAsValue,
10974 
10975     /// A modification of an object which is not sequenced before the value
10976     /// computation of the expression, such as n++.
10977     UK_ModAsSideEffect,
10978 
10979     UK_Count = UK_ModAsSideEffect + 1
10980   };
10981 
10982   struct Usage {
10983     Expr *Use = nullptr;
10984     SequenceTree::Seq Seq;
10985 
10986     Usage() = default;
10987   };
10988 
10989   struct UsageInfo {
10990     Usage Uses[UK_Count];
10991 
10992     /// Have we issued a diagnostic for this variable already?
10993     bool Diagnosed = false;
10994 
10995     UsageInfo() = default;
10996   };
10997   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
10998 
10999   Sema &SemaRef;
11000 
11001   /// Sequenced regions within the expression.
11002   SequenceTree Tree;
11003 
11004   /// Declaration modifications and references which we have seen.
11005   UsageInfoMap UsageMap;
11006 
11007   /// The region we are currently within.
11008   SequenceTree::Seq Region;
11009 
11010   /// Filled in with declarations which were modified as a side-effect
11011   /// (that is, post-increment operations).
11012   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11013 
11014   /// Expressions to check later. We defer checking these to reduce
11015   /// stack usage.
11016   SmallVectorImpl<Expr *> &WorkList;
11017 
11018   /// RAII object wrapping the visitation of a sequenced subexpression of an
11019   /// expression. At the end of this process, the side-effects of the evaluation
11020   /// become sequenced with respect to the value computation of the result, so
11021   /// we downgrade any UK_ModAsSideEffect within the evaluation to
11022   /// UK_ModAsValue.
11023   struct SequencedSubexpression {
11024     SequencedSubexpression(SequenceChecker &Self)
11025       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11026       Self.ModAsSideEffect = &ModAsSideEffect;
11027     }
11028 
11029     ~SequencedSubexpression() {
11030       for (auto &M : llvm::reverse(ModAsSideEffect)) {
11031         UsageInfo &U = Self.UsageMap[M.first];
11032         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
11033         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11034         SideEffectUsage = M.second;
11035       }
11036       Self.ModAsSideEffect = OldModAsSideEffect;
11037     }
11038 
11039     SequenceChecker &Self;
11040     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
11041     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
11042   };
11043 
11044   /// RAII object wrapping the visitation of a subexpression which we might
11045   /// choose to evaluate as a constant. If any subexpression is evaluated and
11046   /// found to be non-constant, this allows us to suppress the evaluation of
11047   /// the outer expression.
11048   class EvaluationTracker {
11049   public:
11050     EvaluationTracker(SequenceChecker &Self)
11051         : Self(Self), Prev(Self.EvalTracker) {
11052       Self.EvalTracker = this;
11053     }
11054 
11055     ~EvaluationTracker() {
11056       Self.EvalTracker = Prev;
11057       if (Prev)
11058         Prev->EvalOK &= EvalOK;
11059     }
11060 
11061     bool evaluate(const Expr *E, bool &Result) {
11062       if (!EvalOK || E->isValueDependent())
11063         return false;
11064       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11065       return EvalOK;
11066     }
11067 
11068   private:
11069     SequenceChecker &Self;
11070     EvaluationTracker *Prev;
11071     bool EvalOK = true;
11072   } *EvalTracker = nullptr;
11073 
11074   /// Find the object which is produced by the specified expression,
11075   /// if any.
11076   Object getObject(Expr *E, bool Mod) const {
11077     E = E->IgnoreParenCasts();
11078     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11079       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11080         return getObject(UO->getSubExpr(), Mod);
11081     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11082       if (BO->getOpcode() == BO_Comma)
11083         return getObject(BO->getRHS(), Mod);
11084       if (Mod && BO->isAssignmentOp())
11085         return getObject(BO->getLHS(), Mod);
11086     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11087       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11088       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11089         return ME->getMemberDecl();
11090     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11091       // FIXME: If this is a reference, map through to its value.
11092       return DRE->getDecl();
11093     return nullptr;
11094   }
11095 
11096   /// Note that an object was modified or used by an expression.
11097   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11098     Usage &U = UI.Uses[UK];
11099     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11100       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11101         ModAsSideEffect->push_back(std::make_pair(O, U));
11102       U.Use = Ref;
11103       U.Seq = Region;
11104     }
11105   }
11106 
11107   /// Check whether a modification or use conflicts with a prior usage.
11108   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11109                   bool IsModMod) {
11110     if (UI.Diagnosed)
11111       return;
11112 
11113     const Usage &U = UI.Uses[OtherKind];
11114     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11115       return;
11116 
11117     Expr *Mod = U.Use;
11118     Expr *ModOrUse = Ref;
11119     if (OtherKind == UK_Use)
11120       std::swap(Mod, ModOrUse);
11121 
11122     SemaRef.Diag(Mod->getExprLoc(),
11123                  IsModMod ? diag::warn_unsequenced_mod_mod
11124                           : diag::warn_unsequenced_mod_use)
11125       << O << SourceRange(ModOrUse->getExprLoc());
11126     UI.Diagnosed = true;
11127   }
11128 
11129   void notePreUse(Object O, Expr *Use) {
11130     UsageInfo &U = UsageMap[O];
11131     // Uses conflict with other modifications.
11132     checkUsage(O, U, Use, UK_ModAsValue, false);
11133   }
11134 
11135   void notePostUse(Object O, Expr *Use) {
11136     UsageInfo &U = UsageMap[O];
11137     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11138     addUsage(U, O, Use, UK_Use);
11139   }
11140 
11141   void notePreMod(Object O, Expr *Mod) {
11142     UsageInfo &U = UsageMap[O];
11143     // Modifications conflict with other modifications and with uses.
11144     checkUsage(O, U, Mod, UK_ModAsValue, true);
11145     checkUsage(O, U, Mod, UK_Use, false);
11146   }
11147 
11148   void notePostMod(Object O, Expr *Use, UsageKind UK) {
11149     UsageInfo &U = UsageMap[O];
11150     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11151     addUsage(U, O, Use, UK);
11152   }
11153 
11154 public:
11155   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
11156       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
11157     Visit(E);
11158   }
11159 
11160   void VisitStmt(Stmt *S) {
11161     // Skip all statements which aren't expressions for now.
11162   }
11163 
11164   void VisitExpr(Expr *E) {
11165     // By default, just recurse to evaluated subexpressions.
11166     Base::VisitStmt(E);
11167   }
11168 
11169   void VisitCastExpr(CastExpr *E) {
11170     Object O = Object();
11171     if (E->getCastKind() == CK_LValueToRValue)
11172       O = getObject(E->getSubExpr(), false);
11173 
11174     if (O)
11175       notePreUse(O, E);
11176     VisitExpr(E);
11177     if (O)
11178       notePostUse(O, E);
11179   }
11180 
11181   void VisitBinComma(BinaryOperator *BO) {
11182     // C++11 [expr.comma]p1:
11183     //   Every value computation and side effect associated with the left
11184     //   expression is sequenced before every value computation and side
11185     //   effect associated with the right expression.
11186     SequenceTree::Seq LHS = Tree.allocate(Region);
11187     SequenceTree::Seq RHS = Tree.allocate(Region);
11188     SequenceTree::Seq OldRegion = Region;
11189 
11190     {
11191       SequencedSubexpression SeqLHS(*this);
11192       Region = LHS;
11193       Visit(BO->getLHS());
11194     }
11195 
11196     Region = RHS;
11197     Visit(BO->getRHS());
11198 
11199     Region = OldRegion;
11200 
11201     // Forget that LHS and RHS are sequenced. They are both unsequenced
11202     // with respect to other stuff.
11203     Tree.merge(LHS);
11204     Tree.merge(RHS);
11205   }
11206 
11207   void VisitBinAssign(BinaryOperator *BO) {
11208     // The modification is sequenced after the value computation of the LHS
11209     // and RHS, so check it before inspecting the operands and update the
11210     // map afterwards.
11211     Object O = getObject(BO->getLHS(), true);
11212     if (!O)
11213       return VisitExpr(BO);
11214 
11215     notePreMod(O, BO);
11216 
11217     // C++11 [expr.ass]p7:
11218     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11219     //   only once.
11220     //
11221     // Therefore, for a compound assignment operator, O is considered used
11222     // everywhere except within the evaluation of E1 itself.
11223     if (isa<CompoundAssignOperator>(BO))
11224       notePreUse(O, BO);
11225 
11226     Visit(BO->getLHS());
11227 
11228     if (isa<CompoundAssignOperator>(BO))
11229       notePostUse(O, BO);
11230 
11231     Visit(BO->getRHS());
11232 
11233     // C++11 [expr.ass]p1:
11234     //   the assignment is sequenced [...] before the value computation of the
11235     //   assignment expression.
11236     // C11 6.5.16/3 has no such rule.
11237     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11238                                                        : UK_ModAsSideEffect);
11239   }
11240 
11241   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11242     VisitBinAssign(CAO);
11243   }
11244 
11245   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11246   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11247   void VisitUnaryPreIncDec(UnaryOperator *UO) {
11248     Object O = getObject(UO->getSubExpr(), true);
11249     if (!O)
11250       return VisitExpr(UO);
11251 
11252     notePreMod(O, UO);
11253     Visit(UO->getSubExpr());
11254     // C++11 [expr.pre.incr]p1:
11255     //   the expression ++x is equivalent to x+=1
11256     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11257                                                        : UK_ModAsSideEffect);
11258   }
11259 
11260   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11261   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11262   void VisitUnaryPostIncDec(UnaryOperator *UO) {
11263     Object O = getObject(UO->getSubExpr(), true);
11264     if (!O)
11265       return VisitExpr(UO);
11266 
11267     notePreMod(O, UO);
11268     Visit(UO->getSubExpr());
11269     notePostMod(O, UO, UK_ModAsSideEffect);
11270   }
11271 
11272   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11273   void VisitBinLOr(BinaryOperator *BO) {
11274     // The side-effects of the LHS of an '&&' are sequenced before the
11275     // value computation of the RHS, and hence before the value computation
11276     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11277     // as if they were unconditionally sequenced.
11278     EvaluationTracker Eval(*this);
11279     {
11280       SequencedSubexpression Sequenced(*this);
11281       Visit(BO->getLHS());
11282     }
11283 
11284     bool Result;
11285     if (Eval.evaluate(BO->getLHS(), Result)) {
11286       if (!Result)
11287         Visit(BO->getRHS());
11288     } else {
11289       // Check for unsequenced operations in the RHS, treating it as an
11290       // entirely separate evaluation.
11291       //
11292       // FIXME: If there are operations in the RHS which are unsequenced
11293       // with respect to operations outside the RHS, and those operations
11294       // are unconditionally evaluated, diagnose them.
11295       WorkList.push_back(BO->getRHS());
11296     }
11297   }
11298   void VisitBinLAnd(BinaryOperator *BO) {
11299     EvaluationTracker Eval(*this);
11300     {
11301       SequencedSubexpression Sequenced(*this);
11302       Visit(BO->getLHS());
11303     }
11304 
11305     bool Result;
11306     if (Eval.evaluate(BO->getLHS(), Result)) {
11307       if (Result)
11308         Visit(BO->getRHS());
11309     } else {
11310       WorkList.push_back(BO->getRHS());
11311     }
11312   }
11313 
11314   // Only visit the condition, unless we can be sure which subexpression will
11315   // be chosen.
11316   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
11317     EvaluationTracker Eval(*this);
11318     {
11319       SequencedSubexpression Sequenced(*this);
11320       Visit(CO->getCond());
11321     }
11322 
11323     bool Result;
11324     if (Eval.evaluate(CO->getCond(), Result))
11325       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
11326     else {
11327       WorkList.push_back(CO->getTrueExpr());
11328       WorkList.push_back(CO->getFalseExpr());
11329     }
11330   }
11331 
11332   void VisitCallExpr(CallExpr *CE) {
11333     // C++11 [intro.execution]p15:
11334     //   When calling a function [...], every value computation and side effect
11335     //   associated with any argument expression, or with the postfix expression
11336     //   designating the called function, is sequenced before execution of every
11337     //   expression or statement in the body of the function [and thus before
11338     //   the value computation of its result].
11339     SequencedSubexpression Sequenced(*this);
11340     Base::VisitCallExpr(CE);
11341 
11342     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11343   }
11344 
11345   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
11346     // This is a call, so all subexpressions are sequenced before the result.
11347     SequencedSubexpression Sequenced(*this);
11348 
11349     if (!CCE->isListInitialization())
11350       return VisitExpr(CCE);
11351 
11352     // In C++11, list initializations are sequenced.
11353     SmallVector<SequenceTree::Seq, 32> Elts;
11354     SequenceTree::Seq Parent = Region;
11355     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11356                                         E = CCE->arg_end();
11357          I != E; ++I) {
11358       Region = Tree.allocate(Parent);
11359       Elts.push_back(Region);
11360       Visit(*I);
11361     }
11362 
11363     // Forget that the initializers are sequenced.
11364     Region = Parent;
11365     for (unsigned I = 0; I < Elts.size(); ++I)
11366       Tree.merge(Elts[I]);
11367   }
11368 
11369   void VisitInitListExpr(InitListExpr *ILE) {
11370     if (!SemaRef.getLangOpts().CPlusPlus11)
11371       return VisitExpr(ILE);
11372 
11373     // In C++11, list initializations are sequenced.
11374     SmallVector<SequenceTree::Seq, 32> Elts;
11375     SequenceTree::Seq Parent = Region;
11376     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11377       Expr *E = ILE->getInit(I);
11378       if (!E) continue;
11379       Region = Tree.allocate(Parent);
11380       Elts.push_back(Region);
11381       Visit(E);
11382     }
11383 
11384     // Forget that the initializers are sequenced.
11385     Region = Parent;
11386     for (unsigned I = 0; I < Elts.size(); ++I)
11387       Tree.merge(Elts[I]);
11388   }
11389 };
11390 
11391 } // namespace
11392 
11393 void Sema::CheckUnsequencedOperations(Expr *E) {
11394   SmallVector<Expr *, 8> WorkList;
11395   WorkList.push_back(E);
11396   while (!WorkList.empty()) {
11397     Expr *Item = WorkList.pop_back_val();
11398     SequenceChecker(*this, Item, WorkList);
11399   }
11400 }
11401 
11402 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11403                               bool IsConstexpr) {
11404   CheckImplicitConversions(E, CheckLoc);
11405   if (!E->isInstantiationDependent())
11406     CheckUnsequencedOperations(E);
11407   if (!IsConstexpr && !E->isValueDependent())
11408     CheckForIntOverflow(E);
11409   DiagnoseMisalignedMembers();
11410 }
11411 
11412 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11413                                        FieldDecl *BitField,
11414                                        Expr *Init) {
11415   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11416 }
11417 
11418 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11419                                          SourceLocation Loc) {
11420   if (!PType->isVariablyModifiedType())
11421     return;
11422   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11423     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11424     return;
11425   }
11426   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11427     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11428     return;
11429   }
11430   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11431     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11432     return;
11433   }
11434 
11435   const ArrayType *AT = S.Context.getAsArrayType(PType);
11436   if (!AT)
11437     return;
11438 
11439   if (AT->getSizeModifier() != ArrayType::Star) {
11440     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11441     return;
11442   }
11443 
11444   S.Diag(Loc, diag::err_array_star_in_function_definition);
11445 }
11446 
11447 /// CheckParmsForFunctionDef - Check that the parameters of the given
11448 /// function are appropriate for the definition of a function. This
11449 /// takes care of any checks that cannot be performed on the
11450 /// declaration itself, e.g., that the types of each of the function
11451 /// parameters are complete.
11452 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
11453                                     bool CheckParameterNames) {
11454   bool HasInvalidParm = false;
11455   for (ParmVarDecl *Param : Parameters) {
11456     // C99 6.7.5.3p4: the parameters in a parameter type list in a
11457     // function declarator that is part of a function definition of
11458     // that function shall not have incomplete type.
11459     //
11460     // This is also C++ [dcl.fct]p6.
11461     if (!Param->isInvalidDecl() &&
11462         RequireCompleteType(Param->getLocation(), Param->getType(),
11463                             diag::err_typecheck_decl_incomplete_type)) {
11464       Param->setInvalidDecl();
11465       HasInvalidParm = true;
11466     }
11467 
11468     // C99 6.9.1p5: If the declarator includes a parameter type list, the
11469     // declaration of each parameter shall include an identifier.
11470     if (CheckParameterNames &&
11471         Param->getIdentifier() == nullptr &&
11472         !Param->isImplicit() &&
11473         !getLangOpts().CPlusPlus)
11474       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
11475 
11476     // C99 6.7.5.3p12:
11477     //   If the function declarator is not part of a definition of that
11478     //   function, parameters may have incomplete type and may use the [*]
11479     //   notation in their sequences of declarator specifiers to specify
11480     //   variable length array types.
11481     QualType PType = Param->getOriginalType();
11482     // FIXME: This diagnostic should point the '[*]' if source-location
11483     // information is added for it.
11484     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
11485 
11486     // If the parameter is a c++ class type and it has to be destructed in the
11487     // callee function, declare the destructor so that it can be called by the
11488     // callee function. Do not perform any direct access check on the dtor here.
11489     if (!Param->isInvalidDecl()) {
11490       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11491         if (!ClassDecl->isInvalidDecl() &&
11492             !ClassDecl->hasIrrelevantDestructor() &&
11493             !ClassDecl->isDependentContext() &&
11494             ClassDecl->isParamDestroyedInCallee()) {
11495           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11496           MarkFunctionReferenced(Param->getLocation(), Destructor);
11497           DiagnoseUseOfDecl(Destructor, Param->getLocation());
11498         }
11499       }
11500     }
11501 
11502     // Parameters with the pass_object_size attribute only need to be marked
11503     // constant at function definitions. Because we lack information about
11504     // whether we're on a declaration or definition when we're instantiating the
11505     // attribute, we need to check for constness here.
11506     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11507       if (!Param->getType().isConstQualified())
11508         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11509             << Attr->getSpelling() << 1;
11510   }
11511 
11512   return HasInvalidParm;
11513 }
11514 
11515 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11516 /// or MemberExpr.
11517 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11518                               ASTContext &Context) {
11519   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11520     return Context.getDeclAlign(DRE->getDecl());
11521 
11522   if (const auto *ME = dyn_cast<MemberExpr>(E))
11523     return Context.getDeclAlign(ME->getMemberDecl());
11524 
11525   return TypeAlign;
11526 }
11527 
11528 /// CheckCastAlign - Implements -Wcast-align, which warns when a
11529 /// pointer cast increases the alignment requirements.
11530 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11531   // This is actually a lot of work to potentially be doing on every
11532   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
11533   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
11534     return;
11535 
11536   // Ignore dependent types.
11537   if (T->isDependentType() || Op->getType()->isDependentType())
11538     return;
11539 
11540   // Require that the destination be a pointer type.
11541   const PointerType *DestPtr = T->getAs<PointerType>();
11542   if (!DestPtr) return;
11543 
11544   // If the destination has alignment 1, we're done.
11545   QualType DestPointee = DestPtr->getPointeeType();
11546   if (DestPointee->isIncompleteType()) return;
11547   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11548   if (DestAlign.isOne()) return;
11549 
11550   // Require that the source be a pointer type.
11551   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11552   if (!SrcPtr) return;
11553   QualType SrcPointee = SrcPtr->getPointeeType();
11554 
11555   // Whitelist casts from cv void*.  We already implicitly
11556   // whitelisted casts to cv void*, since they have alignment 1.
11557   // Also whitelist casts involving incomplete types, which implicitly
11558   // includes 'void'.
11559   if (SrcPointee->isIncompleteType()) return;
11560 
11561   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
11562 
11563   if (auto *CE = dyn_cast<CastExpr>(Op)) {
11564     if (CE->getCastKind() == CK_ArrayToPointerDecay)
11565       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11566   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11567     if (UO->getOpcode() == UO_AddrOf)
11568       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11569   }
11570 
11571   if (SrcAlign >= DestAlign) return;
11572 
11573   Diag(TRange.getBegin(), diag::warn_cast_align)
11574     << Op->getType() << T
11575     << static_cast<unsigned>(SrcAlign.getQuantity())
11576     << static_cast<unsigned>(DestAlign.getQuantity())
11577     << TRange << Op->getSourceRange();
11578 }
11579 
11580 /// Check whether this array fits the idiom of a size-one tail padded
11581 /// array member of a struct.
11582 ///
11583 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
11584 /// commonly used to emulate flexible arrays in C89 code.
11585 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
11586                                     const NamedDecl *ND) {
11587   if (Size != 1 || !ND) return false;
11588 
11589   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11590   if (!FD) return false;
11591 
11592   // Don't consider sizes resulting from macro expansions or template argument
11593   // substitution to form C89 tail-padded arrays.
11594 
11595   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
11596   while (TInfo) {
11597     TypeLoc TL = TInfo->getTypeLoc();
11598     // Look through typedefs.
11599     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11600       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
11601       TInfo = TDL->getTypeSourceInfo();
11602       continue;
11603     }
11604     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11605       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
11606       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11607         return false;
11608     }
11609     break;
11610   }
11611 
11612   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
11613   if (!RD) return false;
11614   if (RD->isUnion()) return false;
11615   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11616     if (!CRD->isStandardLayout()) return false;
11617   }
11618 
11619   // See if this is the last field decl in the record.
11620   const Decl *D = FD;
11621   while ((D = D->getNextDeclInContext()))
11622     if (isa<FieldDecl>(D))
11623       return false;
11624   return true;
11625 }
11626 
11627 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
11628                             const ArraySubscriptExpr *ASE,
11629                             bool AllowOnePastEnd, bool IndexNegated) {
11630   IndexExpr = IndexExpr->IgnoreParenImpCasts();
11631   if (IndexExpr->isValueDependent())
11632     return;
11633 
11634   const Type *EffectiveType =
11635       BaseExpr->getType()->getPointeeOrArrayElementType();
11636   BaseExpr = BaseExpr->IgnoreParenCasts();
11637   const ConstantArrayType *ArrayTy =
11638     Context.getAsConstantArrayType(BaseExpr->getType());
11639   if (!ArrayTy)
11640     return;
11641 
11642   llvm::APSInt index;
11643   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
11644     return;
11645   if (IndexNegated)
11646     index = -index;
11647 
11648   const NamedDecl *ND = nullptr;
11649   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11650     ND = DRE->getDecl();
11651   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11652     ND = ME->getMemberDecl();
11653 
11654   if (index.isUnsigned() || !index.isNegative()) {
11655     llvm::APInt size = ArrayTy->getSize();
11656     if (!size.isStrictlyPositive())
11657       return;
11658 
11659     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
11660     if (BaseType != EffectiveType) {
11661       // Make sure we're comparing apples to apples when comparing index to size
11662       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11663       uint64_t array_typesize = Context.getTypeSize(BaseType);
11664       // Handle ptrarith_typesize being zero, such as when casting to void*
11665       if (!ptrarith_typesize) ptrarith_typesize = 1;
11666       if (ptrarith_typesize != array_typesize) {
11667         // There's a cast to a different size type involved
11668         uint64_t ratio = array_typesize / ptrarith_typesize;
11669         // TODO: Be smarter about handling cases where array_typesize is not a
11670         // multiple of ptrarith_typesize
11671         if (ptrarith_typesize * ratio == array_typesize)
11672           size *= llvm::APInt(size.getBitWidth(), ratio);
11673       }
11674     }
11675 
11676     if (size.getBitWidth() > index.getBitWidth())
11677       index = index.zext(size.getBitWidth());
11678     else if (size.getBitWidth() < index.getBitWidth())
11679       size = size.zext(index.getBitWidth());
11680 
11681     // For array subscripting the index must be less than size, but for pointer
11682     // arithmetic also allow the index (offset) to be equal to size since
11683     // computing the next address after the end of the array is legal and
11684     // commonly done e.g. in C++ iterators and range-based for loops.
11685     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11686       return;
11687 
11688     // Also don't warn for arrays of size 1 which are members of some
11689     // structure. These are often used to approximate flexible arrays in C89
11690     // code.
11691     if (IsTailPaddedMemberArray(*this, size, ND))
11692       return;
11693 
11694     // Suppress the warning if the subscript expression (as identified by the
11695     // ']' location) and the index expression are both from macro expansions
11696     // within a system header.
11697     if (ASE) {
11698       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11699           ASE->getRBracketLoc());
11700       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11701         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11702             IndexExpr->getLocStart());
11703         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11704           return;
11705       }
11706     }
11707 
11708     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11709     if (ASE)
11710       DiagID = diag::warn_array_index_exceeds_bounds;
11711 
11712     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11713                         PDiag(DiagID) << index.toString(10, true)
11714                           << size.toString(10, true)
11715                           << (unsigned)size.getLimitedValue(~0U)
11716                           << IndexExpr->getSourceRange());
11717   } else {
11718     unsigned DiagID = diag::warn_array_index_precedes_bounds;
11719     if (!ASE) {
11720       DiagID = diag::warn_ptr_arith_precedes_bounds;
11721       if (index.isNegative()) index = -index;
11722     }
11723 
11724     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11725                         PDiag(DiagID) << index.toString(10, true)
11726                           << IndexExpr->getSourceRange());
11727   }
11728 
11729   if (!ND) {
11730     // Try harder to find a NamedDecl to point at in the note.
11731     while (const ArraySubscriptExpr *ASE =
11732            dyn_cast<ArraySubscriptExpr>(BaseExpr))
11733       BaseExpr = ASE->getBase()->IgnoreParenCasts();
11734     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11735       ND = DRE->getDecl();
11736     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11737       ND = ME->getMemberDecl();
11738   }
11739 
11740   if (ND)
11741     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11742                         PDiag(diag::note_array_index_out_of_bounds)
11743                           << ND->getDeclName());
11744 }
11745 
11746 void Sema::CheckArrayAccess(const Expr *expr) {
11747   int AllowOnePastEnd = 0;
11748   while (expr) {
11749     expr = expr->IgnoreParenImpCasts();
11750     switch (expr->getStmtClass()) {
11751       case Stmt::ArraySubscriptExprClass: {
11752         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11753         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11754                          AllowOnePastEnd > 0);
11755         expr = ASE->getBase();
11756         break;
11757       }
11758       case Stmt::MemberExprClass: {
11759         expr = cast<MemberExpr>(expr)->getBase();
11760         break;
11761       }
11762       case Stmt::OMPArraySectionExprClass: {
11763         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11764         if (ASE->getLowerBound())
11765           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11766                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
11767         return;
11768       }
11769       case Stmt::UnaryOperatorClass: {
11770         // Only unwrap the * and & unary operators
11771         const UnaryOperator *UO = cast<UnaryOperator>(expr);
11772         expr = UO->getSubExpr();
11773         switch (UO->getOpcode()) {
11774           case UO_AddrOf:
11775             AllowOnePastEnd++;
11776             break;
11777           case UO_Deref:
11778             AllowOnePastEnd--;
11779             break;
11780           default:
11781             return;
11782         }
11783         break;
11784       }
11785       case Stmt::ConditionalOperatorClass: {
11786         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11787         if (const Expr *lhs = cond->getLHS())
11788           CheckArrayAccess(lhs);
11789         if (const Expr *rhs = cond->getRHS())
11790           CheckArrayAccess(rhs);
11791         return;
11792       }
11793       case Stmt::CXXOperatorCallExprClass: {
11794         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11795         for (const auto *Arg : OCE->arguments())
11796           CheckArrayAccess(Arg);
11797         return;
11798       }
11799       default:
11800         return;
11801     }
11802   }
11803 }
11804 
11805 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11806 
11807 namespace {
11808 
11809 struct RetainCycleOwner {
11810   VarDecl *Variable = nullptr;
11811   SourceRange Range;
11812   SourceLocation Loc;
11813   bool Indirect = false;
11814 
11815   RetainCycleOwner() = default;
11816 
11817   void setLocsFrom(Expr *e) {
11818     Loc = e->getExprLoc();
11819     Range = e->getSourceRange();
11820   }
11821 };
11822 
11823 } // namespace
11824 
11825 /// Consider whether capturing the given variable can possibly lead to
11826 /// a retain cycle.
11827 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11828   // In ARC, it's captured strongly iff the variable has __strong
11829   // lifetime.  In MRR, it's captured strongly if the variable is
11830   // __block and has an appropriate type.
11831   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11832     return false;
11833 
11834   owner.Variable = var;
11835   if (ref)
11836     owner.setLocsFrom(ref);
11837   return true;
11838 }
11839 
11840 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11841   while (true) {
11842     e = e->IgnoreParens();
11843     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11844       switch (cast->getCastKind()) {
11845       case CK_BitCast:
11846       case CK_LValueBitCast:
11847       case CK_LValueToRValue:
11848       case CK_ARCReclaimReturnedObject:
11849         e = cast->getSubExpr();
11850         continue;
11851 
11852       default:
11853         return false;
11854       }
11855     }
11856 
11857     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11858       ObjCIvarDecl *ivar = ref->getDecl();
11859       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11860         return false;
11861 
11862       // Try to find a retain cycle in the base.
11863       if (!findRetainCycleOwner(S, ref->getBase(), owner))
11864         return false;
11865 
11866       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11867       owner.Indirect = true;
11868       return true;
11869     }
11870 
11871     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11872       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11873       if (!var) return false;
11874       return considerVariable(var, ref, owner);
11875     }
11876 
11877     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11878       if (member->isArrow()) return false;
11879 
11880       // Don't count this as an indirect ownership.
11881       e = member->getBase();
11882       continue;
11883     }
11884 
11885     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11886       // Only pay attention to pseudo-objects on property references.
11887       ObjCPropertyRefExpr *pre
11888         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11889                                               ->IgnoreParens());
11890       if (!pre) return false;
11891       if (pre->isImplicitProperty()) return false;
11892       ObjCPropertyDecl *property = pre->getExplicitProperty();
11893       if (!property->isRetaining() &&
11894           !(property->getPropertyIvarDecl() &&
11895             property->getPropertyIvarDecl()->getType()
11896               .getObjCLifetime() == Qualifiers::OCL_Strong))
11897           return false;
11898 
11899       owner.Indirect = true;
11900       if (pre->isSuperReceiver()) {
11901         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11902         if (!owner.Variable)
11903           return false;
11904         owner.Loc = pre->getLocation();
11905         owner.Range = pre->getSourceRange();
11906         return true;
11907       }
11908       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11909                               ->getSourceExpr());
11910       continue;
11911     }
11912 
11913     // Array ivars?
11914 
11915     return false;
11916   }
11917 }
11918 
11919 namespace {
11920 
11921   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11922     ASTContext &Context;
11923     VarDecl *Variable;
11924     Expr *Capturer = nullptr;
11925     bool VarWillBeReased = false;
11926 
11927     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11928         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11929           Context(Context), Variable(variable) {}
11930 
11931     void VisitDeclRefExpr(DeclRefExpr *ref) {
11932       if (ref->getDecl() == Variable && !Capturer)
11933         Capturer = ref;
11934     }
11935 
11936     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11937       if (Capturer) return;
11938       Visit(ref->getBase());
11939       if (Capturer && ref->isFreeIvar())
11940         Capturer = ref;
11941     }
11942 
11943     void VisitBlockExpr(BlockExpr *block) {
11944       // Look inside nested blocks
11945       if (block->getBlockDecl()->capturesVariable(Variable))
11946         Visit(block->getBlockDecl()->getBody());
11947     }
11948 
11949     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11950       if (Capturer) return;
11951       if (OVE->getSourceExpr())
11952         Visit(OVE->getSourceExpr());
11953     }
11954 
11955     void VisitBinaryOperator(BinaryOperator *BinOp) {
11956       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11957         return;
11958       Expr *LHS = BinOp->getLHS();
11959       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11960         if (DRE->getDecl() != Variable)
11961           return;
11962         if (Expr *RHS = BinOp->getRHS()) {
11963           RHS = RHS->IgnoreParenCasts();
11964           llvm::APSInt Value;
11965           VarWillBeReased =
11966             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11967         }
11968       }
11969     }
11970   };
11971 
11972 } // namespace
11973 
11974 /// Check whether the given argument is a block which captures a
11975 /// variable.
11976 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11977   assert(owner.Variable && owner.Loc.isValid());
11978 
11979   e = e->IgnoreParenCasts();
11980 
11981   // Look through [^{...} copy] and Block_copy(^{...}).
11982   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11983     Selector Cmd = ME->getSelector();
11984     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11985       e = ME->getInstanceReceiver();
11986       if (!e)
11987         return nullptr;
11988       e = e->IgnoreParenCasts();
11989     }
11990   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11991     if (CE->getNumArgs() == 1) {
11992       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11993       if (Fn) {
11994         const IdentifierInfo *FnI = Fn->getIdentifier();
11995         if (FnI && FnI->isStr("_Block_copy")) {
11996           e = CE->getArg(0)->IgnoreParenCasts();
11997         }
11998       }
11999     }
12000   }
12001 
12002   BlockExpr *block = dyn_cast<BlockExpr>(e);
12003   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
12004     return nullptr;
12005 
12006   FindCaptureVisitor visitor(S.Context, owner.Variable);
12007   visitor.Visit(block->getBlockDecl()->getBody());
12008   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
12009 }
12010 
12011 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12012                                 RetainCycleOwner &owner) {
12013   assert(capturer);
12014   assert(owner.Variable && owner.Loc.isValid());
12015 
12016   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12017     << owner.Variable << capturer->getSourceRange();
12018   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12019     << owner.Indirect << owner.Range;
12020 }
12021 
12022 /// Check for a keyword selector that starts with the word 'add' or
12023 /// 'set'.
12024 static bool isSetterLikeSelector(Selector sel) {
12025   if (sel.isUnarySelector()) return false;
12026 
12027   StringRef str = sel.getNameForSlot(0);
12028   while (!str.empty() && str.front() == '_') str = str.substr(1);
12029   if (str.startswith("set"))
12030     str = str.substr(3);
12031   else if (str.startswith("add")) {
12032     // Specially whitelist 'addOperationWithBlock:'.
12033     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12034       return false;
12035     str = str.substr(3);
12036   }
12037   else
12038     return false;
12039 
12040   if (str.empty()) return true;
12041   return !isLowercase(str.front());
12042 }
12043 
12044 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12045                                                     ObjCMessageExpr *Message) {
12046   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12047                                                 Message->getReceiverInterface(),
12048                                                 NSAPI::ClassId_NSMutableArray);
12049   if (!IsMutableArray) {
12050     return None;
12051   }
12052 
12053   Selector Sel = Message->getSelector();
12054 
12055   Optional<NSAPI::NSArrayMethodKind> MKOpt =
12056     S.NSAPIObj->getNSArrayMethodKind(Sel);
12057   if (!MKOpt) {
12058     return None;
12059   }
12060 
12061   NSAPI::NSArrayMethodKind MK = *MKOpt;
12062 
12063   switch (MK) {
12064     case NSAPI::NSMutableArr_addObject:
12065     case NSAPI::NSMutableArr_insertObjectAtIndex:
12066     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12067       return 0;
12068     case NSAPI::NSMutableArr_replaceObjectAtIndex:
12069       return 1;
12070 
12071     default:
12072       return None;
12073   }
12074 
12075   return None;
12076 }
12077 
12078 static
12079 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12080                                                   ObjCMessageExpr *Message) {
12081   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12082                                             Message->getReceiverInterface(),
12083                                             NSAPI::ClassId_NSMutableDictionary);
12084   if (!IsMutableDictionary) {
12085     return None;
12086   }
12087 
12088   Selector Sel = Message->getSelector();
12089 
12090   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12091     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12092   if (!MKOpt) {
12093     return None;
12094   }
12095 
12096   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12097 
12098   switch (MK) {
12099     case NSAPI::NSMutableDict_setObjectForKey:
12100     case NSAPI::NSMutableDict_setValueForKey:
12101     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12102       return 0;
12103 
12104     default:
12105       return None;
12106   }
12107 
12108   return None;
12109 }
12110 
12111 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
12112   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12113                                                 Message->getReceiverInterface(),
12114                                                 NSAPI::ClassId_NSMutableSet);
12115 
12116   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12117                                             Message->getReceiverInterface(),
12118                                             NSAPI::ClassId_NSMutableOrderedSet);
12119   if (!IsMutableSet && !IsMutableOrderedSet) {
12120     return None;
12121   }
12122 
12123   Selector Sel = Message->getSelector();
12124 
12125   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12126   if (!MKOpt) {
12127     return None;
12128   }
12129 
12130   NSAPI::NSSetMethodKind MK = *MKOpt;
12131 
12132   switch (MK) {
12133     case NSAPI::NSMutableSet_addObject:
12134     case NSAPI::NSOrderedSet_setObjectAtIndex:
12135     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12136     case NSAPI::NSOrderedSet_insertObjectAtIndex:
12137       return 0;
12138     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12139       return 1;
12140   }
12141 
12142   return None;
12143 }
12144 
12145 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12146   if (!Message->isInstanceMessage()) {
12147     return;
12148   }
12149 
12150   Optional<int> ArgOpt;
12151 
12152   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12153       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12154       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12155     return;
12156   }
12157 
12158   int ArgIndex = *ArgOpt;
12159 
12160   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12161   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12162     Arg = OE->getSourceExpr()->IgnoreImpCasts();
12163   }
12164 
12165   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12166     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12167       if (ArgRE->isObjCSelfExpr()) {
12168         Diag(Message->getSourceRange().getBegin(),
12169              diag::warn_objc_circular_container)
12170           << ArgRE->getDecl() << StringRef("'super'");
12171       }
12172     }
12173   } else {
12174     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12175 
12176     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12177       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12178     }
12179 
12180     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12181       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12182         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12183           ValueDecl *Decl = ReceiverRE->getDecl();
12184           Diag(Message->getSourceRange().getBegin(),
12185                diag::warn_objc_circular_container)
12186             << Decl << Decl;
12187           if (!ArgRE->isObjCSelfExpr()) {
12188             Diag(Decl->getLocation(),
12189                  diag::note_objc_circular_container_declared_here)
12190               << Decl;
12191           }
12192         }
12193       }
12194     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12195       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12196         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12197           ObjCIvarDecl *Decl = IvarRE->getDecl();
12198           Diag(Message->getSourceRange().getBegin(),
12199                diag::warn_objc_circular_container)
12200             << Decl << Decl;
12201           Diag(Decl->getLocation(),
12202                diag::note_objc_circular_container_declared_here)
12203             << Decl;
12204         }
12205       }
12206     }
12207   }
12208 }
12209 
12210 /// Check a message send to see if it's likely to cause a retain cycle.
12211 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12212   // Only check instance methods whose selector looks like a setter.
12213   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12214     return;
12215 
12216   // Try to find a variable that the receiver is strongly owned by.
12217   RetainCycleOwner owner;
12218   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
12219     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
12220       return;
12221   } else {
12222     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12223     owner.Variable = getCurMethodDecl()->getSelfDecl();
12224     owner.Loc = msg->getSuperLoc();
12225     owner.Range = msg->getSuperLoc();
12226   }
12227 
12228   // Check whether the receiver is captured by any of the arguments.
12229   const ObjCMethodDecl *MD = msg->getMethodDecl();
12230   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12231     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12232       // noescape blocks should not be retained by the method.
12233       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12234         continue;
12235       return diagnoseRetainCycle(*this, capturer, owner);
12236     }
12237   }
12238 }
12239 
12240 /// Check a property assign to see if it's likely to cause a retain cycle.
12241 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12242   RetainCycleOwner owner;
12243   if (!findRetainCycleOwner(*this, receiver, owner))
12244     return;
12245 
12246   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12247     diagnoseRetainCycle(*this, capturer, owner);
12248 }
12249 
12250 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12251   RetainCycleOwner Owner;
12252   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
12253     return;
12254 
12255   // Because we don't have an expression for the variable, we have to set the
12256   // location explicitly here.
12257   Owner.Loc = Var->getLocation();
12258   Owner.Range = Var->getSourceRange();
12259 
12260   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12261     diagnoseRetainCycle(*this, Capturer, Owner);
12262 }
12263 
12264 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12265                                      Expr *RHS, bool isProperty) {
12266   // Check if RHS is an Objective-C object literal, which also can get
12267   // immediately zapped in a weak reference.  Note that we explicitly
12268   // allow ObjCStringLiterals, since those are designed to never really die.
12269   RHS = RHS->IgnoreParenImpCasts();
12270 
12271   // This enum needs to match with the 'select' in
12272   // warn_objc_arc_literal_assign (off-by-1).
12273   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12274   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12275     return false;
12276 
12277   S.Diag(Loc, diag::warn_arc_literal_assign)
12278     << (unsigned) Kind
12279     << (isProperty ? 0 : 1)
12280     << RHS->getSourceRange();
12281 
12282   return true;
12283 }
12284 
12285 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12286                                     Qualifiers::ObjCLifetime LT,
12287                                     Expr *RHS, bool isProperty) {
12288   // Strip off any implicit cast added to get to the one ARC-specific.
12289   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12290     if (cast->getCastKind() == CK_ARCConsumeObject) {
12291       S.Diag(Loc, diag::warn_arc_retained_assign)
12292         << (LT == Qualifiers::OCL_ExplicitNone)
12293         << (isProperty ? 0 : 1)
12294         << RHS->getSourceRange();
12295       return true;
12296     }
12297     RHS = cast->getSubExpr();
12298   }
12299 
12300   if (LT == Qualifiers::OCL_Weak &&
12301       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12302     return true;
12303 
12304   return false;
12305 }
12306 
12307 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12308                               QualType LHS, Expr *RHS) {
12309   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12310 
12311   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12312     return false;
12313 
12314   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12315     return true;
12316 
12317   return false;
12318 }
12319 
12320 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12321                               Expr *LHS, Expr *RHS) {
12322   QualType LHSType;
12323   // PropertyRef on LHS type need be directly obtained from
12324   // its declaration as it has a PseudoType.
12325   ObjCPropertyRefExpr *PRE
12326     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12327   if (PRE && !PRE->isImplicitProperty()) {
12328     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12329     if (PD)
12330       LHSType = PD->getType();
12331   }
12332 
12333   if (LHSType.isNull())
12334     LHSType = LHS->getType();
12335 
12336   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12337 
12338   if (LT == Qualifiers::OCL_Weak) {
12339     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
12340       getCurFunction()->markSafeWeakUse(LHS);
12341   }
12342 
12343   if (checkUnsafeAssigns(Loc, LHSType, RHS))
12344     return;
12345 
12346   // FIXME. Check for other life times.
12347   if (LT != Qualifiers::OCL_None)
12348     return;
12349 
12350   if (PRE) {
12351     if (PRE->isImplicitProperty())
12352       return;
12353     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12354     if (!PD)
12355       return;
12356 
12357     unsigned Attributes = PD->getPropertyAttributes();
12358     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
12359       // when 'assign' attribute was not explicitly specified
12360       // by user, ignore it and rely on property type itself
12361       // for lifetime info.
12362       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12363       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12364           LHSType->isObjCRetainableType())
12365         return;
12366 
12367       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12368         if (cast->getCastKind() == CK_ARCConsumeObject) {
12369           Diag(Loc, diag::warn_arc_retained_property_assign)
12370           << RHS->getSourceRange();
12371           return;
12372         }
12373         RHS = cast->getSubExpr();
12374       }
12375     }
12376     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
12377       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12378         return;
12379     }
12380   }
12381 }
12382 
12383 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12384 
12385 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12386                                         SourceLocation StmtLoc,
12387                                         const NullStmt *Body) {
12388   // Do not warn if the body is a macro that expands to nothing, e.g:
12389   //
12390   // #define CALL(x)
12391   // if (condition)
12392   //   CALL(0);
12393   if (Body->hasLeadingEmptyMacro())
12394     return false;
12395 
12396   // Get line numbers of statement and body.
12397   bool StmtLineInvalid;
12398   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
12399                                                       &StmtLineInvalid);
12400   if (StmtLineInvalid)
12401     return false;
12402 
12403   bool BodyLineInvalid;
12404   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12405                                                       &BodyLineInvalid);
12406   if (BodyLineInvalid)
12407     return false;
12408 
12409   // Warn if null statement and body are on the same line.
12410   if (StmtLine != BodyLine)
12411     return false;
12412 
12413   return true;
12414 }
12415 
12416 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12417                                  const Stmt *Body,
12418                                  unsigned DiagID) {
12419   // Since this is a syntactic check, don't emit diagnostic for template
12420   // instantiations, this just adds noise.
12421   if (CurrentInstantiationScope)
12422     return;
12423 
12424   // The body should be a null statement.
12425   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12426   if (!NBody)
12427     return;
12428 
12429   // Do the usual checks.
12430   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12431     return;
12432 
12433   Diag(NBody->getSemiLoc(), DiagID);
12434   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12435 }
12436 
12437 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12438                                  const Stmt *PossibleBody) {
12439   assert(!CurrentInstantiationScope); // Ensured by caller
12440 
12441   SourceLocation StmtLoc;
12442   const Stmt *Body;
12443   unsigned DiagID;
12444   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12445     StmtLoc = FS->getRParenLoc();
12446     Body = FS->getBody();
12447     DiagID = diag::warn_empty_for_body;
12448   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12449     StmtLoc = WS->getCond()->getSourceRange().getEnd();
12450     Body = WS->getBody();
12451     DiagID = diag::warn_empty_while_body;
12452   } else
12453     return; // Neither `for' nor `while'.
12454 
12455   // The body should be a null statement.
12456   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12457   if (!NBody)
12458     return;
12459 
12460   // Skip expensive checks if diagnostic is disabled.
12461   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
12462     return;
12463 
12464   // Do the usual checks.
12465   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12466     return;
12467 
12468   // `for(...);' and `while(...);' are popular idioms, so in order to keep
12469   // noise level low, emit diagnostics only if for/while is followed by a
12470   // CompoundStmt, e.g.:
12471   //    for (int i = 0; i < n; i++);
12472   //    {
12473   //      a(i);
12474   //    }
12475   // or if for/while is followed by a statement with more indentation
12476   // than for/while itself:
12477   //    for (int i = 0; i < n; i++);
12478   //      a(i);
12479   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12480   if (!ProbableTypo) {
12481     bool BodyColInvalid;
12482     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12483                              PossibleBody->getLocStart(),
12484                              &BodyColInvalid);
12485     if (BodyColInvalid)
12486       return;
12487 
12488     bool StmtColInvalid;
12489     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12490                              S->getLocStart(),
12491                              &StmtColInvalid);
12492     if (StmtColInvalid)
12493       return;
12494 
12495     if (BodyCol > StmtCol)
12496       ProbableTypo = true;
12497   }
12498 
12499   if (ProbableTypo) {
12500     Diag(NBody->getSemiLoc(), DiagID);
12501     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12502   }
12503 }
12504 
12505 //===--- CHECK: Warn on self move with std::move. -------------------------===//
12506 
12507 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12508 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12509                              SourceLocation OpLoc) {
12510   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12511     return;
12512 
12513   if (inTemplateInstantiation())
12514     return;
12515 
12516   // Strip parens and casts away.
12517   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12518   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12519 
12520   // Check for a call expression
12521   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12522   if (!CE || CE->getNumArgs() != 1)
12523     return;
12524 
12525   // Check for a call to std::move
12526   if (!CE->isCallToStdMove())
12527     return;
12528 
12529   // Get argument from std::move
12530   RHSExpr = CE->getArg(0);
12531 
12532   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12533   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12534 
12535   // Two DeclRefExpr's, check that the decls are the same.
12536   if (LHSDeclRef && RHSDeclRef) {
12537     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12538       return;
12539     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12540         RHSDeclRef->getDecl()->getCanonicalDecl())
12541       return;
12542 
12543     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12544                                         << LHSExpr->getSourceRange()
12545                                         << RHSExpr->getSourceRange();
12546     return;
12547   }
12548 
12549   // Member variables require a different approach to check for self moves.
12550   // MemberExpr's are the same if every nested MemberExpr refers to the same
12551   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12552   // the base Expr's are CXXThisExpr's.
12553   const Expr *LHSBase = LHSExpr;
12554   const Expr *RHSBase = RHSExpr;
12555   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12556   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12557   if (!LHSME || !RHSME)
12558     return;
12559 
12560   while (LHSME && RHSME) {
12561     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12562         RHSME->getMemberDecl()->getCanonicalDecl())
12563       return;
12564 
12565     LHSBase = LHSME->getBase();
12566     RHSBase = RHSME->getBase();
12567     LHSME = dyn_cast<MemberExpr>(LHSBase);
12568     RHSME = dyn_cast<MemberExpr>(RHSBase);
12569   }
12570 
12571   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12572   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12573   if (LHSDeclRef && RHSDeclRef) {
12574     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12575       return;
12576     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12577         RHSDeclRef->getDecl()->getCanonicalDecl())
12578       return;
12579 
12580     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12581                                         << LHSExpr->getSourceRange()
12582                                         << RHSExpr->getSourceRange();
12583     return;
12584   }
12585 
12586   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12587     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12588                                         << LHSExpr->getSourceRange()
12589                                         << RHSExpr->getSourceRange();
12590 }
12591 
12592 //===--- Layout compatibility ----------------------------------------------//
12593 
12594 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
12595 
12596 /// Check if two enumeration types are layout-compatible.
12597 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
12598   // C++11 [dcl.enum] p8:
12599   // Two enumeration types are layout-compatible if they have the same
12600   // underlying type.
12601   return ED1->isComplete() && ED2->isComplete() &&
12602          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12603 }
12604 
12605 /// Check if two fields are layout-compatible.
12606 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12607                                FieldDecl *Field2) {
12608   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12609     return false;
12610 
12611   if (Field1->isBitField() != Field2->isBitField())
12612     return false;
12613 
12614   if (Field1->isBitField()) {
12615     // Make sure that the bit-fields are the same length.
12616     unsigned Bits1 = Field1->getBitWidthValue(C);
12617     unsigned Bits2 = Field2->getBitWidthValue(C);
12618 
12619     if (Bits1 != Bits2)
12620       return false;
12621   }
12622 
12623   return true;
12624 }
12625 
12626 /// Check if two standard-layout structs are layout-compatible.
12627 /// (C++11 [class.mem] p17)
12628 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12629                                      RecordDecl *RD2) {
12630   // If both records are C++ classes, check that base classes match.
12631   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12632     // If one of records is a CXXRecordDecl we are in C++ mode,
12633     // thus the other one is a CXXRecordDecl, too.
12634     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12635     // Check number of base classes.
12636     if (D1CXX->getNumBases() != D2CXX->getNumBases())
12637       return false;
12638 
12639     // Check the base classes.
12640     for (CXXRecordDecl::base_class_const_iterator
12641                Base1 = D1CXX->bases_begin(),
12642            BaseEnd1 = D1CXX->bases_end(),
12643               Base2 = D2CXX->bases_begin();
12644          Base1 != BaseEnd1;
12645          ++Base1, ++Base2) {
12646       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12647         return false;
12648     }
12649   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12650     // If only RD2 is a C++ class, it should have zero base classes.
12651     if (D2CXX->getNumBases() > 0)
12652       return false;
12653   }
12654 
12655   // Check the fields.
12656   RecordDecl::field_iterator Field2 = RD2->field_begin(),
12657                              Field2End = RD2->field_end(),
12658                              Field1 = RD1->field_begin(),
12659                              Field1End = RD1->field_end();
12660   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12661     if (!isLayoutCompatible(C, *Field1, *Field2))
12662       return false;
12663   }
12664   if (Field1 != Field1End || Field2 != Field2End)
12665     return false;
12666 
12667   return true;
12668 }
12669 
12670 /// Check if two standard-layout unions are layout-compatible.
12671 /// (C++11 [class.mem] p18)
12672 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12673                                     RecordDecl *RD2) {
12674   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
12675   for (auto *Field2 : RD2->fields())
12676     UnmatchedFields.insert(Field2);
12677 
12678   for (auto *Field1 : RD1->fields()) {
12679     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12680         I = UnmatchedFields.begin(),
12681         E = UnmatchedFields.end();
12682 
12683     for ( ; I != E; ++I) {
12684       if (isLayoutCompatible(C, Field1, *I)) {
12685         bool Result = UnmatchedFields.erase(*I);
12686         (void) Result;
12687         assert(Result);
12688         break;
12689       }
12690     }
12691     if (I == E)
12692       return false;
12693   }
12694 
12695   return UnmatchedFields.empty();
12696 }
12697 
12698 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12699                                RecordDecl *RD2) {
12700   if (RD1->isUnion() != RD2->isUnion())
12701     return false;
12702 
12703   if (RD1->isUnion())
12704     return isLayoutCompatibleUnion(C, RD1, RD2);
12705   else
12706     return isLayoutCompatibleStruct(C, RD1, RD2);
12707 }
12708 
12709 /// Check if two types are layout-compatible in C++11 sense.
12710 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12711   if (T1.isNull() || T2.isNull())
12712     return false;
12713 
12714   // C++11 [basic.types] p11:
12715   // If two types T1 and T2 are the same type, then T1 and T2 are
12716   // layout-compatible types.
12717   if (C.hasSameType(T1, T2))
12718     return true;
12719 
12720   T1 = T1.getCanonicalType().getUnqualifiedType();
12721   T2 = T2.getCanonicalType().getUnqualifiedType();
12722 
12723   const Type::TypeClass TC1 = T1->getTypeClass();
12724   const Type::TypeClass TC2 = T2->getTypeClass();
12725 
12726   if (TC1 != TC2)
12727     return false;
12728 
12729   if (TC1 == Type::Enum) {
12730     return isLayoutCompatible(C,
12731                               cast<EnumType>(T1)->getDecl(),
12732                               cast<EnumType>(T2)->getDecl());
12733   } else if (TC1 == Type::Record) {
12734     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12735       return false;
12736 
12737     return isLayoutCompatible(C,
12738                               cast<RecordType>(T1)->getDecl(),
12739                               cast<RecordType>(T2)->getDecl());
12740   }
12741 
12742   return false;
12743 }
12744 
12745 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12746 
12747 /// Given a type tag expression find the type tag itself.
12748 ///
12749 /// \param TypeExpr Type tag expression, as it appears in user's code.
12750 ///
12751 /// \param VD Declaration of an identifier that appears in a type tag.
12752 ///
12753 /// \param MagicValue Type tag magic value.
12754 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12755                             const ValueDecl **VD, uint64_t *MagicValue) {
12756   while(true) {
12757     if (!TypeExpr)
12758       return false;
12759 
12760     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12761 
12762     switch (TypeExpr->getStmtClass()) {
12763     case Stmt::UnaryOperatorClass: {
12764       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12765       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12766         TypeExpr = UO->getSubExpr();
12767         continue;
12768       }
12769       return false;
12770     }
12771 
12772     case Stmt::DeclRefExprClass: {
12773       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12774       *VD = DRE->getDecl();
12775       return true;
12776     }
12777 
12778     case Stmt::IntegerLiteralClass: {
12779       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12780       llvm::APInt MagicValueAPInt = IL->getValue();
12781       if (MagicValueAPInt.getActiveBits() <= 64) {
12782         *MagicValue = MagicValueAPInt.getZExtValue();
12783         return true;
12784       } else
12785         return false;
12786     }
12787 
12788     case Stmt::BinaryConditionalOperatorClass:
12789     case Stmt::ConditionalOperatorClass: {
12790       const AbstractConditionalOperator *ACO =
12791           cast<AbstractConditionalOperator>(TypeExpr);
12792       bool Result;
12793       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12794         if (Result)
12795           TypeExpr = ACO->getTrueExpr();
12796         else
12797           TypeExpr = ACO->getFalseExpr();
12798         continue;
12799       }
12800       return false;
12801     }
12802 
12803     case Stmt::BinaryOperatorClass: {
12804       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12805       if (BO->getOpcode() == BO_Comma) {
12806         TypeExpr = BO->getRHS();
12807         continue;
12808       }
12809       return false;
12810     }
12811 
12812     default:
12813       return false;
12814     }
12815   }
12816 }
12817 
12818 /// Retrieve the C type corresponding to type tag TypeExpr.
12819 ///
12820 /// \param TypeExpr Expression that specifies a type tag.
12821 ///
12822 /// \param MagicValues Registered magic values.
12823 ///
12824 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12825 ///        kind.
12826 ///
12827 /// \param TypeInfo Information about the corresponding C type.
12828 ///
12829 /// \returns true if the corresponding C type was found.
12830 static bool GetMatchingCType(
12831         const IdentifierInfo *ArgumentKind,
12832         const Expr *TypeExpr, const ASTContext &Ctx,
12833         const llvm::DenseMap<Sema::TypeTagMagicValue,
12834                              Sema::TypeTagData> *MagicValues,
12835         bool &FoundWrongKind,
12836         Sema::TypeTagData &TypeInfo) {
12837   FoundWrongKind = false;
12838 
12839   // Variable declaration that has type_tag_for_datatype attribute.
12840   const ValueDecl *VD = nullptr;
12841 
12842   uint64_t MagicValue;
12843 
12844   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12845     return false;
12846 
12847   if (VD) {
12848     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12849       if (I->getArgumentKind() != ArgumentKind) {
12850         FoundWrongKind = true;
12851         return false;
12852       }
12853       TypeInfo.Type = I->getMatchingCType();
12854       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12855       TypeInfo.MustBeNull = I->getMustBeNull();
12856       return true;
12857     }
12858     return false;
12859   }
12860 
12861   if (!MagicValues)
12862     return false;
12863 
12864   llvm::DenseMap<Sema::TypeTagMagicValue,
12865                  Sema::TypeTagData>::const_iterator I =
12866       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12867   if (I == MagicValues->end())
12868     return false;
12869 
12870   TypeInfo = I->second;
12871   return true;
12872 }
12873 
12874 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12875                                       uint64_t MagicValue, QualType Type,
12876                                       bool LayoutCompatible,
12877                                       bool MustBeNull) {
12878   if (!TypeTagForDatatypeMagicValues)
12879     TypeTagForDatatypeMagicValues.reset(
12880         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12881 
12882   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12883   (*TypeTagForDatatypeMagicValues)[Magic] =
12884       TypeTagData(Type, LayoutCompatible, MustBeNull);
12885 }
12886 
12887 static bool IsSameCharType(QualType T1, QualType T2) {
12888   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12889   if (!BT1)
12890     return false;
12891 
12892   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12893   if (!BT2)
12894     return false;
12895 
12896   BuiltinType::Kind T1Kind = BT1->getKind();
12897   BuiltinType::Kind T2Kind = BT2->getKind();
12898 
12899   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
12900          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
12901          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12902          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12903 }
12904 
12905 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12906                                     const ArrayRef<const Expr *> ExprArgs,
12907                                     SourceLocation CallSiteLoc) {
12908   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12909   bool IsPointerAttr = Attr->getIsPointer();
12910 
12911   // Retrieve the argument representing the 'type_tag'.
12912   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12913   if (TypeTagIdxAST >= ExprArgs.size()) {
12914     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12915         << 0 << Attr->getTypeTagIdx().getSourceIndex();
12916     return;
12917   }
12918   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
12919   bool FoundWrongKind;
12920   TypeTagData TypeInfo;
12921   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12922                         TypeTagForDatatypeMagicValues.get(),
12923                         FoundWrongKind, TypeInfo)) {
12924     if (FoundWrongKind)
12925       Diag(TypeTagExpr->getExprLoc(),
12926            diag::warn_type_tag_for_datatype_wrong_kind)
12927         << TypeTagExpr->getSourceRange();
12928     return;
12929   }
12930 
12931   // Retrieve the argument representing the 'arg_idx'.
12932   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12933   if (ArgumentIdxAST >= ExprArgs.size()) {
12934     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12935         << 1 << Attr->getArgumentIdx().getSourceIndex();
12936     return;
12937   }
12938   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
12939   if (IsPointerAttr) {
12940     // Skip implicit cast of pointer to `void *' (as a function argument).
12941     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12942       if (ICE->getType()->isVoidPointerType() &&
12943           ICE->getCastKind() == CK_BitCast)
12944         ArgumentExpr = ICE->getSubExpr();
12945   }
12946   QualType ArgumentType = ArgumentExpr->getType();
12947 
12948   // Passing a `void*' pointer shouldn't trigger a warning.
12949   if (IsPointerAttr && ArgumentType->isVoidPointerType())
12950     return;
12951 
12952   if (TypeInfo.MustBeNull) {
12953     // Type tag with matching void type requires a null pointer.
12954     if (!ArgumentExpr->isNullPointerConstant(Context,
12955                                              Expr::NPC_ValueDependentIsNotNull)) {
12956       Diag(ArgumentExpr->getExprLoc(),
12957            diag::warn_type_safety_null_pointer_required)
12958           << ArgumentKind->getName()
12959           << ArgumentExpr->getSourceRange()
12960           << TypeTagExpr->getSourceRange();
12961     }
12962     return;
12963   }
12964 
12965   QualType RequiredType = TypeInfo.Type;
12966   if (IsPointerAttr)
12967     RequiredType = Context.getPointerType(RequiredType);
12968 
12969   bool mismatch = false;
12970   if (!TypeInfo.LayoutCompatible) {
12971     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12972 
12973     // C++11 [basic.fundamental] p1:
12974     // Plain char, signed char, and unsigned char are three distinct types.
12975     //
12976     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12977     // char' depending on the current char signedness mode.
12978     if (mismatch)
12979       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12980                                            RequiredType->getPointeeType())) ||
12981           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12982         mismatch = false;
12983   } else
12984     if (IsPointerAttr)
12985       mismatch = !isLayoutCompatible(Context,
12986                                      ArgumentType->getPointeeType(),
12987                                      RequiredType->getPointeeType());
12988     else
12989       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12990 
12991   if (mismatch)
12992     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12993         << ArgumentType << ArgumentKind
12994         << TypeInfo.LayoutCompatible << RequiredType
12995         << ArgumentExpr->getSourceRange()
12996         << TypeTagExpr->getSourceRange();
12997 }
12998 
12999 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13000                                          CharUnits Alignment) {
13001   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13002 }
13003 
13004 void Sema::DiagnoseMisalignedMembers() {
13005   for (MisalignedMember &m : MisalignedMembers) {
13006     const NamedDecl *ND = m.RD;
13007     if (ND->getName().empty()) {
13008       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13009         ND = TD;
13010     }
13011     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
13012         << m.MD << ND << m.E->getSourceRange();
13013   }
13014   MisalignedMembers.clear();
13015 }
13016 
13017 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
13018   E = E->IgnoreParens();
13019   if (!T->isPointerType() && !T->isIntegerType())
13020     return;
13021   if (isa<UnaryOperator>(E) &&
13022       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13023     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13024     if (isa<MemberExpr>(Op)) {
13025       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13026                           MisalignedMember(Op));
13027       if (MA != MisalignedMembers.end() &&
13028           (T->isIntegerType() ||
13029            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13030                                    Context.getTypeAlignInChars(
13031                                        T->getPointeeType()) <= MA->Alignment))))
13032         MisalignedMembers.erase(MA);
13033     }
13034   }
13035 }
13036 
13037 void Sema::RefersToMemberWithReducedAlignment(
13038     Expr *E,
13039     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13040         Action) {
13041   const auto *ME = dyn_cast<MemberExpr>(E);
13042   if (!ME)
13043     return;
13044 
13045   // No need to check expressions with an __unaligned-qualified type.
13046   if (E->getType().getQualifiers().hasUnaligned())
13047     return;
13048 
13049   // For a chain of MemberExpr like "a.b.c.d" this list
13050   // will keep FieldDecl's like [d, c, b].
13051   SmallVector<FieldDecl *, 4> ReverseMemberChain;
13052   const MemberExpr *TopME = nullptr;
13053   bool AnyIsPacked = false;
13054   do {
13055     QualType BaseType = ME->getBase()->getType();
13056     if (ME->isArrow())
13057       BaseType = BaseType->getPointeeType();
13058     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
13059     if (RD->isInvalidDecl())
13060       return;
13061 
13062     ValueDecl *MD = ME->getMemberDecl();
13063     auto *FD = dyn_cast<FieldDecl>(MD);
13064     // We do not care about non-data members.
13065     if (!FD || FD->isInvalidDecl())
13066       return;
13067 
13068     AnyIsPacked =
13069         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13070     ReverseMemberChain.push_back(FD);
13071 
13072     TopME = ME;
13073     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13074   } while (ME);
13075   assert(TopME && "We did not compute a topmost MemberExpr!");
13076 
13077   // Not the scope of this diagnostic.
13078   if (!AnyIsPacked)
13079     return;
13080 
13081   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13082   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13083   // TODO: The innermost base of the member expression may be too complicated.
13084   // For now, just disregard these cases. This is left for future
13085   // improvement.
13086   if (!DRE && !isa<CXXThisExpr>(TopBase))
13087       return;
13088 
13089   // Alignment expected by the whole expression.
13090   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13091 
13092   // No need to do anything else with this case.
13093   if (ExpectedAlignment.isOne())
13094     return;
13095 
13096   // Synthesize offset of the whole access.
13097   CharUnits Offset;
13098   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13099        I++) {
13100     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13101   }
13102 
13103   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13104   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13105       ReverseMemberChain.back()->getParent()->getTypeForDecl());
13106 
13107   // The base expression of the innermost MemberExpr may give
13108   // stronger guarantees than the class containing the member.
13109   if (DRE && !TopME->isArrow()) {
13110     const ValueDecl *VD = DRE->getDecl();
13111     if (!VD->getType()->isReferenceType())
13112       CompleteObjectAlignment =
13113           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13114   }
13115 
13116   // Check if the synthesized offset fulfills the alignment.
13117   if (Offset % ExpectedAlignment != 0 ||
13118       // It may fulfill the offset it but the effective alignment may still be
13119       // lower than the expected expression alignment.
13120       CompleteObjectAlignment < ExpectedAlignment) {
13121     // If this happens, we want to determine a sensible culprit of this.
13122     // Intuitively, watching the chain of member expressions from right to
13123     // left, we start with the required alignment (as required by the field
13124     // type) but some packed attribute in that chain has reduced the alignment.
13125     // It may happen that another packed structure increases it again. But if
13126     // we are here such increase has not been enough. So pointing the first
13127     // FieldDecl that either is packed or else its RecordDecl is,
13128     // seems reasonable.
13129     FieldDecl *FD = nullptr;
13130     CharUnits Alignment;
13131     for (FieldDecl *FDI : ReverseMemberChain) {
13132       if (FDI->hasAttr<PackedAttr>() ||
13133           FDI->getParent()->hasAttr<PackedAttr>()) {
13134         FD = FDI;
13135         Alignment = std::min(
13136             Context.getTypeAlignInChars(FD->getType()),
13137             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13138         break;
13139       }
13140     }
13141     assert(FD && "We did not find a packed FieldDecl!");
13142     Action(E, FD->getParent(), FD, Alignment);
13143   }
13144 }
13145 
13146 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13147   using namespace std::placeholders;
13148 
13149   RefersToMemberWithReducedAlignment(
13150       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13151                      _2, _3, _4));
13152 }
13153