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/ASTContext.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/ExprOpenMP.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/SyncScope.h"
29 #include "clang/Basic/TargetBuiltins.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32 #include "clang/Sema/Initialization.h"
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/Sema.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/SmallBitVector.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/Support/ConvertUTF.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/Locale.h"
43 #include "llvm/Support/raw_ostream.h"
44 
45 using namespace clang;
46 using namespace sema;
47 
48 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
49                                                     unsigned ByteNo) const {
50   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
51                                Context.getTargetInfo());
52 }
53 
54 /// Checks that a call expression's argument count is the desired number.
55 /// This is useful when doing custom type-checking.  Returns true on error.
56 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
57   unsigned argCount = call->getNumArgs();
58   if (argCount == desiredArgCount) return false;
59 
60   if (argCount < desiredArgCount)
61     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
62         << 0 /*function call*/ << desiredArgCount << argCount
63         << call->getSourceRange();
64 
65   // Highlight all the excess arguments.
66   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
67                     call->getArg(argCount - 1)->getLocEnd());
68 
69   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
70     << 0 /*function call*/ << desiredArgCount << argCount
71     << call->getArg(1)->getSourceRange();
72 }
73 
74 /// Check that the first argument to __builtin_annotation is an integer
75 /// and the second argument is a non-wide string literal.
76 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
77   if (checkArgCount(S, TheCall, 2))
78     return true;
79 
80   // First argument should be an integer.
81   Expr *ValArg = TheCall->getArg(0);
82   QualType Ty = ValArg->getType();
83   if (!Ty->isIntegerType()) {
84     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
85       << ValArg->getSourceRange();
86     return true;
87   }
88 
89   // Second argument should be a constant string.
90   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
91   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
92   if (!Literal || !Literal->isAscii()) {
93     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
94       << StrArg->getSourceRange();
95     return true;
96   }
97 
98   TheCall->setType(Ty);
99   return false;
100 }
101 
102 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
103   // We need at least one argument.
104   if (TheCall->getNumArgs() < 1) {
105     S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
106         << 0 << 1 << TheCall->getNumArgs()
107         << TheCall->getCallee()->getSourceRange();
108     return true;
109   }
110 
111   // All arguments should be wide string literals.
112   for (Expr *Arg : TheCall->arguments()) {
113     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
114     if (!Literal || !Literal->isWide()) {
115       S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
116           << Arg->getSourceRange();
117       return true;
118     }
119   }
120 
121   return false;
122 }
123 
124 /// Check that the argument to __builtin_addressof is a glvalue, and set the
125 /// result type to the corresponding pointer type.
126 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
127   if (checkArgCount(S, TheCall, 1))
128     return true;
129 
130   ExprResult Arg(TheCall->getArg(0));
131   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
132   if (ResultType.isNull())
133     return true;
134 
135   TheCall->setArg(0, Arg.get());
136   TheCall->setType(ResultType);
137   return false;
138 }
139 
140 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
141   if (checkArgCount(S, TheCall, 3))
142     return true;
143 
144   // First two arguments should be integers.
145   for (unsigned I = 0; I < 2; ++I) {
146     Expr *Arg = TheCall->getArg(I);
147     QualType Ty = Arg->getType();
148     if (!Ty->isIntegerType()) {
149       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
150           << Ty << Arg->getSourceRange();
151       return true;
152     }
153   }
154 
155   // Third argument should be a pointer to a non-const integer.
156   // IRGen correctly handles volatile, restrict, and address spaces, and
157   // the other qualifiers aren't possible.
158   {
159     Expr *Arg = TheCall->getArg(2);
160     QualType Ty = Arg->getType();
161     const auto *PtrTy = Ty->getAs<PointerType>();
162     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
163           !PtrTy->getPointeeType().isConstQualified())) {
164       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
165           << Ty << Arg->getSourceRange();
166       return true;
167     }
168   }
169 
170   return false;
171 }
172 
173 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
174 		                  CallExpr *TheCall, unsigned SizeIdx,
175                                   unsigned DstSizeIdx) {
176   if (TheCall->getNumArgs() <= SizeIdx ||
177       TheCall->getNumArgs() <= DstSizeIdx)
178     return;
179 
180   const Expr *SizeArg = TheCall->getArg(SizeIdx);
181   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
182 
183   llvm::APSInt Size, DstSize;
184 
185   // find out if both sizes are known at compile time
186   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
187       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
188     return;
189 
190   if (Size.ule(DstSize))
191     return;
192 
193   // confirmed overflow so generate the diagnostic.
194   IdentifierInfo *FnName = FDecl->getIdentifier();
195   SourceLocation SL = TheCall->getLocStart();
196   SourceRange SR = TheCall->getSourceRange();
197 
198   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
199 }
200 
201 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
202   if (checkArgCount(S, BuiltinCall, 2))
203     return true;
204 
205   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
206   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
207   Expr *Call = BuiltinCall->getArg(0);
208   Expr *Chain = BuiltinCall->getArg(1);
209 
210   if (Call->getStmtClass() != Stmt::CallExprClass) {
211     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
212         << Call->getSourceRange();
213     return true;
214   }
215 
216   auto CE = cast<CallExpr>(Call);
217   if (CE->getCallee()->getType()->isBlockPointerType()) {
218     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
219         << Call->getSourceRange();
220     return true;
221   }
222 
223   const Decl *TargetDecl = CE->getCalleeDecl();
224   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
225     if (FD->getBuiltinID()) {
226       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
227           << Call->getSourceRange();
228       return true;
229     }
230 
231   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
232     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
233         << Call->getSourceRange();
234     return true;
235   }
236 
237   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
238   if (ChainResult.isInvalid())
239     return true;
240   if (!ChainResult.get()->getType()->isPointerType()) {
241     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
242         << Chain->getSourceRange();
243     return true;
244   }
245 
246   QualType ReturnTy = CE->getCallReturnType(S.Context);
247   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
248   QualType BuiltinTy = S.Context.getFunctionType(
249       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
250   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
251 
252   Builtin =
253       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
254 
255   BuiltinCall->setType(CE->getType());
256   BuiltinCall->setValueKind(CE->getValueKind());
257   BuiltinCall->setObjectKind(CE->getObjectKind());
258   BuiltinCall->setCallee(Builtin);
259   BuiltinCall->setArg(1, ChainResult.get());
260 
261   return false;
262 }
263 
264 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
265                                      Scope::ScopeFlags NeededScopeFlags,
266                                      unsigned DiagID) {
267   // Scopes aren't available during instantiation. Fortunately, builtin
268   // functions cannot be template args so they cannot be formed through template
269   // instantiation. Therefore checking once during the parse is sufficient.
270   if (SemaRef.inTemplateInstantiation())
271     return false;
272 
273   Scope *S = SemaRef.getCurScope();
274   while (S && !S->isSEHExceptScope())
275     S = S->getParent();
276   if (!S || !(S->getFlags() & NeededScopeFlags)) {
277     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
278     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
279         << DRE->getDecl()->getIdentifier();
280     return true;
281   }
282 
283   return false;
284 }
285 
286 static inline bool isBlockPointer(Expr *Arg) {
287   return Arg->getType()->isBlockPointerType();
288 }
289 
290 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
291 /// void*, which is a requirement of device side enqueue.
292 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
293   const BlockPointerType *BPT =
294       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
295   ArrayRef<QualType> Params =
296       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
297   unsigned ArgCounter = 0;
298   bool IllegalParams = false;
299   // Iterate through the block parameters until either one is found that is not
300   // a local void*, or the block is valid.
301   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
302        I != E; ++I, ++ArgCounter) {
303     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
304         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
305             LangAS::opencl_local) {
306       // Get the location of the error. If a block literal has been passed
307       // (BlockExpr) then we can point straight to the offending argument,
308       // else we just point to the variable reference.
309       SourceLocation ErrorLoc;
310       if (isa<BlockExpr>(BlockArg)) {
311         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
312         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
313       } else if (isa<DeclRefExpr>(BlockArg)) {
314         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
315       }
316       S.Diag(ErrorLoc,
317              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
318       IllegalParams = true;
319     }
320   }
321 
322   return IllegalParams;
323 }
324 
325 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
326   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
327     S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
328           << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
329     return true;
330   }
331   return false;
332 }
333 
334 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
335   if (checkArgCount(S, TheCall, 2))
336     return true;
337 
338   if (checkOpenCLSubgroupExt(S, TheCall))
339     return true;
340 
341   // First argument is an ndrange_t type.
342   Expr *NDRangeArg = TheCall->getArg(0);
343   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
344     S.Diag(NDRangeArg->getLocStart(),
345            diag::err_opencl_builtin_expected_type)
346         << TheCall->getDirectCallee() << "'ndrange_t'";
347     return true;
348   }
349 
350   Expr *BlockArg = TheCall->getArg(1);
351   if (!isBlockPointer(BlockArg)) {
352     S.Diag(BlockArg->getLocStart(),
353            diag::err_opencl_builtin_expected_type)
354         << TheCall->getDirectCallee() << "block";
355     return true;
356   }
357   return checkOpenCLBlockArgs(S, BlockArg);
358 }
359 
360 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
361 /// get_kernel_work_group_size
362 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
363 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
364   if (checkArgCount(S, TheCall, 1))
365     return true;
366 
367   Expr *BlockArg = TheCall->getArg(0);
368   if (!isBlockPointer(BlockArg)) {
369     S.Diag(BlockArg->getLocStart(),
370            diag::err_opencl_builtin_expected_type)
371         << TheCall->getDirectCallee() << "block";
372     return true;
373   }
374   return checkOpenCLBlockArgs(S, BlockArg);
375 }
376 
377 /// Diagnose integer type and any valid implicit conversion to it.
378 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
379                                       const QualType &IntType);
380 
381 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
382                                             unsigned Start, unsigned End) {
383   bool IllegalParams = false;
384   for (unsigned I = Start; I <= End; ++I)
385     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
386                                               S.Context.getSizeType());
387   return IllegalParams;
388 }
389 
390 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
391 /// 'local void*' parameter of passed block.
392 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
393                                            Expr *BlockArg,
394                                            unsigned NumNonVarArgs) {
395   const BlockPointerType *BPT =
396       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
397   unsigned NumBlockParams =
398       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
399   unsigned TotalNumArgs = TheCall->getNumArgs();
400 
401   // For each argument passed to the block, a corresponding uint needs to
402   // be passed to describe the size of the local memory.
403   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
404     S.Diag(TheCall->getLocStart(),
405            diag::err_opencl_enqueue_kernel_local_size_args);
406     return true;
407   }
408 
409   // Check that the sizes of the local memory are specified by integers.
410   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
411                                          TotalNumArgs - 1);
412 }
413 
414 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
415 /// overload formats specified in Table 6.13.17.1.
416 /// int enqueue_kernel(queue_t queue,
417 ///                    kernel_enqueue_flags_t flags,
418 ///                    const ndrange_t ndrange,
419 ///                    void (^block)(void))
420 /// int enqueue_kernel(queue_t queue,
421 ///                    kernel_enqueue_flags_t flags,
422 ///                    const ndrange_t ndrange,
423 ///                    uint num_events_in_wait_list,
424 ///                    clk_event_t *event_wait_list,
425 ///                    clk_event_t *event_ret,
426 ///                    void (^block)(void))
427 /// int enqueue_kernel(queue_t queue,
428 ///                    kernel_enqueue_flags_t flags,
429 ///                    const ndrange_t ndrange,
430 ///                    void (^block)(local void*, ...),
431 ///                    uint size0, ...)
432 /// int enqueue_kernel(queue_t queue,
433 ///                    kernel_enqueue_flags_t flags,
434 ///                    const ndrange_t ndrange,
435 ///                    uint num_events_in_wait_list,
436 ///                    clk_event_t *event_wait_list,
437 ///                    clk_event_t *event_ret,
438 ///                    void (^block)(local void*, ...),
439 ///                    uint size0, ...)
440 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
441   unsigned NumArgs = TheCall->getNumArgs();
442 
443   if (NumArgs < 4) {
444     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
445     return true;
446   }
447 
448   Expr *Arg0 = TheCall->getArg(0);
449   Expr *Arg1 = TheCall->getArg(1);
450   Expr *Arg2 = TheCall->getArg(2);
451   Expr *Arg3 = TheCall->getArg(3);
452 
453   // First argument always needs to be a queue_t type.
454   if (!Arg0->getType()->isQueueT()) {
455     S.Diag(TheCall->getArg(0)->getLocStart(),
456            diag::err_opencl_builtin_expected_type)
457         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
458     return true;
459   }
460 
461   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
462   if (!Arg1->getType()->isIntegerType()) {
463     S.Diag(TheCall->getArg(1)->getLocStart(),
464            diag::err_opencl_builtin_expected_type)
465         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
466     return true;
467   }
468 
469   // Third argument is always an ndrange_t type.
470   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
471     S.Diag(TheCall->getArg(2)->getLocStart(),
472            diag::err_opencl_builtin_expected_type)
473         << TheCall->getDirectCallee() << "'ndrange_t'";
474     return true;
475   }
476 
477   // With four arguments, there is only one form that the function could be
478   // called in: no events and no variable arguments.
479   if (NumArgs == 4) {
480     // check that the last argument is the right block type.
481     if (!isBlockPointer(Arg3)) {
482       S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
483           << TheCall->getDirectCallee() << "block";
484       return true;
485     }
486     // we have a block type, check the prototype
487     const BlockPointerType *BPT =
488         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
489     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
490       S.Diag(Arg3->getLocStart(),
491              diag::err_opencl_enqueue_kernel_blocks_no_args);
492       return true;
493     }
494     return false;
495   }
496   // we can have block + varargs.
497   if (isBlockPointer(Arg3))
498     return (checkOpenCLBlockArgs(S, Arg3) ||
499             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
500   // last two cases with either exactly 7 args or 7 args and varargs.
501   if (NumArgs >= 7) {
502     // check common block argument.
503     Expr *Arg6 = TheCall->getArg(6);
504     if (!isBlockPointer(Arg6)) {
505       S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
506           << TheCall->getDirectCallee() << "block";
507       return true;
508     }
509     if (checkOpenCLBlockArgs(S, Arg6))
510       return true;
511 
512     // Forth argument has to be any integer type.
513     if (!Arg3->getType()->isIntegerType()) {
514       S.Diag(TheCall->getArg(3)->getLocStart(),
515              diag::err_opencl_builtin_expected_type)
516           << TheCall->getDirectCallee() << "integer";
517       return true;
518     }
519     // check remaining common arguments.
520     Expr *Arg4 = TheCall->getArg(4);
521     Expr *Arg5 = TheCall->getArg(5);
522 
523     // Fifth argument is always passed as a pointer to clk_event_t.
524     if (!Arg4->isNullPointerConstant(S.Context,
525                                      Expr::NPC_ValueDependentIsNotNull) &&
526         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
527       S.Diag(TheCall->getArg(4)->getLocStart(),
528              diag::err_opencl_builtin_expected_type)
529           << TheCall->getDirectCallee()
530           << S.Context.getPointerType(S.Context.OCLClkEventTy);
531       return true;
532     }
533 
534     // Sixth argument is always passed as a pointer to clk_event_t.
535     if (!Arg5->isNullPointerConstant(S.Context,
536                                      Expr::NPC_ValueDependentIsNotNull) &&
537         !(Arg5->getType()->isPointerType() &&
538           Arg5->getType()->getPointeeType()->isClkEventT())) {
539       S.Diag(TheCall->getArg(5)->getLocStart(),
540              diag::err_opencl_builtin_expected_type)
541           << TheCall->getDirectCallee()
542           << S.Context.getPointerType(S.Context.OCLClkEventTy);
543       return true;
544     }
545 
546     if (NumArgs == 7)
547       return false;
548 
549     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
550   }
551 
552   // None of the specific case has been detected, give generic error
553   S.Diag(TheCall->getLocStart(),
554          diag::err_opencl_enqueue_kernel_incorrect_args);
555   return true;
556 }
557 
558 /// Returns OpenCL access qual.
559 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
560     return D->getAttr<OpenCLAccessAttr>();
561 }
562 
563 /// Returns true if pipe element type is different from the pointer.
564 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
565   const Expr *Arg0 = Call->getArg(0);
566   // First argument type should always be pipe.
567   if (!Arg0->getType()->isPipeType()) {
568     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
569         << Call->getDirectCallee() << Arg0->getSourceRange();
570     return true;
571   }
572   OpenCLAccessAttr *AccessQual =
573       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
574   // Validates the access qualifier is compatible with the call.
575   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
576   // read_only and write_only, and assumed to be read_only if no qualifier is
577   // specified.
578   switch (Call->getDirectCallee()->getBuiltinID()) {
579   case Builtin::BIread_pipe:
580   case Builtin::BIreserve_read_pipe:
581   case Builtin::BIcommit_read_pipe:
582   case Builtin::BIwork_group_reserve_read_pipe:
583   case Builtin::BIsub_group_reserve_read_pipe:
584   case Builtin::BIwork_group_commit_read_pipe:
585   case Builtin::BIsub_group_commit_read_pipe:
586     if (!(!AccessQual || AccessQual->isReadOnly())) {
587       S.Diag(Arg0->getLocStart(),
588              diag::err_opencl_builtin_pipe_invalid_access_modifier)
589           << "read_only" << Arg0->getSourceRange();
590       return true;
591     }
592     break;
593   case Builtin::BIwrite_pipe:
594   case Builtin::BIreserve_write_pipe:
595   case Builtin::BIcommit_write_pipe:
596   case Builtin::BIwork_group_reserve_write_pipe:
597   case Builtin::BIsub_group_reserve_write_pipe:
598   case Builtin::BIwork_group_commit_write_pipe:
599   case Builtin::BIsub_group_commit_write_pipe:
600     if (!(AccessQual && AccessQual->isWriteOnly())) {
601       S.Diag(Arg0->getLocStart(),
602              diag::err_opencl_builtin_pipe_invalid_access_modifier)
603           << "write_only" << Arg0->getSourceRange();
604       return true;
605     }
606     break;
607   default:
608     break;
609   }
610   return false;
611 }
612 
613 /// Returns true if pipe element type is different from the pointer.
614 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
615   const Expr *Arg0 = Call->getArg(0);
616   const Expr *ArgIdx = Call->getArg(Idx);
617   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
618   const QualType EltTy = PipeTy->getElementType();
619   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
620   // The Idx argument should be a pointer and the type of the pointer and
621   // the type of pipe element should also be the same.
622   if (!ArgTy ||
623       !S.Context.hasSameType(
624           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
625     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
626         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
627         << ArgIdx->getType() << ArgIdx->getSourceRange();
628     return true;
629   }
630   return false;
631 }
632 
633 // \brief Performs semantic analysis for the read/write_pipe call.
634 // \param S Reference to the semantic analyzer.
635 // \param Call A pointer to the builtin call.
636 // \return True if a semantic error has been found, false otherwise.
637 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
638   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
639   // functions have two forms.
640   switch (Call->getNumArgs()) {
641   case 2: {
642     if (checkOpenCLPipeArg(S, Call))
643       return true;
644     // The call with 2 arguments should be
645     // read/write_pipe(pipe T, T*).
646     // Check packet type T.
647     if (checkOpenCLPipePacketType(S, Call, 1))
648       return true;
649   } break;
650 
651   case 4: {
652     if (checkOpenCLPipeArg(S, Call))
653       return true;
654     // The call with 4 arguments should be
655     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
656     // Check reserve_id_t.
657     if (!Call->getArg(1)->getType()->isReserveIDT()) {
658       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
659           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
660           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
661       return true;
662     }
663 
664     // Check the index.
665     const Expr *Arg2 = Call->getArg(2);
666     if (!Arg2->getType()->isIntegerType() &&
667         !Arg2->getType()->isUnsignedIntegerType()) {
668       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
669           << Call->getDirectCallee() << S.Context.UnsignedIntTy
670           << Arg2->getType() << Arg2->getSourceRange();
671       return true;
672     }
673 
674     // Check packet type T.
675     if (checkOpenCLPipePacketType(S, Call, 3))
676       return true;
677   } break;
678   default:
679     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
680         << Call->getDirectCallee() << Call->getSourceRange();
681     return true;
682   }
683 
684   return false;
685 }
686 
687 // \brief Performs a semantic analysis on the {work_group_/sub_group_
688 //        /_}reserve_{read/write}_pipe
689 // \param S Reference to the semantic analyzer.
690 // \param Call The call to the builtin function to be analyzed.
691 // \return True if a semantic error was found, false otherwise.
692 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
693   if (checkArgCount(S, Call, 2))
694     return true;
695 
696   if (checkOpenCLPipeArg(S, Call))
697     return true;
698 
699   // Check the reserve size.
700   if (!Call->getArg(1)->getType()->isIntegerType() &&
701       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
702     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
703         << Call->getDirectCallee() << S.Context.UnsignedIntTy
704         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
705     return true;
706   }
707 
708   // Since return type of reserve_read/write_pipe built-in function is
709   // reserve_id_t, which is not defined in the builtin def file , we used int
710   // as return type and need to override the return type of these functions.
711   Call->setType(S.Context.OCLReserveIDTy);
712 
713   return false;
714 }
715 
716 // \brief Performs a semantic analysis on {work_group_/sub_group_
717 //        /_}commit_{read/write}_pipe
718 // \param S Reference to the semantic analyzer.
719 // \param Call The call to the builtin function to be analyzed.
720 // \return True if a semantic error was found, false otherwise.
721 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
722   if (checkArgCount(S, Call, 2))
723     return true;
724 
725   if (checkOpenCLPipeArg(S, Call))
726     return true;
727 
728   // Check reserve_id_t.
729   if (!Call->getArg(1)->getType()->isReserveIDT()) {
730     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
731         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
732         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
733     return true;
734   }
735 
736   return false;
737 }
738 
739 // \brief Performs a semantic analysis on the call to built-in Pipe
740 //        Query Functions.
741 // \param S Reference to the semantic analyzer.
742 // \param Call The call to the builtin function to be analyzed.
743 // \return True if a semantic error was found, false otherwise.
744 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
745   if (checkArgCount(S, Call, 1))
746     return true;
747 
748   if (!Call->getArg(0)->getType()->isPipeType()) {
749     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
750         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
751     return true;
752   }
753 
754   return false;
755 }
756 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
757 // \brief Performs semantic analysis for the to_global/local/private call.
758 // \param S Reference to the semantic analyzer.
759 // \param BuiltinID ID of the builtin function.
760 // \param Call A pointer to the builtin call.
761 // \return True if a semantic error has been found, false otherwise.
762 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
763                                     CallExpr *Call) {
764   if (Call->getNumArgs() != 1) {
765     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
766         << Call->getDirectCallee() << Call->getSourceRange();
767     return true;
768   }
769 
770   auto RT = Call->getArg(0)->getType();
771   if (!RT->isPointerType() || RT->getPointeeType()
772       .getAddressSpace() == LangAS::opencl_constant) {
773     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
774         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
775     return true;
776   }
777 
778   RT = RT->getPointeeType();
779   auto Qual = RT.getQualifiers();
780   switch (BuiltinID) {
781   case Builtin::BIto_global:
782     Qual.setAddressSpace(LangAS::opencl_global);
783     break;
784   case Builtin::BIto_local:
785     Qual.setAddressSpace(LangAS::opencl_local);
786     break;
787   case Builtin::BIto_private:
788     Qual.setAddressSpace(LangAS::opencl_private);
789     break;
790   default:
791     llvm_unreachable("Invalid builtin function");
792   }
793   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
794       RT.getUnqualifiedType(), Qual)));
795 
796   return false;
797 }
798 
799 ExprResult
800 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
801                                CallExpr *TheCall) {
802   ExprResult TheCallResult(TheCall);
803 
804   // Find out if any arguments are required to be integer constant expressions.
805   unsigned ICEArguments = 0;
806   ASTContext::GetBuiltinTypeError Error;
807   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
808   if (Error != ASTContext::GE_None)
809     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
810 
811   // If any arguments are required to be ICE's, check and diagnose.
812   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
813     // Skip arguments not required to be ICE's.
814     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
815 
816     llvm::APSInt Result;
817     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
818       return true;
819     ICEArguments &= ~(1 << ArgNo);
820   }
821 
822   switch (BuiltinID) {
823   case Builtin::BI__builtin___CFStringMakeConstantString:
824     assert(TheCall->getNumArgs() == 1 &&
825            "Wrong # arguments to builtin CFStringMakeConstantString");
826     if (CheckObjCString(TheCall->getArg(0)))
827       return ExprError();
828     break;
829   case Builtin::BI__builtin_ms_va_start:
830   case Builtin::BI__builtin_stdarg_start:
831   case Builtin::BI__builtin_va_start:
832     if (SemaBuiltinVAStart(BuiltinID, TheCall))
833       return ExprError();
834     break;
835   case Builtin::BI__va_start: {
836     switch (Context.getTargetInfo().getTriple().getArch()) {
837     case llvm::Triple::arm:
838     case llvm::Triple::thumb:
839       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
840         return ExprError();
841       break;
842     default:
843       if (SemaBuiltinVAStart(BuiltinID, TheCall))
844         return ExprError();
845       break;
846     }
847     break;
848   }
849   case Builtin::BI__builtin_isgreater:
850   case Builtin::BI__builtin_isgreaterequal:
851   case Builtin::BI__builtin_isless:
852   case Builtin::BI__builtin_islessequal:
853   case Builtin::BI__builtin_islessgreater:
854   case Builtin::BI__builtin_isunordered:
855     if (SemaBuiltinUnorderedCompare(TheCall))
856       return ExprError();
857     break;
858   case Builtin::BI__builtin_fpclassify:
859     if (SemaBuiltinFPClassification(TheCall, 6))
860       return ExprError();
861     break;
862   case Builtin::BI__builtin_isfinite:
863   case Builtin::BI__builtin_isinf:
864   case Builtin::BI__builtin_isinf_sign:
865   case Builtin::BI__builtin_isnan:
866   case Builtin::BI__builtin_isnormal:
867     if (SemaBuiltinFPClassification(TheCall, 1))
868       return ExprError();
869     break;
870   case Builtin::BI__builtin_shufflevector:
871     return SemaBuiltinShuffleVector(TheCall);
872     // TheCall will be freed by the smart pointer here, but that's fine, since
873     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
874   case Builtin::BI__builtin_prefetch:
875     if (SemaBuiltinPrefetch(TheCall))
876       return ExprError();
877     break;
878   case Builtin::BI__builtin_alloca_with_align:
879     if (SemaBuiltinAllocaWithAlign(TheCall))
880       return ExprError();
881     break;
882   case Builtin::BI__assume:
883   case Builtin::BI__builtin_assume:
884     if (SemaBuiltinAssume(TheCall))
885       return ExprError();
886     break;
887   case Builtin::BI__builtin_assume_aligned:
888     if (SemaBuiltinAssumeAligned(TheCall))
889       return ExprError();
890     break;
891   case Builtin::BI__builtin_object_size:
892     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
893       return ExprError();
894     break;
895   case Builtin::BI__builtin_longjmp:
896     if (SemaBuiltinLongjmp(TheCall))
897       return ExprError();
898     break;
899   case Builtin::BI__builtin_setjmp:
900     if (SemaBuiltinSetjmp(TheCall))
901       return ExprError();
902     break;
903   case Builtin::BI_setjmp:
904   case Builtin::BI_setjmpex:
905     if (checkArgCount(*this, TheCall, 1))
906       return true;
907     break;
908 
909   case Builtin::BI__builtin_classify_type:
910     if (checkArgCount(*this, TheCall, 1)) return true;
911     TheCall->setType(Context.IntTy);
912     break;
913   case Builtin::BI__builtin_constant_p:
914     if (checkArgCount(*this, TheCall, 1)) return true;
915     TheCall->setType(Context.IntTy);
916     break;
917   case Builtin::BI__sync_fetch_and_add:
918   case Builtin::BI__sync_fetch_and_add_1:
919   case Builtin::BI__sync_fetch_and_add_2:
920   case Builtin::BI__sync_fetch_and_add_4:
921   case Builtin::BI__sync_fetch_and_add_8:
922   case Builtin::BI__sync_fetch_and_add_16:
923   case Builtin::BI__sync_fetch_and_sub:
924   case Builtin::BI__sync_fetch_and_sub_1:
925   case Builtin::BI__sync_fetch_and_sub_2:
926   case Builtin::BI__sync_fetch_and_sub_4:
927   case Builtin::BI__sync_fetch_and_sub_8:
928   case Builtin::BI__sync_fetch_and_sub_16:
929   case Builtin::BI__sync_fetch_and_or:
930   case Builtin::BI__sync_fetch_and_or_1:
931   case Builtin::BI__sync_fetch_and_or_2:
932   case Builtin::BI__sync_fetch_and_or_4:
933   case Builtin::BI__sync_fetch_and_or_8:
934   case Builtin::BI__sync_fetch_and_or_16:
935   case Builtin::BI__sync_fetch_and_and:
936   case Builtin::BI__sync_fetch_and_and_1:
937   case Builtin::BI__sync_fetch_and_and_2:
938   case Builtin::BI__sync_fetch_and_and_4:
939   case Builtin::BI__sync_fetch_and_and_8:
940   case Builtin::BI__sync_fetch_and_and_16:
941   case Builtin::BI__sync_fetch_and_xor:
942   case Builtin::BI__sync_fetch_and_xor_1:
943   case Builtin::BI__sync_fetch_and_xor_2:
944   case Builtin::BI__sync_fetch_and_xor_4:
945   case Builtin::BI__sync_fetch_and_xor_8:
946   case Builtin::BI__sync_fetch_and_xor_16:
947   case Builtin::BI__sync_fetch_and_nand:
948   case Builtin::BI__sync_fetch_and_nand_1:
949   case Builtin::BI__sync_fetch_and_nand_2:
950   case Builtin::BI__sync_fetch_and_nand_4:
951   case Builtin::BI__sync_fetch_and_nand_8:
952   case Builtin::BI__sync_fetch_and_nand_16:
953   case Builtin::BI__sync_add_and_fetch:
954   case Builtin::BI__sync_add_and_fetch_1:
955   case Builtin::BI__sync_add_and_fetch_2:
956   case Builtin::BI__sync_add_and_fetch_4:
957   case Builtin::BI__sync_add_and_fetch_8:
958   case Builtin::BI__sync_add_and_fetch_16:
959   case Builtin::BI__sync_sub_and_fetch:
960   case Builtin::BI__sync_sub_and_fetch_1:
961   case Builtin::BI__sync_sub_and_fetch_2:
962   case Builtin::BI__sync_sub_and_fetch_4:
963   case Builtin::BI__sync_sub_and_fetch_8:
964   case Builtin::BI__sync_sub_and_fetch_16:
965   case Builtin::BI__sync_and_and_fetch:
966   case Builtin::BI__sync_and_and_fetch_1:
967   case Builtin::BI__sync_and_and_fetch_2:
968   case Builtin::BI__sync_and_and_fetch_4:
969   case Builtin::BI__sync_and_and_fetch_8:
970   case Builtin::BI__sync_and_and_fetch_16:
971   case Builtin::BI__sync_or_and_fetch:
972   case Builtin::BI__sync_or_and_fetch_1:
973   case Builtin::BI__sync_or_and_fetch_2:
974   case Builtin::BI__sync_or_and_fetch_4:
975   case Builtin::BI__sync_or_and_fetch_8:
976   case Builtin::BI__sync_or_and_fetch_16:
977   case Builtin::BI__sync_xor_and_fetch:
978   case Builtin::BI__sync_xor_and_fetch_1:
979   case Builtin::BI__sync_xor_and_fetch_2:
980   case Builtin::BI__sync_xor_and_fetch_4:
981   case Builtin::BI__sync_xor_and_fetch_8:
982   case Builtin::BI__sync_xor_and_fetch_16:
983   case Builtin::BI__sync_nand_and_fetch:
984   case Builtin::BI__sync_nand_and_fetch_1:
985   case Builtin::BI__sync_nand_and_fetch_2:
986   case Builtin::BI__sync_nand_and_fetch_4:
987   case Builtin::BI__sync_nand_and_fetch_8:
988   case Builtin::BI__sync_nand_and_fetch_16:
989   case Builtin::BI__sync_val_compare_and_swap:
990   case Builtin::BI__sync_val_compare_and_swap_1:
991   case Builtin::BI__sync_val_compare_and_swap_2:
992   case Builtin::BI__sync_val_compare_and_swap_4:
993   case Builtin::BI__sync_val_compare_and_swap_8:
994   case Builtin::BI__sync_val_compare_and_swap_16:
995   case Builtin::BI__sync_bool_compare_and_swap:
996   case Builtin::BI__sync_bool_compare_and_swap_1:
997   case Builtin::BI__sync_bool_compare_and_swap_2:
998   case Builtin::BI__sync_bool_compare_and_swap_4:
999   case Builtin::BI__sync_bool_compare_and_swap_8:
1000   case Builtin::BI__sync_bool_compare_and_swap_16:
1001   case Builtin::BI__sync_lock_test_and_set:
1002   case Builtin::BI__sync_lock_test_and_set_1:
1003   case Builtin::BI__sync_lock_test_and_set_2:
1004   case Builtin::BI__sync_lock_test_and_set_4:
1005   case Builtin::BI__sync_lock_test_and_set_8:
1006   case Builtin::BI__sync_lock_test_and_set_16:
1007   case Builtin::BI__sync_lock_release:
1008   case Builtin::BI__sync_lock_release_1:
1009   case Builtin::BI__sync_lock_release_2:
1010   case Builtin::BI__sync_lock_release_4:
1011   case Builtin::BI__sync_lock_release_8:
1012   case Builtin::BI__sync_lock_release_16:
1013   case Builtin::BI__sync_swap:
1014   case Builtin::BI__sync_swap_1:
1015   case Builtin::BI__sync_swap_2:
1016   case Builtin::BI__sync_swap_4:
1017   case Builtin::BI__sync_swap_8:
1018   case Builtin::BI__sync_swap_16:
1019     return SemaBuiltinAtomicOverloaded(TheCallResult);
1020   case Builtin::BI__builtin_nontemporal_load:
1021   case Builtin::BI__builtin_nontemporal_store:
1022     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1023 #define BUILTIN(ID, TYPE, ATTRS)
1024 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1025   case Builtin::BI##ID: \
1026     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1027 #include "clang/Basic/Builtins.def"
1028   case Builtin::BI__annotation:
1029     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1030       return ExprError();
1031     break;
1032   case Builtin::BI__builtin_annotation:
1033     if (SemaBuiltinAnnotation(*this, TheCall))
1034       return ExprError();
1035     break;
1036   case Builtin::BI__builtin_addressof:
1037     if (SemaBuiltinAddressof(*this, TheCall))
1038       return ExprError();
1039     break;
1040   case Builtin::BI__builtin_add_overflow:
1041   case Builtin::BI__builtin_sub_overflow:
1042   case Builtin::BI__builtin_mul_overflow:
1043     if (SemaBuiltinOverflow(*this, TheCall))
1044       return ExprError();
1045     break;
1046   case Builtin::BI__builtin_operator_new:
1047   case Builtin::BI__builtin_operator_delete:
1048     if (!getLangOpts().CPlusPlus) {
1049       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1050         << (BuiltinID == Builtin::BI__builtin_operator_new
1051                 ? "__builtin_operator_new"
1052                 : "__builtin_operator_delete")
1053         << "C++";
1054       return ExprError();
1055     }
1056     // CodeGen assumes it can find the global new and delete to call,
1057     // so ensure that they are declared.
1058     DeclareGlobalNewDelete();
1059     break;
1060 
1061   // check secure string manipulation functions where overflows
1062   // are detectable at compile time
1063   case Builtin::BI__builtin___memcpy_chk:
1064   case Builtin::BI__builtin___memmove_chk:
1065   case Builtin::BI__builtin___memset_chk:
1066   case Builtin::BI__builtin___strlcat_chk:
1067   case Builtin::BI__builtin___strlcpy_chk:
1068   case Builtin::BI__builtin___strncat_chk:
1069   case Builtin::BI__builtin___strncpy_chk:
1070   case Builtin::BI__builtin___stpncpy_chk:
1071     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1072     break;
1073   case Builtin::BI__builtin___memccpy_chk:
1074     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1075     break;
1076   case Builtin::BI__builtin___snprintf_chk:
1077   case Builtin::BI__builtin___vsnprintf_chk:
1078     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1079     break;
1080   case Builtin::BI__builtin_call_with_static_chain:
1081     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1082       return ExprError();
1083     break;
1084   case Builtin::BI__exception_code:
1085   case Builtin::BI_exception_code:
1086     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1087                                  diag::err_seh___except_block))
1088       return ExprError();
1089     break;
1090   case Builtin::BI__exception_info:
1091   case Builtin::BI_exception_info:
1092     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1093                                  diag::err_seh___except_filter))
1094       return ExprError();
1095     break;
1096   case Builtin::BI__GetExceptionInfo:
1097     if (checkArgCount(*this, TheCall, 1))
1098       return ExprError();
1099 
1100     if (CheckCXXThrowOperand(
1101             TheCall->getLocStart(),
1102             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1103             TheCall))
1104       return ExprError();
1105 
1106     TheCall->setType(Context.VoidPtrTy);
1107     break;
1108   // OpenCL v2.0, s6.13.16 - Pipe functions
1109   case Builtin::BIread_pipe:
1110   case Builtin::BIwrite_pipe:
1111     // Since those two functions are declared with var args, we need a semantic
1112     // check for the argument.
1113     if (SemaBuiltinRWPipe(*this, TheCall))
1114       return ExprError();
1115     TheCall->setType(Context.IntTy);
1116     break;
1117   case Builtin::BIreserve_read_pipe:
1118   case Builtin::BIreserve_write_pipe:
1119   case Builtin::BIwork_group_reserve_read_pipe:
1120   case Builtin::BIwork_group_reserve_write_pipe:
1121     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1122       return ExprError();
1123     break;
1124   case Builtin::BIsub_group_reserve_read_pipe:
1125   case Builtin::BIsub_group_reserve_write_pipe:
1126     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1127         SemaBuiltinReserveRWPipe(*this, TheCall))
1128       return ExprError();
1129     break;
1130   case Builtin::BIcommit_read_pipe:
1131   case Builtin::BIcommit_write_pipe:
1132   case Builtin::BIwork_group_commit_read_pipe:
1133   case Builtin::BIwork_group_commit_write_pipe:
1134     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1135       return ExprError();
1136     break;
1137   case Builtin::BIsub_group_commit_read_pipe:
1138   case Builtin::BIsub_group_commit_write_pipe:
1139     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1140         SemaBuiltinCommitRWPipe(*this, TheCall))
1141       return ExprError();
1142     break;
1143   case Builtin::BIget_pipe_num_packets:
1144   case Builtin::BIget_pipe_max_packets:
1145     if (SemaBuiltinPipePackets(*this, TheCall))
1146       return ExprError();
1147     TheCall->setType(Context.UnsignedIntTy);
1148     break;
1149   case Builtin::BIto_global:
1150   case Builtin::BIto_local:
1151   case Builtin::BIto_private:
1152     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1153       return ExprError();
1154     break;
1155   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1156   case Builtin::BIenqueue_kernel:
1157     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1158       return ExprError();
1159     break;
1160   case Builtin::BIget_kernel_work_group_size:
1161   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1162     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1163       return ExprError();
1164     break;
1165     break;
1166   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1167   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1168     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1169       return ExprError();
1170     break;
1171   case Builtin::BI__builtin_os_log_format:
1172   case Builtin::BI__builtin_os_log_format_buffer_size:
1173     if (SemaBuiltinOSLogFormat(TheCall)) {
1174       return ExprError();
1175     }
1176     break;
1177   }
1178 
1179   // Since the target specific builtins for each arch overlap, only check those
1180   // of the arch we are compiling for.
1181   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1182     switch (Context.getTargetInfo().getTriple().getArch()) {
1183       case llvm::Triple::arm:
1184       case llvm::Triple::armeb:
1185       case llvm::Triple::thumb:
1186       case llvm::Triple::thumbeb:
1187         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1188           return ExprError();
1189         break;
1190       case llvm::Triple::aarch64:
1191       case llvm::Triple::aarch64_be:
1192         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1193           return ExprError();
1194         break;
1195       case llvm::Triple::mips:
1196       case llvm::Triple::mipsel:
1197       case llvm::Triple::mips64:
1198       case llvm::Triple::mips64el:
1199         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1200           return ExprError();
1201         break;
1202       case llvm::Triple::systemz:
1203         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1204           return ExprError();
1205         break;
1206       case llvm::Triple::x86:
1207       case llvm::Triple::x86_64:
1208         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1209           return ExprError();
1210         break;
1211       case llvm::Triple::ppc:
1212       case llvm::Triple::ppc64:
1213       case llvm::Triple::ppc64le:
1214         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1215           return ExprError();
1216         break;
1217       default:
1218         break;
1219     }
1220   }
1221 
1222   return TheCallResult;
1223 }
1224 
1225 // Get the valid immediate range for the specified NEON type code.
1226 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1227   NeonTypeFlags Type(t);
1228   int IsQuad = ForceQuad ? true : Type.isQuad();
1229   switch (Type.getEltType()) {
1230   case NeonTypeFlags::Int8:
1231   case NeonTypeFlags::Poly8:
1232     return shift ? 7 : (8 << IsQuad) - 1;
1233   case NeonTypeFlags::Int16:
1234   case NeonTypeFlags::Poly16:
1235     return shift ? 15 : (4 << IsQuad) - 1;
1236   case NeonTypeFlags::Int32:
1237     return shift ? 31 : (2 << IsQuad) - 1;
1238   case NeonTypeFlags::Int64:
1239   case NeonTypeFlags::Poly64:
1240     return shift ? 63 : (1 << IsQuad) - 1;
1241   case NeonTypeFlags::Poly128:
1242     return shift ? 127 : (1 << IsQuad) - 1;
1243   case NeonTypeFlags::Float16:
1244     assert(!shift && "cannot shift float types!");
1245     return (4 << IsQuad) - 1;
1246   case NeonTypeFlags::Float32:
1247     assert(!shift && "cannot shift float types!");
1248     return (2 << IsQuad) - 1;
1249   case NeonTypeFlags::Float64:
1250     assert(!shift && "cannot shift float types!");
1251     return (1 << IsQuad) - 1;
1252   }
1253   llvm_unreachable("Invalid NeonTypeFlag!");
1254 }
1255 
1256 /// getNeonEltType - Return the QualType corresponding to the elements of
1257 /// the vector type specified by the NeonTypeFlags.  This is used to check
1258 /// the pointer arguments for Neon load/store intrinsics.
1259 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1260                                bool IsPolyUnsigned, bool IsInt64Long) {
1261   switch (Flags.getEltType()) {
1262   case NeonTypeFlags::Int8:
1263     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1264   case NeonTypeFlags::Int16:
1265     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1266   case NeonTypeFlags::Int32:
1267     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1268   case NeonTypeFlags::Int64:
1269     if (IsInt64Long)
1270       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1271     else
1272       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1273                                 : Context.LongLongTy;
1274   case NeonTypeFlags::Poly8:
1275     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1276   case NeonTypeFlags::Poly16:
1277     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1278   case NeonTypeFlags::Poly64:
1279     if (IsInt64Long)
1280       return Context.UnsignedLongTy;
1281     else
1282       return Context.UnsignedLongLongTy;
1283   case NeonTypeFlags::Poly128:
1284     break;
1285   case NeonTypeFlags::Float16:
1286     return Context.HalfTy;
1287   case NeonTypeFlags::Float32:
1288     return Context.FloatTy;
1289   case NeonTypeFlags::Float64:
1290     return Context.DoubleTy;
1291   }
1292   llvm_unreachable("Invalid NeonTypeFlag!");
1293 }
1294 
1295 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1296   llvm::APSInt Result;
1297   uint64_t mask = 0;
1298   unsigned TV = 0;
1299   int PtrArgNum = -1;
1300   bool HasConstPtr = false;
1301   switch (BuiltinID) {
1302 #define GET_NEON_OVERLOAD_CHECK
1303 #include "clang/Basic/arm_neon.inc"
1304 #undef GET_NEON_OVERLOAD_CHECK
1305   }
1306 
1307   // For NEON intrinsics which are overloaded on vector element type, validate
1308   // the immediate which specifies which variant to emit.
1309   unsigned ImmArg = TheCall->getNumArgs()-1;
1310   if (mask) {
1311     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1312       return true;
1313 
1314     TV = Result.getLimitedValue(64);
1315     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1316       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1317         << TheCall->getArg(ImmArg)->getSourceRange();
1318   }
1319 
1320   if (PtrArgNum >= 0) {
1321     // Check that pointer arguments have the specified type.
1322     Expr *Arg = TheCall->getArg(PtrArgNum);
1323     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1324       Arg = ICE->getSubExpr();
1325     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1326     QualType RHSTy = RHS.get()->getType();
1327 
1328     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1329     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1330                           Arch == llvm::Triple::aarch64_be;
1331     bool IsInt64Long =
1332         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1333     QualType EltTy =
1334         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1335     if (HasConstPtr)
1336       EltTy = EltTy.withConst();
1337     QualType LHSTy = Context.getPointerType(EltTy);
1338     AssignConvertType ConvTy;
1339     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1340     if (RHS.isInvalid())
1341       return true;
1342     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1343                                  RHS.get(), AA_Assigning))
1344       return true;
1345   }
1346 
1347   // For NEON intrinsics which take an immediate value as part of the
1348   // instruction, range check them here.
1349   unsigned i = 0, l = 0, u = 0;
1350   switch (BuiltinID) {
1351   default:
1352     return false;
1353 #define GET_NEON_IMMEDIATE_CHECK
1354 #include "clang/Basic/arm_neon.inc"
1355 #undef GET_NEON_IMMEDIATE_CHECK
1356   }
1357 
1358   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1359 }
1360 
1361 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1362                                         unsigned MaxWidth) {
1363   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1364           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1365           BuiltinID == ARM::BI__builtin_arm_strex ||
1366           BuiltinID == ARM::BI__builtin_arm_stlex ||
1367           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1368           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1369           BuiltinID == AArch64::BI__builtin_arm_strex ||
1370           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1371          "unexpected ARM builtin");
1372   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1373                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1374                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1375                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1376 
1377   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1378 
1379   // Ensure that we have the proper number of arguments.
1380   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1381     return true;
1382 
1383   // Inspect the pointer argument of the atomic builtin.  This should always be
1384   // a pointer type, whose element is an integral scalar or pointer type.
1385   // Because it is a pointer type, we don't have to worry about any implicit
1386   // casts here.
1387   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1388   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1389   if (PointerArgRes.isInvalid())
1390     return true;
1391   PointerArg = PointerArgRes.get();
1392 
1393   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1394   if (!pointerType) {
1395     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1396       << PointerArg->getType() << PointerArg->getSourceRange();
1397     return true;
1398   }
1399 
1400   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1401   // task is to insert the appropriate casts into the AST. First work out just
1402   // what the appropriate type is.
1403   QualType ValType = pointerType->getPointeeType();
1404   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1405   if (IsLdrex)
1406     AddrType.addConst();
1407 
1408   // Issue a warning if the cast is dodgy.
1409   CastKind CastNeeded = CK_NoOp;
1410   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1411     CastNeeded = CK_BitCast;
1412     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1413       << PointerArg->getType()
1414       << Context.getPointerType(AddrType)
1415       << AA_Passing << PointerArg->getSourceRange();
1416   }
1417 
1418   // Finally, do the cast and replace the argument with the corrected version.
1419   AddrType = Context.getPointerType(AddrType);
1420   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1421   if (PointerArgRes.isInvalid())
1422     return true;
1423   PointerArg = PointerArgRes.get();
1424 
1425   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1426 
1427   // In general, we allow ints, floats and pointers to be loaded and stored.
1428   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1429       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1430     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1431       << PointerArg->getType() << PointerArg->getSourceRange();
1432     return true;
1433   }
1434 
1435   // But ARM doesn't have instructions to deal with 128-bit versions.
1436   if (Context.getTypeSize(ValType) > MaxWidth) {
1437     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1438     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1439       << PointerArg->getType() << PointerArg->getSourceRange();
1440     return true;
1441   }
1442 
1443   switch (ValType.getObjCLifetime()) {
1444   case Qualifiers::OCL_None:
1445   case Qualifiers::OCL_ExplicitNone:
1446     // okay
1447     break;
1448 
1449   case Qualifiers::OCL_Weak:
1450   case Qualifiers::OCL_Strong:
1451   case Qualifiers::OCL_Autoreleasing:
1452     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1453       << ValType << PointerArg->getSourceRange();
1454     return true;
1455   }
1456 
1457   if (IsLdrex) {
1458     TheCall->setType(ValType);
1459     return false;
1460   }
1461 
1462   // Initialize the argument to be stored.
1463   ExprResult ValArg = TheCall->getArg(0);
1464   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1465       Context, ValType, /*consume*/ false);
1466   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1467   if (ValArg.isInvalid())
1468     return true;
1469   TheCall->setArg(0, ValArg.get());
1470 
1471   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1472   // but the custom checker bypasses all default analysis.
1473   TheCall->setType(Context.IntTy);
1474   return false;
1475 }
1476 
1477 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1478   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1479       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1480       BuiltinID == ARM::BI__builtin_arm_strex ||
1481       BuiltinID == ARM::BI__builtin_arm_stlex) {
1482     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1483   }
1484 
1485   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1486     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1487       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1488   }
1489 
1490   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1491       BuiltinID == ARM::BI__builtin_arm_wsr64)
1492     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1493 
1494   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1495       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1496       BuiltinID == ARM::BI__builtin_arm_wsr ||
1497       BuiltinID == ARM::BI__builtin_arm_wsrp)
1498     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1499 
1500   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1501     return true;
1502 
1503   // For intrinsics which take an immediate value as part of the instruction,
1504   // range check them here.
1505   unsigned i = 0, l = 0, u = 0;
1506   switch (BuiltinID) {
1507   default: return false;
1508   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1509   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1510   case ARM::BI__builtin_arm_vcvtr_f:
1511   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1512   case ARM::BI__builtin_arm_dmb:
1513   case ARM::BI__builtin_arm_dsb:
1514   case ARM::BI__builtin_arm_isb:
1515   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1516   }
1517 
1518   // FIXME: VFP Intrinsics should error if VFP not present.
1519   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1520 }
1521 
1522 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1523                                          CallExpr *TheCall) {
1524   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1525       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1526       BuiltinID == AArch64::BI__builtin_arm_strex ||
1527       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1528     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1529   }
1530 
1531   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1532     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1533       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1534       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1535       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1536   }
1537 
1538   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1539       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1540     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1541 
1542   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1543       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1544       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1545       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1546     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1547 
1548   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1549     return true;
1550 
1551   // For intrinsics which take an immediate value as part of the instruction,
1552   // range check them here.
1553   unsigned i = 0, l = 0, u = 0;
1554   switch (BuiltinID) {
1555   default: return false;
1556   case AArch64::BI__builtin_arm_dmb:
1557   case AArch64::BI__builtin_arm_dsb:
1558   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1559   }
1560 
1561   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1562 }
1563 
1564 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1565 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1566 // ordering for DSP is unspecified. MSA is ordered by the data format used
1567 // by the underlying instruction i.e., df/m, df/n and then by size.
1568 //
1569 // FIXME: The size tests here should instead be tablegen'd along with the
1570 //        definitions from include/clang/Basic/BuiltinsMips.def.
1571 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1572 //        be too.
1573 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1574   unsigned i = 0, l = 0, u = 0, m = 0;
1575   switch (BuiltinID) {
1576   default: return false;
1577   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1578   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1579   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1580   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1581   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1582   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1583   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1584   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1585   // df/m field.
1586   // These intrinsics take an unsigned 3 bit immediate.
1587   case Mips::BI__builtin_msa_bclri_b:
1588   case Mips::BI__builtin_msa_bnegi_b:
1589   case Mips::BI__builtin_msa_bseti_b:
1590   case Mips::BI__builtin_msa_sat_s_b:
1591   case Mips::BI__builtin_msa_sat_u_b:
1592   case Mips::BI__builtin_msa_slli_b:
1593   case Mips::BI__builtin_msa_srai_b:
1594   case Mips::BI__builtin_msa_srari_b:
1595   case Mips::BI__builtin_msa_srli_b:
1596   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1597   case Mips::BI__builtin_msa_binsli_b:
1598   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1599   // These intrinsics take an unsigned 4 bit immediate.
1600   case Mips::BI__builtin_msa_bclri_h:
1601   case Mips::BI__builtin_msa_bnegi_h:
1602   case Mips::BI__builtin_msa_bseti_h:
1603   case Mips::BI__builtin_msa_sat_s_h:
1604   case Mips::BI__builtin_msa_sat_u_h:
1605   case Mips::BI__builtin_msa_slli_h:
1606   case Mips::BI__builtin_msa_srai_h:
1607   case Mips::BI__builtin_msa_srari_h:
1608   case Mips::BI__builtin_msa_srli_h:
1609   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1610   case Mips::BI__builtin_msa_binsli_h:
1611   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1612   // These intrinsics take an unsigned 5 bit immedate.
1613   // The first block of intrinsics actually have an unsigned 5 bit field,
1614   // not a df/n field.
1615   case Mips::BI__builtin_msa_clei_u_b:
1616   case Mips::BI__builtin_msa_clei_u_h:
1617   case Mips::BI__builtin_msa_clei_u_w:
1618   case Mips::BI__builtin_msa_clei_u_d:
1619   case Mips::BI__builtin_msa_clti_u_b:
1620   case Mips::BI__builtin_msa_clti_u_h:
1621   case Mips::BI__builtin_msa_clti_u_w:
1622   case Mips::BI__builtin_msa_clti_u_d:
1623   case Mips::BI__builtin_msa_maxi_u_b:
1624   case Mips::BI__builtin_msa_maxi_u_h:
1625   case Mips::BI__builtin_msa_maxi_u_w:
1626   case Mips::BI__builtin_msa_maxi_u_d:
1627   case Mips::BI__builtin_msa_mini_u_b:
1628   case Mips::BI__builtin_msa_mini_u_h:
1629   case Mips::BI__builtin_msa_mini_u_w:
1630   case Mips::BI__builtin_msa_mini_u_d:
1631   case Mips::BI__builtin_msa_addvi_b:
1632   case Mips::BI__builtin_msa_addvi_h:
1633   case Mips::BI__builtin_msa_addvi_w:
1634   case Mips::BI__builtin_msa_addvi_d:
1635   case Mips::BI__builtin_msa_bclri_w:
1636   case Mips::BI__builtin_msa_bnegi_w:
1637   case Mips::BI__builtin_msa_bseti_w:
1638   case Mips::BI__builtin_msa_sat_s_w:
1639   case Mips::BI__builtin_msa_sat_u_w:
1640   case Mips::BI__builtin_msa_slli_w:
1641   case Mips::BI__builtin_msa_srai_w:
1642   case Mips::BI__builtin_msa_srari_w:
1643   case Mips::BI__builtin_msa_srli_w:
1644   case Mips::BI__builtin_msa_srlri_w:
1645   case Mips::BI__builtin_msa_subvi_b:
1646   case Mips::BI__builtin_msa_subvi_h:
1647   case Mips::BI__builtin_msa_subvi_w:
1648   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1649   case Mips::BI__builtin_msa_binsli_w:
1650   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1651   // These intrinsics take an unsigned 6 bit immediate.
1652   case Mips::BI__builtin_msa_bclri_d:
1653   case Mips::BI__builtin_msa_bnegi_d:
1654   case Mips::BI__builtin_msa_bseti_d:
1655   case Mips::BI__builtin_msa_sat_s_d:
1656   case Mips::BI__builtin_msa_sat_u_d:
1657   case Mips::BI__builtin_msa_slli_d:
1658   case Mips::BI__builtin_msa_srai_d:
1659   case Mips::BI__builtin_msa_srari_d:
1660   case Mips::BI__builtin_msa_srli_d:
1661   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1662   case Mips::BI__builtin_msa_binsli_d:
1663   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1664   // These intrinsics take a signed 5 bit immediate.
1665   case Mips::BI__builtin_msa_ceqi_b:
1666   case Mips::BI__builtin_msa_ceqi_h:
1667   case Mips::BI__builtin_msa_ceqi_w:
1668   case Mips::BI__builtin_msa_ceqi_d:
1669   case Mips::BI__builtin_msa_clti_s_b:
1670   case Mips::BI__builtin_msa_clti_s_h:
1671   case Mips::BI__builtin_msa_clti_s_w:
1672   case Mips::BI__builtin_msa_clti_s_d:
1673   case Mips::BI__builtin_msa_clei_s_b:
1674   case Mips::BI__builtin_msa_clei_s_h:
1675   case Mips::BI__builtin_msa_clei_s_w:
1676   case Mips::BI__builtin_msa_clei_s_d:
1677   case Mips::BI__builtin_msa_maxi_s_b:
1678   case Mips::BI__builtin_msa_maxi_s_h:
1679   case Mips::BI__builtin_msa_maxi_s_w:
1680   case Mips::BI__builtin_msa_maxi_s_d:
1681   case Mips::BI__builtin_msa_mini_s_b:
1682   case Mips::BI__builtin_msa_mini_s_h:
1683   case Mips::BI__builtin_msa_mini_s_w:
1684   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1685   // These intrinsics take an unsigned 8 bit immediate.
1686   case Mips::BI__builtin_msa_andi_b:
1687   case Mips::BI__builtin_msa_nori_b:
1688   case Mips::BI__builtin_msa_ori_b:
1689   case Mips::BI__builtin_msa_shf_b:
1690   case Mips::BI__builtin_msa_shf_h:
1691   case Mips::BI__builtin_msa_shf_w:
1692   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1693   case Mips::BI__builtin_msa_bseli_b:
1694   case Mips::BI__builtin_msa_bmnzi_b:
1695   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1696   // df/n format
1697   // These intrinsics take an unsigned 4 bit immediate.
1698   case Mips::BI__builtin_msa_copy_s_b:
1699   case Mips::BI__builtin_msa_copy_u_b:
1700   case Mips::BI__builtin_msa_insve_b:
1701   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1702   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1703   // These intrinsics take an unsigned 3 bit immediate.
1704   case Mips::BI__builtin_msa_copy_s_h:
1705   case Mips::BI__builtin_msa_copy_u_h:
1706   case Mips::BI__builtin_msa_insve_h:
1707   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1708   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1709   // These intrinsics take an unsigned 2 bit immediate.
1710   case Mips::BI__builtin_msa_copy_s_w:
1711   case Mips::BI__builtin_msa_copy_u_w:
1712   case Mips::BI__builtin_msa_insve_w:
1713   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1714   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1715   // These intrinsics take an unsigned 1 bit immediate.
1716   case Mips::BI__builtin_msa_copy_s_d:
1717   case Mips::BI__builtin_msa_copy_u_d:
1718   case Mips::BI__builtin_msa_insve_d:
1719   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1720   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1721   // Memory offsets and immediate loads.
1722   // These intrinsics take a signed 10 bit immediate.
1723   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1724   case Mips::BI__builtin_msa_ldi_h:
1725   case Mips::BI__builtin_msa_ldi_w:
1726   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1727   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1728   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1729   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1730   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1731   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1732   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1733   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1734   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1735   }
1736 
1737   if (!m)
1738     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1739 
1740   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1741          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1742 }
1743 
1744 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1745   unsigned i = 0, l = 0, u = 0;
1746   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1747                       BuiltinID == PPC::BI__builtin_divdeu ||
1748                       BuiltinID == PPC::BI__builtin_bpermd;
1749   bool IsTarget64Bit = Context.getTargetInfo()
1750                               .getTypeWidth(Context
1751                                             .getTargetInfo()
1752                                             .getIntPtrType()) == 64;
1753   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1754                        BuiltinID == PPC::BI__builtin_divweu ||
1755                        BuiltinID == PPC::BI__builtin_divde ||
1756                        BuiltinID == PPC::BI__builtin_divdeu;
1757 
1758   if (Is64BitBltin && !IsTarget64Bit)
1759       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1760              << TheCall->getSourceRange();
1761 
1762   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1763       (BuiltinID == PPC::BI__builtin_bpermd &&
1764        !Context.getTargetInfo().hasFeature("bpermd")))
1765     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1766            << TheCall->getSourceRange();
1767 
1768   switch (BuiltinID) {
1769   default: return false;
1770   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1771   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1772     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1773            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1774   case PPC::BI__builtin_tbegin:
1775   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1776   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1777   case PPC::BI__builtin_tabortwc:
1778   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1779   case PPC::BI__builtin_tabortwci:
1780   case PPC::BI__builtin_tabortdci:
1781     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1782            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1783   case PPC::BI__builtin_vsx_xxpermdi:
1784   case PPC::BI__builtin_vsx_xxsldwi:
1785     return SemaBuiltinVSX(TheCall);
1786   }
1787   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1788 }
1789 
1790 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1791                                            CallExpr *TheCall) {
1792   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1793     Expr *Arg = TheCall->getArg(0);
1794     llvm::APSInt AbortCode(32);
1795     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1796         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1797       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1798              << Arg->getSourceRange();
1799   }
1800 
1801   // For intrinsics which take an immediate value as part of the instruction,
1802   // range check them here.
1803   unsigned i = 0, l = 0, u = 0;
1804   switch (BuiltinID) {
1805   default: return false;
1806   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1807   case SystemZ::BI__builtin_s390_verimb:
1808   case SystemZ::BI__builtin_s390_verimh:
1809   case SystemZ::BI__builtin_s390_verimf:
1810   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1811   case SystemZ::BI__builtin_s390_vfaeb:
1812   case SystemZ::BI__builtin_s390_vfaeh:
1813   case SystemZ::BI__builtin_s390_vfaef:
1814   case SystemZ::BI__builtin_s390_vfaebs:
1815   case SystemZ::BI__builtin_s390_vfaehs:
1816   case SystemZ::BI__builtin_s390_vfaefs:
1817   case SystemZ::BI__builtin_s390_vfaezb:
1818   case SystemZ::BI__builtin_s390_vfaezh:
1819   case SystemZ::BI__builtin_s390_vfaezf:
1820   case SystemZ::BI__builtin_s390_vfaezbs:
1821   case SystemZ::BI__builtin_s390_vfaezhs:
1822   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1823   case SystemZ::BI__builtin_s390_vfisb:
1824   case SystemZ::BI__builtin_s390_vfidb:
1825     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1826            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1827   case SystemZ::BI__builtin_s390_vftcisb:
1828   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1829   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1830   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1831   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1832   case SystemZ::BI__builtin_s390_vstrcb:
1833   case SystemZ::BI__builtin_s390_vstrch:
1834   case SystemZ::BI__builtin_s390_vstrcf:
1835   case SystemZ::BI__builtin_s390_vstrczb:
1836   case SystemZ::BI__builtin_s390_vstrczh:
1837   case SystemZ::BI__builtin_s390_vstrczf:
1838   case SystemZ::BI__builtin_s390_vstrcbs:
1839   case SystemZ::BI__builtin_s390_vstrchs:
1840   case SystemZ::BI__builtin_s390_vstrcfs:
1841   case SystemZ::BI__builtin_s390_vstrczbs:
1842   case SystemZ::BI__builtin_s390_vstrczhs:
1843   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1844   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1845   case SystemZ::BI__builtin_s390_vfminsb:
1846   case SystemZ::BI__builtin_s390_vfmaxsb:
1847   case SystemZ::BI__builtin_s390_vfmindb:
1848   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
1849   }
1850   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1851 }
1852 
1853 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1854 /// This checks that the target supports __builtin_cpu_supports and
1855 /// that the string argument is constant and valid.
1856 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1857   Expr *Arg = TheCall->getArg(0);
1858 
1859   // Check if the argument is a string literal.
1860   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1861     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1862            << Arg->getSourceRange();
1863 
1864   // Check the contents of the string.
1865   StringRef Feature =
1866       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1867   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1868     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1869            << Arg->getSourceRange();
1870   return false;
1871 }
1872 
1873 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1874 /// This checks that the target supports __builtin_cpu_is and
1875 /// that the string argument is constant and valid.
1876 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1877   Expr *Arg = TheCall->getArg(0);
1878 
1879   // Check if the argument is a string literal.
1880   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1881     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1882            << Arg->getSourceRange();
1883 
1884   // Check the contents of the string.
1885   StringRef Feature =
1886       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1887   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1888     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1889            << Arg->getSourceRange();
1890   return false;
1891 }
1892 
1893 // Check if the rounding mode is legal.
1894 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1895   // Indicates if this instruction has rounding control or just SAE.
1896   bool HasRC = false;
1897 
1898   unsigned ArgNum = 0;
1899   switch (BuiltinID) {
1900   default:
1901     return false;
1902   case X86::BI__builtin_ia32_vcvttsd2si32:
1903   case X86::BI__builtin_ia32_vcvttsd2si64:
1904   case X86::BI__builtin_ia32_vcvttsd2usi32:
1905   case X86::BI__builtin_ia32_vcvttsd2usi64:
1906   case X86::BI__builtin_ia32_vcvttss2si32:
1907   case X86::BI__builtin_ia32_vcvttss2si64:
1908   case X86::BI__builtin_ia32_vcvttss2usi32:
1909   case X86::BI__builtin_ia32_vcvttss2usi64:
1910     ArgNum = 1;
1911     break;
1912   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1913   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1914   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1915   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1916   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1917   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1918   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1919   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1920   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1921   case X86::BI__builtin_ia32_exp2pd_mask:
1922   case X86::BI__builtin_ia32_exp2ps_mask:
1923   case X86::BI__builtin_ia32_getexppd512_mask:
1924   case X86::BI__builtin_ia32_getexpps512_mask:
1925   case X86::BI__builtin_ia32_rcp28pd_mask:
1926   case X86::BI__builtin_ia32_rcp28ps_mask:
1927   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1928   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1929   case X86::BI__builtin_ia32_vcomisd:
1930   case X86::BI__builtin_ia32_vcomiss:
1931   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1932     ArgNum = 3;
1933     break;
1934   case X86::BI__builtin_ia32_cmppd512_mask:
1935   case X86::BI__builtin_ia32_cmpps512_mask:
1936   case X86::BI__builtin_ia32_cmpsd_mask:
1937   case X86::BI__builtin_ia32_cmpss_mask:
1938   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1939   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1940   case X86::BI__builtin_ia32_getexpss128_round_mask:
1941   case X86::BI__builtin_ia32_maxpd512_mask:
1942   case X86::BI__builtin_ia32_maxps512_mask:
1943   case X86::BI__builtin_ia32_maxsd_round_mask:
1944   case X86::BI__builtin_ia32_maxss_round_mask:
1945   case X86::BI__builtin_ia32_minpd512_mask:
1946   case X86::BI__builtin_ia32_minps512_mask:
1947   case X86::BI__builtin_ia32_minsd_round_mask:
1948   case X86::BI__builtin_ia32_minss_round_mask:
1949   case X86::BI__builtin_ia32_rcp28sd_round_mask:
1950   case X86::BI__builtin_ia32_rcp28ss_round_mask:
1951   case X86::BI__builtin_ia32_reducepd512_mask:
1952   case X86::BI__builtin_ia32_reduceps512_mask:
1953   case X86::BI__builtin_ia32_rndscalepd_mask:
1954   case X86::BI__builtin_ia32_rndscaleps_mask:
1955   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1956   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1957     ArgNum = 4;
1958     break;
1959   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1960   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1961   case X86::BI__builtin_ia32_fixupimmps512_mask:
1962   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1963   case X86::BI__builtin_ia32_fixupimmsd_mask:
1964   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1965   case X86::BI__builtin_ia32_fixupimmss_mask:
1966   case X86::BI__builtin_ia32_fixupimmss_maskz:
1967   case X86::BI__builtin_ia32_rangepd512_mask:
1968   case X86::BI__builtin_ia32_rangeps512_mask:
1969   case X86::BI__builtin_ia32_rangesd128_round_mask:
1970   case X86::BI__builtin_ia32_rangess128_round_mask:
1971   case X86::BI__builtin_ia32_reducesd_mask:
1972   case X86::BI__builtin_ia32_reducess_mask:
1973   case X86::BI__builtin_ia32_rndscalesd_round_mask:
1974   case X86::BI__builtin_ia32_rndscaless_round_mask:
1975     ArgNum = 5;
1976     break;
1977   case X86::BI__builtin_ia32_vcvtsd2si64:
1978   case X86::BI__builtin_ia32_vcvtsd2si32:
1979   case X86::BI__builtin_ia32_vcvtsd2usi32:
1980   case X86::BI__builtin_ia32_vcvtsd2usi64:
1981   case X86::BI__builtin_ia32_vcvtss2si32:
1982   case X86::BI__builtin_ia32_vcvtss2si64:
1983   case X86::BI__builtin_ia32_vcvtss2usi32:
1984   case X86::BI__builtin_ia32_vcvtss2usi64:
1985     ArgNum = 1;
1986     HasRC = true;
1987     break;
1988   case X86::BI__builtin_ia32_cvtsi2sd64:
1989   case X86::BI__builtin_ia32_cvtsi2ss32:
1990   case X86::BI__builtin_ia32_cvtsi2ss64:
1991   case X86::BI__builtin_ia32_cvtusi2sd64:
1992   case X86::BI__builtin_ia32_cvtusi2ss32:
1993   case X86::BI__builtin_ia32_cvtusi2ss64:
1994     ArgNum = 2;
1995     HasRC = true;
1996     break;
1997   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1998   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1999   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2000   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2001   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2002   case X86::BI__builtin_ia32_cvtps2qq512_mask:
2003   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2004   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2005   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2006   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2007   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2008   case X86::BI__builtin_ia32_sqrtpd512_mask:
2009   case X86::BI__builtin_ia32_sqrtps512_mask:
2010     ArgNum = 3;
2011     HasRC = true;
2012     break;
2013   case X86::BI__builtin_ia32_addpd512_mask:
2014   case X86::BI__builtin_ia32_addps512_mask:
2015   case X86::BI__builtin_ia32_divpd512_mask:
2016   case X86::BI__builtin_ia32_divps512_mask:
2017   case X86::BI__builtin_ia32_mulpd512_mask:
2018   case X86::BI__builtin_ia32_mulps512_mask:
2019   case X86::BI__builtin_ia32_subpd512_mask:
2020   case X86::BI__builtin_ia32_subps512_mask:
2021   case X86::BI__builtin_ia32_addss_round_mask:
2022   case X86::BI__builtin_ia32_addsd_round_mask:
2023   case X86::BI__builtin_ia32_divss_round_mask:
2024   case X86::BI__builtin_ia32_divsd_round_mask:
2025   case X86::BI__builtin_ia32_mulss_round_mask:
2026   case X86::BI__builtin_ia32_mulsd_round_mask:
2027   case X86::BI__builtin_ia32_subss_round_mask:
2028   case X86::BI__builtin_ia32_subsd_round_mask:
2029   case X86::BI__builtin_ia32_scalefpd512_mask:
2030   case X86::BI__builtin_ia32_scalefps512_mask:
2031   case X86::BI__builtin_ia32_scalefsd_round_mask:
2032   case X86::BI__builtin_ia32_scalefss_round_mask:
2033   case X86::BI__builtin_ia32_getmantpd512_mask:
2034   case X86::BI__builtin_ia32_getmantps512_mask:
2035   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2036   case X86::BI__builtin_ia32_sqrtsd_round_mask:
2037   case X86::BI__builtin_ia32_sqrtss_round_mask:
2038   case X86::BI__builtin_ia32_vfmaddpd512_mask:
2039   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2040   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2041   case X86::BI__builtin_ia32_vfmaddps512_mask:
2042   case X86::BI__builtin_ia32_vfmaddps512_mask3:
2043   case X86::BI__builtin_ia32_vfmaddps512_maskz:
2044   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2045   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2046   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2047   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2048   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2049   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2050   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2051   case X86::BI__builtin_ia32_vfmsubps512_mask3:
2052   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2053   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2054   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2055   case X86::BI__builtin_ia32_vfnmaddps512_mask:
2056   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2057   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2058   case X86::BI__builtin_ia32_vfnmsubps512_mask:
2059   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2060   case X86::BI__builtin_ia32_vfmaddsd3_mask:
2061   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2062   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2063   case X86::BI__builtin_ia32_vfmaddss3_mask:
2064   case X86::BI__builtin_ia32_vfmaddss3_maskz:
2065   case X86::BI__builtin_ia32_vfmaddss3_mask3:
2066     ArgNum = 4;
2067     HasRC = true;
2068     break;
2069   case X86::BI__builtin_ia32_getmantsd_round_mask:
2070   case X86::BI__builtin_ia32_getmantss_round_mask:
2071     ArgNum = 5;
2072     HasRC = true;
2073     break;
2074   }
2075 
2076   llvm::APSInt Result;
2077 
2078   // We can't check the value of a dependent argument.
2079   Expr *Arg = TheCall->getArg(ArgNum);
2080   if (Arg->isTypeDependent() || Arg->isValueDependent())
2081     return false;
2082 
2083   // Check constant-ness first.
2084   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2085     return true;
2086 
2087   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2088   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2089   // combined with ROUND_NO_EXC.
2090   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2091       Result == 8/*ROUND_NO_EXC*/ ||
2092       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2093     return false;
2094 
2095   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2096     << Arg->getSourceRange();
2097 }
2098 
2099 // Check if the gather/scatter scale is legal.
2100 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2101                                              CallExpr *TheCall) {
2102   unsigned ArgNum = 0;
2103   switch (BuiltinID) {
2104   default:
2105     return false;
2106   case X86::BI__builtin_ia32_gatherpfdpd:
2107   case X86::BI__builtin_ia32_gatherpfdps:
2108   case X86::BI__builtin_ia32_gatherpfqpd:
2109   case X86::BI__builtin_ia32_gatherpfqps:
2110   case X86::BI__builtin_ia32_scatterpfdpd:
2111   case X86::BI__builtin_ia32_scatterpfdps:
2112   case X86::BI__builtin_ia32_scatterpfqpd:
2113   case X86::BI__builtin_ia32_scatterpfqps:
2114     ArgNum = 3;
2115     break;
2116   case X86::BI__builtin_ia32_gatherd_pd:
2117   case X86::BI__builtin_ia32_gatherd_pd256:
2118   case X86::BI__builtin_ia32_gatherq_pd:
2119   case X86::BI__builtin_ia32_gatherq_pd256:
2120   case X86::BI__builtin_ia32_gatherd_ps:
2121   case X86::BI__builtin_ia32_gatherd_ps256:
2122   case X86::BI__builtin_ia32_gatherq_ps:
2123   case X86::BI__builtin_ia32_gatherq_ps256:
2124   case X86::BI__builtin_ia32_gatherd_q:
2125   case X86::BI__builtin_ia32_gatherd_q256:
2126   case X86::BI__builtin_ia32_gatherq_q:
2127   case X86::BI__builtin_ia32_gatherq_q256:
2128   case X86::BI__builtin_ia32_gatherd_d:
2129   case X86::BI__builtin_ia32_gatherd_d256:
2130   case X86::BI__builtin_ia32_gatherq_d:
2131   case X86::BI__builtin_ia32_gatherq_d256:
2132   case X86::BI__builtin_ia32_gather3div2df:
2133   case X86::BI__builtin_ia32_gather3div2di:
2134   case X86::BI__builtin_ia32_gather3div4df:
2135   case X86::BI__builtin_ia32_gather3div4di:
2136   case X86::BI__builtin_ia32_gather3div4sf:
2137   case X86::BI__builtin_ia32_gather3div4si:
2138   case X86::BI__builtin_ia32_gather3div8sf:
2139   case X86::BI__builtin_ia32_gather3div8si:
2140   case X86::BI__builtin_ia32_gather3siv2df:
2141   case X86::BI__builtin_ia32_gather3siv2di:
2142   case X86::BI__builtin_ia32_gather3siv4df:
2143   case X86::BI__builtin_ia32_gather3siv4di:
2144   case X86::BI__builtin_ia32_gather3siv4sf:
2145   case X86::BI__builtin_ia32_gather3siv4si:
2146   case X86::BI__builtin_ia32_gather3siv8sf:
2147   case X86::BI__builtin_ia32_gather3siv8si:
2148   case X86::BI__builtin_ia32_gathersiv8df:
2149   case X86::BI__builtin_ia32_gathersiv16sf:
2150   case X86::BI__builtin_ia32_gatherdiv8df:
2151   case X86::BI__builtin_ia32_gatherdiv16sf:
2152   case X86::BI__builtin_ia32_gathersiv8di:
2153   case X86::BI__builtin_ia32_gathersiv16si:
2154   case X86::BI__builtin_ia32_gatherdiv8di:
2155   case X86::BI__builtin_ia32_gatherdiv16si:
2156   case X86::BI__builtin_ia32_scatterdiv2df:
2157   case X86::BI__builtin_ia32_scatterdiv2di:
2158   case X86::BI__builtin_ia32_scatterdiv4df:
2159   case X86::BI__builtin_ia32_scatterdiv4di:
2160   case X86::BI__builtin_ia32_scatterdiv4sf:
2161   case X86::BI__builtin_ia32_scatterdiv4si:
2162   case X86::BI__builtin_ia32_scatterdiv8sf:
2163   case X86::BI__builtin_ia32_scatterdiv8si:
2164   case X86::BI__builtin_ia32_scattersiv2df:
2165   case X86::BI__builtin_ia32_scattersiv2di:
2166   case X86::BI__builtin_ia32_scattersiv4df:
2167   case X86::BI__builtin_ia32_scattersiv4di:
2168   case X86::BI__builtin_ia32_scattersiv4sf:
2169   case X86::BI__builtin_ia32_scattersiv4si:
2170   case X86::BI__builtin_ia32_scattersiv8sf:
2171   case X86::BI__builtin_ia32_scattersiv8si:
2172   case X86::BI__builtin_ia32_scattersiv8df:
2173   case X86::BI__builtin_ia32_scattersiv16sf:
2174   case X86::BI__builtin_ia32_scatterdiv8df:
2175   case X86::BI__builtin_ia32_scatterdiv16sf:
2176   case X86::BI__builtin_ia32_scattersiv8di:
2177   case X86::BI__builtin_ia32_scattersiv16si:
2178   case X86::BI__builtin_ia32_scatterdiv8di:
2179   case X86::BI__builtin_ia32_scatterdiv16si:
2180     ArgNum = 4;
2181     break;
2182   }
2183 
2184   llvm::APSInt Result;
2185 
2186   // We can't check the value of a dependent argument.
2187   Expr *Arg = TheCall->getArg(ArgNum);
2188   if (Arg->isTypeDependent() || Arg->isValueDependent())
2189     return false;
2190 
2191   // Check constant-ness first.
2192   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2193     return true;
2194 
2195   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2196     return false;
2197 
2198   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2199     << Arg->getSourceRange();
2200 }
2201 
2202 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2203   if (BuiltinID == X86::BI__builtin_cpu_supports)
2204     return SemaBuiltinCpuSupports(*this, TheCall);
2205 
2206   if (BuiltinID == X86::BI__builtin_cpu_is)
2207     return SemaBuiltinCpuIs(*this, TheCall);
2208 
2209   // If the intrinsic has rounding or SAE make sure its valid.
2210   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2211     return true;
2212 
2213   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2214   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2215     return true;
2216 
2217   // For intrinsics which take an immediate value as part of the instruction,
2218   // range check them here.
2219   int i = 0, l = 0, u = 0;
2220   switch (BuiltinID) {
2221   default:
2222     return false;
2223   case X86::BI_mm_prefetch:
2224     i = 1; l = 0; u = 3;
2225     break;
2226   case X86::BI__builtin_ia32_sha1rnds4:
2227   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2228   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2229   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2230   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2231     i = 2; l = 0; u = 3;
2232     break;
2233   case X86::BI__builtin_ia32_vpermil2pd:
2234   case X86::BI__builtin_ia32_vpermil2pd256:
2235   case X86::BI__builtin_ia32_vpermil2ps:
2236   case X86::BI__builtin_ia32_vpermil2ps256:
2237     i = 3; l = 0; u = 3;
2238     break;
2239   case X86::BI__builtin_ia32_cmpb128_mask:
2240   case X86::BI__builtin_ia32_cmpw128_mask:
2241   case X86::BI__builtin_ia32_cmpd128_mask:
2242   case X86::BI__builtin_ia32_cmpq128_mask:
2243   case X86::BI__builtin_ia32_cmpb256_mask:
2244   case X86::BI__builtin_ia32_cmpw256_mask:
2245   case X86::BI__builtin_ia32_cmpd256_mask:
2246   case X86::BI__builtin_ia32_cmpq256_mask:
2247   case X86::BI__builtin_ia32_cmpb512_mask:
2248   case X86::BI__builtin_ia32_cmpw512_mask:
2249   case X86::BI__builtin_ia32_cmpd512_mask:
2250   case X86::BI__builtin_ia32_cmpq512_mask:
2251   case X86::BI__builtin_ia32_ucmpb128_mask:
2252   case X86::BI__builtin_ia32_ucmpw128_mask:
2253   case X86::BI__builtin_ia32_ucmpd128_mask:
2254   case X86::BI__builtin_ia32_ucmpq128_mask:
2255   case X86::BI__builtin_ia32_ucmpb256_mask:
2256   case X86::BI__builtin_ia32_ucmpw256_mask:
2257   case X86::BI__builtin_ia32_ucmpd256_mask:
2258   case X86::BI__builtin_ia32_ucmpq256_mask:
2259   case X86::BI__builtin_ia32_ucmpb512_mask:
2260   case X86::BI__builtin_ia32_ucmpw512_mask:
2261   case X86::BI__builtin_ia32_ucmpd512_mask:
2262   case X86::BI__builtin_ia32_ucmpq512_mask:
2263   case X86::BI__builtin_ia32_vpcomub:
2264   case X86::BI__builtin_ia32_vpcomuw:
2265   case X86::BI__builtin_ia32_vpcomud:
2266   case X86::BI__builtin_ia32_vpcomuq:
2267   case X86::BI__builtin_ia32_vpcomb:
2268   case X86::BI__builtin_ia32_vpcomw:
2269   case X86::BI__builtin_ia32_vpcomd:
2270   case X86::BI__builtin_ia32_vpcomq:
2271     i = 2; l = 0; u = 7;
2272     break;
2273   case X86::BI__builtin_ia32_roundps:
2274   case X86::BI__builtin_ia32_roundpd:
2275   case X86::BI__builtin_ia32_roundps256:
2276   case X86::BI__builtin_ia32_roundpd256:
2277     i = 1; l = 0; u = 15;
2278     break;
2279   case X86::BI__builtin_ia32_roundss:
2280   case X86::BI__builtin_ia32_roundsd:
2281   case X86::BI__builtin_ia32_rangepd128_mask:
2282   case X86::BI__builtin_ia32_rangepd256_mask:
2283   case X86::BI__builtin_ia32_rangepd512_mask:
2284   case X86::BI__builtin_ia32_rangeps128_mask:
2285   case X86::BI__builtin_ia32_rangeps256_mask:
2286   case X86::BI__builtin_ia32_rangeps512_mask:
2287   case X86::BI__builtin_ia32_getmantsd_round_mask:
2288   case X86::BI__builtin_ia32_getmantss_round_mask:
2289     i = 2; l = 0; u = 15;
2290     break;
2291   case X86::BI__builtin_ia32_cmpps:
2292   case X86::BI__builtin_ia32_cmpss:
2293   case X86::BI__builtin_ia32_cmppd:
2294   case X86::BI__builtin_ia32_cmpsd:
2295   case X86::BI__builtin_ia32_cmpps256:
2296   case X86::BI__builtin_ia32_cmppd256:
2297   case X86::BI__builtin_ia32_cmpps128_mask:
2298   case X86::BI__builtin_ia32_cmppd128_mask:
2299   case X86::BI__builtin_ia32_cmpps256_mask:
2300   case X86::BI__builtin_ia32_cmppd256_mask:
2301   case X86::BI__builtin_ia32_cmpps512_mask:
2302   case X86::BI__builtin_ia32_cmppd512_mask:
2303   case X86::BI__builtin_ia32_cmpsd_mask:
2304   case X86::BI__builtin_ia32_cmpss_mask:
2305     i = 2; l = 0; u = 31;
2306     break;
2307   case X86::BI__builtin_ia32_xabort:
2308     i = 0; l = -128; u = 255;
2309     break;
2310   case X86::BI__builtin_ia32_pshufw:
2311   case X86::BI__builtin_ia32_aeskeygenassist128:
2312     i = 1; l = -128; u = 255;
2313     break;
2314   case X86::BI__builtin_ia32_vcvtps2ph:
2315   case X86::BI__builtin_ia32_vcvtps2ph256:
2316   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2317   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2318   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2319   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2320   case X86::BI__builtin_ia32_rndscaleps_mask:
2321   case X86::BI__builtin_ia32_rndscalepd_mask:
2322   case X86::BI__builtin_ia32_reducepd128_mask:
2323   case X86::BI__builtin_ia32_reducepd256_mask:
2324   case X86::BI__builtin_ia32_reducepd512_mask:
2325   case X86::BI__builtin_ia32_reduceps128_mask:
2326   case X86::BI__builtin_ia32_reduceps256_mask:
2327   case X86::BI__builtin_ia32_reduceps512_mask:
2328   case X86::BI__builtin_ia32_prold512_mask:
2329   case X86::BI__builtin_ia32_prolq512_mask:
2330   case X86::BI__builtin_ia32_prold128_mask:
2331   case X86::BI__builtin_ia32_prold256_mask:
2332   case X86::BI__builtin_ia32_prolq128_mask:
2333   case X86::BI__builtin_ia32_prolq256_mask:
2334   case X86::BI__builtin_ia32_prord128_mask:
2335   case X86::BI__builtin_ia32_prord256_mask:
2336   case X86::BI__builtin_ia32_prorq128_mask:
2337   case X86::BI__builtin_ia32_prorq256_mask:
2338   case X86::BI__builtin_ia32_fpclasspd128_mask:
2339   case X86::BI__builtin_ia32_fpclasspd256_mask:
2340   case X86::BI__builtin_ia32_fpclassps128_mask:
2341   case X86::BI__builtin_ia32_fpclassps256_mask:
2342   case X86::BI__builtin_ia32_fpclassps512_mask:
2343   case X86::BI__builtin_ia32_fpclasspd512_mask:
2344   case X86::BI__builtin_ia32_fpclasssd_mask:
2345   case X86::BI__builtin_ia32_fpclassss_mask:
2346     i = 1; l = 0; u = 255;
2347     break;
2348   case X86::BI__builtin_ia32_palignr:
2349   case X86::BI__builtin_ia32_insertps128:
2350   case X86::BI__builtin_ia32_dpps:
2351   case X86::BI__builtin_ia32_dppd:
2352   case X86::BI__builtin_ia32_dpps256:
2353   case X86::BI__builtin_ia32_mpsadbw128:
2354   case X86::BI__builtin_ia32_mpsadbw256:
2355   case X86::BI__builtin_ia32_pcmpistrm128:
2356   case X86::BI__builtin_ia32_pcmpistri128:
2357   case X86::BI__builtin_ia32_pcmpistria128:
2358   case X86::BI__builtin_ia32_pcmpistric128:
2359   case X86::BI__builtin_ia32_pcmpistrio128:
2360   case X86::BI__builtin_ia32_pcmpistris128:
2361   case X86::BI__builtin_ia32_pcmpistriz128:
2362   case X86::BI__builtin_ia32_pclmulqdq128:
2363   case X86::BI__builtin_ia32_vperm2f128_pd256:
2364   case X86::BI__builtin_ia32_vperm2f128_ps256:
2365   case X86::BI__builtin_ia32_vperm2f128_si256:
2366   case X86::BI__builtin_ia32_permti256:
2367     i = 2; l = -128; u = 255;
2368     break;
2369   case X86::BI__builtin_ia32_palignr128:
2370   case X86::BI__builtin_ia32_palignr256:
2371   case X86::BI__builtin_ia32_palignr512_mask:
2372   case X86::BI__builtin_ia32_vcomisd:
2373   case X86::BI__builtin_ia32_vcomiss:
2374   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2375   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2376   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2377   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2378   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2379   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2380   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2381     i = 2; l = 0; u = 255;
2382     break;
2383   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2384   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2385   case X86::BI__builtin_ia32_fixupimmps512_mask:
2386   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2387   case X86::BI__builtin_ia32_fixupimmsd_mask:
2388   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2389   case X86::BI__builtin_ia32_fixupimmss_mask:
2390   case X86::BI__builtin_ia32_fixupimmss_maskz:
2391   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2392   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2393   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2394   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2395   case X86::BI__builtin_ia32_fixupimmps128_mask:
2396   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2397   case X86::BI__builtin_ia32_fixupimmps256_mask:
2398   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2399   case X86::BI__builtin_ia32_pternlogd512_mask:
2400   case X86::BI__builtin_ia32_pternlogd512_maskz:
2401   case X86::BI__builtin_ia32_pternlogq512_mask:
2402   case X86::BI__builtin_ia32_pternlogq512_maskz:
2403   case X86::BI__builtin_ia32_pternlogd128_mask:
2404   case X86::BI__builtin_ia32_pternlogd128_maskz:
2405   case X86::BI__builtin_ia32_pternlogd256_mask:
2406   case X86::BI__builtin_ia32_pternlogd256_maskz:
2407   case X86::BI__builtin_ia32_pternlogq128_mask:
2408   case X86::BI__builtin_ia32_pternlogq128_maskz:
2409   case X86::BI__builtin_ia32_pternlogq256_mask:
2410   case X86::BI__builtin_ia32_pternlogq256_maskz:
2411     i = 3; l = 0; u = 255;
2412     break;
2413   case X86::BI__builtin_ia32_gatherpfdpd:
2414   case X86::BI__builtin_ia32_gatherpfdps:
2415   case X86::BI__builtin_ia32_gatherpfqpd:
2416   case X86::BI__builtin_ia32_gatherpfqps:
2417   case X86::BI__builtin_ia32_scatterpfdpd:
2418   case X86::BI__builtin_ia32_scatterpfdps:
2419   case X86::BI__builtin_ia32_scatterpfqpd:
2420   case X86::BI__builtin_ia32_scatterpfqps:
2421     i = 4; l = 2; u = 3;
2422     break;
2423   case X86::BI__builtin_ia32_pcmpestrm128:
2424   case X86::BI__builtin_ia32_pcmpestri128:
2425   case X86::BI__builtin_ia32_pcmpestria128:
2426   case X86::BI__builtin_ia32_pcmpestric128:
2427   case X86::BI__builtin_ia32_pcmpestrio128:
2428   case X86::BI__builtin_ia32_pcmpestris128:
2429   case X86::BI__builtin_ia32_pcmpestriz128:
2430     i = 4; l = -128; u = 255;
2431     break;
2432   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2433   case X86::BI__builtin_ia32_rndscaless_round_mask:
2434     i = 4; l = 0; u = 255;
2435     break;
2436   }
2437   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2438 }
2439 
2440 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2441 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2442 /// Returns true when the format fits the function and the FormatStringInfo has
2443 /// been populated.
2444 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2445                                FormatStringInfo *FSI) {
2446   FSI->HasVAListArg = Format->getFirstArg() == 0;
2447   FSI->FormatIdx = Format->getFormatIdx() - 1;
2448   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2449 
2450   // The way the format attribute works in GCC, the implicit this argument
2451   // of member functions is counted. However, it doesn't appear in our own
2452   // lists, so decrement format_idx in that case.
2453   if (IsCXXMember) {
2454     if(FSI->FormatIdx == 0)
2455       return false;
2456     --FSI->FormatIdx;
2457     if (FSI->FirstDataArg != 0)
2458       --FSI->FirstDataArg;
2459   }
2460   return true;
2461 }
2462 
2463 /// Checks if a the given expression evaluates to null.
2464 ///
2465 /// \brief Returns true if the value evaluates to null.
2466 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2467   // If the expression has non-null type, it doesn't evaluate to null.
2468   if (auto nullability
2469         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2470     if (*nullability == NullabilityKind::NonNull)
2471       return false;
2472   }
2473 
2474   // As a special case, transparent unions initialized with zero are
2475   // considered null for the purposes of the nonnull attribute.
2476   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2477     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2478       if (const CompoundLiteralExpr *CLE =
2479           dyn_cast<CompoundLiteralExpr>(Expr))
2480         if (const InitListExpr *ILE =
2481             dyn_cast<InitListExpr>(CLE->getInitializer()))
2482           Expr = ILE->getInit(0);
2483   }
2484 
2485   bool Result;
2486   return (!Expr->isValueDependent() &&
2487           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2488           !Result);
2489 }
2490 
2491 static void CheckNonNullArgument(Sema &S,
2492                                  const Expr *ArgExpr,
2493                                  SourceLocation CallSiteLoc) {
2494   if (CheckNonNullExpr(S, ArgExpr))
2495     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2496            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2497 }
2498 
2499 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2500   FormatStringInfo FSI;
2501   if ((GetFormatStringType(Format) == FST_NSString) &&
2502       getFormatStringInfo(Format, false, &FSI)) {
2503     Idx = FSI.FormatIdx;
2504     return true;
2505   }
2506   return false;
2507 }
2508 /// \brief Diagnose use of %s directive in an NSString which is being passed
2509 /// as formatting string to formatting method.
2510 static void
2511 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2512                                         const NamedDecl *FDecl,
2513                                         Expr **Args,
2514                                         unsigned NumArgs) {
2515   unsigned Idx = 0;
2516   bool Format = false;
2517   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2518   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2519     Idx = 2;
2520     Format = true;
2521   }
2522   else
2523     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2524       if (S.GetFormatNSStringIdx(I, Idx)) {
2525         Format = true;
2526         break;
2527       }
2528     }
2529   if (!Format || NumArgs <= Idx)
2530     return;
2531   const Expr *FormatExpr = Args[Idx];
2532   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2533     FormatExpr = CSCE->getSubExpr();
2534   const StringLiteral *FormatString;
2535   if (const ObjCStringLiteral *OSL =
2536       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2537     FormatString = OSL->getString();
2538   else
2539     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2540   if (!FormatString)
2541     return;
2542   if (S.FormatStringHasSArg(FormatString)) {
2543     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2544       << "%s" << 1 << 1;
2545     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2546       << FDecl->getDeclName();
2547   }
2548 }
2549 
2550 /// Determine whether the given type has a non-null nullability annotation.
2551 static bool isNonNullType(ASTContext &ctx, QualType type) {
2552   if (auto nullability = type->getNullability(ctx))
2553     return *nullability == NullabilityKind::NonNull;
2554 
2555   return false;
2556 }
2557 
2558 static void CheckNonNullArguments(Sema &S,
2559                                   const NamedDecl *FDecl,
2560                                   const FunctionProtoType *Proto,
2561                                   ArrayRef<const Expr *> Args,
2562                                   SourceLocation CallSiteLoc) {
2563   assert((FDecl || Proto) && "Need a function declaration or prototype");
2564 
2565   // Check the attributes attached to the method/function itself.
2566   llvm::SmallBitVector NonNullArgs;
2567   if (FDecl) {
2568     // Handle the nonnull attribute on the function/method declaration itself.
2569     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2570       if (!NonNull->args_size()) {
2571         // Easy case: all pointer arguments are nonnull.
2572         for (const auto *Arg : Args)
2573           if (S.isValidPointerAttrType(Arg->getType()))
2574             CheckNonNullArgument(S, Arg, CallSiteLoc);
2575         return;
2576       }
2577 
2578       for (unsigned Val : NonNull->args()) {
2579         if (Val >= Args.size())
2580           continue;
2581         if (NonNullArgs.empty())
2582           NonNullArgs.resize(Args.size());
2583         NonNullArgs.set(Val);
2584       }
2585     }
2586   }
2587 
2588   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2589     // Handle the nonnull attribute on the parameters of the
2590     // function/method.
2591     ArrayRef<ParmVarDecl*> parms;
2592     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2593       parms = FD->parameters();
2594     else
2595       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2596 
2597     unsigned ParamIndex = 0;
2598     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2599          I != E; ++I, ++ParamIndex) {
2600       const ParmVarDecl *PVD = *I;
2601       if (PVD->hasAttr<NonNullAttr>() ||
2602           isNonNullType(S.Context, PVD->getType())) {
2603         if (NonNullArgs.empty())
2604           NonNullArgs.resize(Args.size());
2605 
2606         NonNullArgs.set(ParamIndex);
2607       }
2608     }
2609   } else {
2610     // If we have a non-function, non-method declaration but no
2611     // function prototype, try to dig out the function prototype.
2612     if (!Proto) {
2613       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2614         QualType type = VD->getType().getNonReferenceType();
2615         if (auto pointerType = type->getAs<PointerType>())
2616           type = pointerType->getPointeeType();
2617         else if (auto blockType = type->getAs<BlockPointerType>())
2618           type = blockType->getPointeeType();
2619         // FIXME: data member pointers?
2620 
2621         // Dig out the function prototype, if there is one.
2622         Proto = type->getAs<FunctionProtoType>();
2623       }
2624     }
2625 
2626     // Fill in non-null argument information from the nullability
2627     // information on the parameter types (if we have them).
2628     if (Proto) {
2629       unsigned Index = 0;
2630       for (auto paramType : Proto->getParamTypes()) {
2631         if (isNonNullType(S.Context, paramType)) {
2632           if (NonNullArgs.empty())
2633             NonNullArgs.resize(Args.size());
2634 
2635           NonNullArgs.set(Index);
2636         }
2637 
2638         ++Index;
2639       }
2640     }
2641   }
2642 
2643   // Check for non-null arguments.
2644   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2645        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2646     if (NonNullArgs[ArgIndex])
2647       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2648   }
2649 }
2650 
2651 /// Handles the checks for format strings, non-POD arguments to vararg
2652 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2653 /// attributes.
2654 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2655                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
2656                      bool IsMemberFunction, SourceLocation Loc,
2657                      SourceRange Range, VariadicCallType CallType) {
2658   // FIXME: We should check as much as we can in the template definition.
2659   if (CurContext->isDependentContext())
2660     return;
2661 
2662   // Printf and scanf checking.
2663   llvm::SmallBitVector CheckedVarArgs;
2664   if (FDecl) {
2665     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2666       // Only create vector if there are format attributes.
2667       CheckedVarArgs.resize(Args.size());
2668 
2669       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2670                            CheckedVarArgs);
2671     }
2672   }
2673 
2674   // Refuse POD arguments that weren't caught by the format string
2675   // checks above.
2676   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2677   if (CallType != VariadicDoesNotApply &&
2678       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2679     unsigned NumParams = Proto ? Proto->getNumParams()
2680                        : FDecl && isa<FunctionDecl>(FDecl)
2681                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2682                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2683                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2684                        : 0;
2685 
2686     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2687       // Args[ArgIdx] can be null in malformed code.
2688       if (const Expr *Arg = Args[ArgIdx]) {
2689         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2690           checkVariadicArgument(Arg, CallType);
2691       }
2692     }
2693   }
2694 
2695   if (FDecl || Proto) {
2696     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2697 
2698     // Type safety checking.
2699     if (FDecl) {
2700       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2701         CheckArgumentWithTypeTag(I, Args.data());
2702     }
2703   }
2704 
2705   if (FD)
2706     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2707 }
2708 
2709 /// CheckConstructorCall - Check a constructor call for correctness and safety
2710 /// properties not enforced by the C type system.
2711 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2712                                 ArrayRef<const Expr *> Args,
2713                                 const FunctionProtoType *Proto,
2714                                 SourceLocation Loc) {
2715   VariadicCallType CallType =
2716     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2717   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2718             Loc, SourceRange(), CallType);
2719 }
2720 
2721 /// CheckFunctionCall - Check a direct function call for various correctness
2722 /// and safety properties not strictly enforced by the C type system.
2723 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2724                              const FunctionProtoType *Proto) {
2725   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2726                               isa<CXXMethodDecl>(FDecl);
2727   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2728                           IsMemberOperatorCall;
2729   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2730                                                   TheCall->getCallee());
2731   Expr** Args = TheCall->getArgs();
2732   unsigned NumArgs = TheCall->getNumArgs();
2733 
2734   Expr *ImplicitThis = nullptr;
2735   if (IsMemberOperatorCall) {
2736     // If this is a call to a member operator, hide the first argument
2737     // from checkCall.
2738     // FIXME: Our choice of AST representation here is less than ideal.
2739     ImplicitThis = Args[0];
2740     ++Args;
2741     --NumArgs;
2742   } else if (IsMemberFunction)
2743     ImplicitThis =
2744         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2745 
2746   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2747             IsMemberFunction, TheCall->getRParenLoc(),
2748             TheCall->getCallee()->getSourceRange(), CallType);
2749 
2750   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2751   // None of the checks below are needed for functions that don't have
2752   // simple names (e.g., C++ conversion functions).
2753   if (!FnInfo)
2754     return false;
2755 
2756   CheckAbsoluteValueFunction(TheCall, FDecl);
2757   CheckMaxUnsignedZero(TheCall, FDecl);
2758 
2759   if (getLangOpts().ObjC1)
2760     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2761 
2762   unsigned CMId = FDecl->getMemoryFunctionKind();
2763   if (CMId == 0)
2764     return false;
2765 
2766   // Handle memory setting and copying functions.
2767   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2768     CheckStrlcpycatArguments(TheCall, FnInfo);
2769   else if (CMId == Builtin::BIstrncat)
2770     CheckStrncatArguments(TheCall, FnInfo);
2771   else
2772     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2773 
2774   return false;
2775 }
2776 
2777 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2778                                ArrayRef<const Expr *> Args) {
2779   VariadicCallType CallType =
2780       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2781 
2782   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2783             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2784             CallType);
2785 
2786   return false;
2787 }
2788 
2789 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2790                             const FunctionProtoType *Proto) {
2791   QualType Ty;
2792   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2793     Ty = V->getType().getNonReferenceType();
2794   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2795     Ty = F->getType().getNonReferenceType();
2796   else
2797     return false;
2798 
2799   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2800       !Ty->isFunctionProtoType())
2801     return false;
2802 
2803   VariadicCallType CallType;
2804   if (!Proto || !Proto->isVariadic()) {
2805     CallType = VariadicDoesNotApply;
2806   } else if (Ty->isBlockPointerType()) {
2807     CallType = VariadicBlock;
2808   } else { // Ty->isFunctionPointerType()
2809     CallType = VariadicFunction;
2810   }
2811 
2812   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2813             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2814             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2815             TheCall->getCallee()->getSourceRange(), CallType);
2816 
2817   return false;
2818 }
2819 
2820 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2821 /// such as function pointers returned from functions.
2822 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2823   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2824                                                   TheCall->getCallee());
2825   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2826             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2827             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2828             TheCall->getCallee()->getSourceRange(), CallType);
2829 
2830   return false;
2831 }
2832 
2833 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2834   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2835     return false;
2836 
2837   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2838   switch (Op) {
2839   case AtomicExpr::AO__c11_atomic_init:
2840   case AtomicExpr::AO__opencl_atomic_init:
2841     llvm_unreachable("There is no ordering argument for an init");
2842 
2843   case AtomicExpr::AO__c11_atomic_load:
2844   case AtomicExpr::AO__opencl_atomic_load:
2845   case AtomicExpr::AO__atomic_load_n:
2846   case AtomicExpr::AO__atomic_load:
2847     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2848            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2849 
2850   case AtomicExpr::AO__c11_atomic_store:
2851   case AtomicExpr::AO__opencl_atomic_store:
2852   case AtomicExpr::AO__atomic_store:
2853   case AtomicExpr::AO__atomic_store_n:
2854     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2855            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2856            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2857 
2858   default:
2859     return true;
2860   }
2861 }
2862 
2863 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2864                                          AtomicExpr::AtomicOp Op) {
2865   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2866   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2867 
2868   // All the non-OpenCL operations take one of the following forms.
2869   // The OpenCL operations take the __c11 forms with one extra argument for
2870   // synchronization scope.
2871   enum {
2872     // C    __c11_atomic_init(A *, C)
2873     Init,
2874     // C    __c11_atomic_load(A *, int)
2875     Load,
2876     // void __atomic_load(A *, CP, int)
2877     LoadCopy,
2878     // void __atomic_store(A *, CP, int)
2879     Copy,
2880     // C    __c11_atomic_add(A *, M, int)
2881     Arithmetic,
2882     // C    __atomic_exchange_n(A *, CP, int)
2883     Xchg,
2884     // void __atomic_exchange(A *, C *, CP, int)
2885     GNUXchg,
2886     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2887     C11CmpXchg,
2888     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2889     GNUCmpXchg
2890   } Form = Init;
2891   const unsigned NumForm = GNUCmpXchg + 1;
2892   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2893   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2894   // where:
2895   //   C is an appropriate type,
2896   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2897   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2898   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2899   //   the int parameters are for orderings.
2900 
2901   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2902       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2903       "need to update code for modified forms");
2904   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2905                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2906                         AtomicExpr::AO__atomic_load,
2907                 "need to update code for modified C11 atomics");
2908   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2909                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2910   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2911                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2912                IsOpenCL;
2913   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2914              Op == AtomicExpr::AO__atomic_store_n ||
2915              Op == AtomicExpr::AO__atomic_exchange_n ||
2916              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2917   bool IsAddSub = false;
2918 
2919   switch (Op) {
2920   case AtomicExpr::AO__c11_atomic_init:
2921   case AtomicExpr::AO__opencl_atomic_init:
2922     Form = Init;
2923     break;
2924 
2925   case AtomicExpr::AO__c11_atomic_load:
2926   case AtomicExpr::AO__opencl_atomic_load:
2927   case AtomicExpr::AO__atomic_load_n:
2928     Form = Load;
2929     break;
2930 
2931   case AtomicExpr::AO__atomic_load:
2932     Form = LoadCopy;
2933     break;
2934 
2935   case AtomicExpr::AO__c11_atomic_store:
2936   case AtomicExpr::AO__opencl_atomic_store:
2937   case AtomicExpr::AO__atomic_store:
2938   case AtomicExpr::AO__atomic_store_n:
2939     Form = Copy;
2940     break;
2941 
2942   case AtomicExpr::AO__c11_atomic_fetch_add:
2943   case AtomicExpr::AO__c11_atomic_fetch_sub:
2944   case AtomicExpr::AO__opencl_atomic_fetch_add:
2945   case AtomicExpr::AO__opencl_atomic_fetch_sub:
2946   case AtomicExpr::AO__opencl_atomic_fetch_min:
2947   case AtomicExpr::AO__opencl_atomic_fetch_max:
2948   case AtomicExpr::AO__atomic_fetch_add:
2949   case AtomicExpr::AO__atomic_fetch_sub:
2950   case AtomicExpr::AO__atomic_add_fetch:
2951   case AtomicExpr::AO__atomic_sub_fetch:
2952     IsAddSub = true;
2953     // Fall through.
2954   case AtomicExpr::AO__c11_atomic_fetch_and:
2955   case AtomicExpr::AO__c11_atomic_fetch_or:
2956   case AtomicExpr::AO__c11_atomic_fetch_xor:
2957   case AtomicExpr::AO__opencl_atomic_fetch_and:
2958   case AtomicExpr::AO__opencl_atomic_fetch_or:
2959   case AtomicExpr::AO__opencl_atomic_fetch_xor:
2960   case AtomicExpr::AO__atomic_fetch_and:
2961   case AtomicExpr::AO__atomic_fetch_or:
2962   case AtomicExpr::AO__atomic_fetch_xor:
2963   case AtomicExpr::AO__atomic_fetch_nand:
2964   case AtomicExpr::AO__atomic_and_fetch:
2965   case AtomicExpr::AO__atomic_or_fetch:
2966   case AtomicExpr::AO__atomic_xor_fetch:
2967   case AtomicExpr::AO__atomic_nand_fetch:
2968     Form = Arithmetic;
2969     break;
2970 
2971   case AtomicExpr::AO__c11_atomic_exchange:
2972   case AtomicExpr::AO__opencl_atomic_exchange:
2973   case AtomicExpr::AO__atomic_exchange_n:
2974     Form = Xchg;
2975     break;
2976 
2977   case AtomicExpr::AO__atomic_exchange:
2978     Form = GNUXchg;
2979     break;
2980 
2981   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2982   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2983   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
2984   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
2985     Form = C11CmpXchg;
2986     break;
2987 
2988   case AtomicExpr::AO__atomic_compare_exchange:
2989   case AtomicExpr::AO__atomic_compare_exchange_n:
2990     Form = GNUCmpXchg;
2991     break;
2992   }
2993 
2994   unsigned AdjustedNumArgs = NumArgs[Form];
2995   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
2996     ++AdjustedNumArgs;
2997   // Check we have the right number of arguments.
2998   if (TheCall->getNumArgs() < AdjustedNumArgs) {
2999     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3000       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3001       << TheCall->getCallee()->getSourceRange();
3002     return ExprError();
3003   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3004     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3005          diag::err_typecheck_call_too_many_args)
3006       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3007       << TheCall->getCallee()->getSourceRange();
3008     return ExprError();
3009   }
3010 
3011   // Inspect the first argument of the atomic operation.
3012   Expr *Ptr = TheCall->getArg(0);
3013   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3014   if (ConvertedPtr.isInvalid())
3015     return ExprError();
3016 
3017   Ptr = ConvertedPtr.get();
3018   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3019   if (!pointerType) {
3020     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3021       << Ptr->getType() << Ptr->getSourceRange();
3022     return ExprError();
3023   }
3024 
3025   // For a __c11 builtin, this should be a pointer to an _Atomic type.
3026   QualType AtomTy = pointerType->getPointeeType(); // 'A'
3027   QualType ValType = AtomTy; // 'C'
3028   if (IsC11) {
3029     if (!AtomTy->isAtomicType()) {
3030       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3031         << Ptr->getType() << Ptr->getSourceRange();
3032       return ExprError();
3033     }
3034     if (AtomTy.isConstQualified() ||
3035         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3036       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3037           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3038           << Ptr->getSourceRange();
3039       return ExprError();
3040     }
3041     ValType = AtomTy->getAs<AtomicType>()->getValueType();
3042   } else if (Form != Load && Form != LoadCopy) {
3043     if (ValType.isConstQualified()) {
3044       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3045         << Ptr->getType() << Ptr->getSourceRange();
3046       return ExprError();
3047     }
3048   }
3049 
3050   // For an arithmetic operation, the implied arithmetic must be well-formed.
3051   if (Form == Arithmetic) {
3052     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3053     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3054       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3055         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3056       return ExprError();
3057     }
3058     if (!IsAddSub && !ValType->isIntegerType()) {
3059       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3060         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3061       return ExprError();
3062     }
3063     if (IsC11 && ValType->isPointerType() &&
3064         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3065                             diag::err_incomplete_type)) {
3066       return ExprError();
3067     }
3068   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3069     // For __atomic_*_n operations, the value type must be a scalar integral or
3070     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3071     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3072       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3073     return ExprError();
3074   }
3075 
3076   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3077       !AtomTy->isScalarType()) {
3078     // For GNU atomics, require a trivially-copyable type. This is not part of
3079     // the GNU atomics specification, but we enforce it for sanity.
3080     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3081       << Ptr->getType() << Ptr->getSourceRange();
3082     return ExprError();
3083   }
3084 
3085   switch (ValType.getObjCLifetime()) {
3086   case Qualifiers::OCL_None:
3087   case Qualifiers::OCL_ExplicitNone:
3088     // okay
3089     break;
3090 
3091   case Qualifiers::OCL_Weak:
3092   case Qualifiers::OCL_Strong:
3093   case Qualifiers::OCL_Autoreleasing:
3094     // FIXME: Can this happen? By this point, ValType should be known
3095     // to be trivially copyable.
3096     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3097       << ValType << Ptr->getSourceRange();
3098     return ExprError();
3099   }
3100 
3101   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
3102   // volatile-ness of the pointee-type inject itself into the result or the
3103   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3104   ValType.removeLocalVolatile();
3105   ValType.removeLocalConst();
3106   QualType ResultType = ValType;
3107   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3108       Form == Init)
3109     ResultType = Context.VoidTy;
3110   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3111     ResultType = Context.BoolTy;
3112 
3113   // The type of a parameter passed 'by value'. In the GNU atomics, such
3114   // arguments are actually passed as pointers.
3115   QualType ByValType = ValType; // 'CP'
3116   if (!IsC11 && !IsN)
3117     ByValType = Ptr->getType();
3118 
3119   // The first argument --- the pointer --- has a fixed type; we
3120   // deduce the types of the rest of the arguments accordingly.  Walk
3121   // the remaining arguments, converting them to the deduced value type.
3122   for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3123     QualType Ty;
3124     if (i < NumVals[Form] + 1) {
3125       switch (i) {
3126       case 1:
3127         // The second argument is the non-atomic operand. For arithmetic, this
3128         // is always passed by value, and for a compare_exchange it is always
3129         // passed by address. For the rest, GNU uses by-address and C11 uses
3130         // by-value.
3131         assert(Form != Load);
3132         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3133           Ty = ValType;
3134         else if (Form == Copy || Form == Xchg)
3135           Ty = ByValType;
3136         else if (Form == Arithmetic)
3137           Ty = Context.getPointerDiffType();
3138         else {
3139           Expr *ValArg = TheCall->getArg(i);
3140           // Treat this argument as _Nonnull as we want to show a warning if
3141           // NULL is passed into it.
3142           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3143           LangAS AS = LangAS::Default;
3144           // Keep address space of non-atomic pointer type.
3145           if (const PointerType *PtrTy =
3146                   ValArg->getType()->getAs<PointerType>()) {
3147             AS = PtrTy->getPointeeType().getAddressSpace();
3148           }
3149           Ty = Context.getPointerType(
3150               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3151         }
3152         break;
3153       case 2:
3154         // The third argument to compare_exchange / GNU exchange is a
3155         // (pointer to a) desired value.
3156         Ty = ByValType;
3157         break;
3158       case 3:
3159         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3160         Ty = Context.BoolTy;
3161         break;
3162       }
3163     } else {
3164       // The order(s) and scope are always converted to int.
3165       Ty = Context.IntTy;
3166     }
3167 
3168     InitializedEntity Entity =
3169         InitializedEntity::InitializeParameter(Context, Ty, false);
3170     ExprResult Arg = TheCall->getArg(i);
3171     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3172     if (Arg.isInvalid())
3173       return true;
3174     TheCall->setArg(i, Arg.get());
3175   }
3176 
3177   // Permute the arguments into a 'consistent' order.
3178   SmallVector<Expr*, 5> SubExprs;
3179   SubExprs.push_back(Ptr);
3180   switch (Form) {
3181   case Init:
3182     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3183     SubExprs.push_back(TheCall->getArg(1)); // Val1
3184     break;
3185   case Load:
3186     SubExprs.push_back(TheCall->getArg(1)); // Order
3187     break;
3188   case LoadCopy:
3189   case Copy:
3190   case Arithmetic:
3191   case Xchg:
3192     SubExprs.push_back(TheCall->getArg(2)); // Order
3193     SubExprs.push_back(TheCall->getArg(1)); // Val1
3194     break;
3195   case GNUXchg:
3196     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3197     SubExprs.push_back(TheCall->getArg(3)); // Order
3198     SubExprs.push_back(TheCall->getArg(1)); // Val1
3199     SubExprs.push_back(TheCall->getArg(2)); // Val2
3200     break;
3201   case C11CmpXchg:
3202     SubExprs.push_back(TheCall->getArg(3)); // Order
3203     SubExprs.push_back(TheCall->getArg(1)); // Val1
3204     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3205     SubExprs.push_back(TheCall->getArg(2)); // Val2
3206     break;
3207   case GNUCmpXchg:
3208     SubExprs.push_back(TheCall->getArg(4)); // Order
3209     SubExprs.push_back(TheCall->getArg(1)); // Val1
3210     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3211     SubExprs.push_back(TheCall->getArg(2)); // Val2
3212     SubExprs.push_back(TheCall->getArg(3)); // Weak
3213     break;
3214   }
3215 
3216   if (SubExprs.size() >= 2 && Form != Init) {
3217     llvm::APSInt Result(32);
3218     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3219         !isValidOrderingForOp(Result.getSExtValue(), Op))
3220       Diag(SubExprs[1]->getLocStart(),
3221            diag::warn_atomic_op_has_invalid_memory_order)
3222           << SubExprs[1]->getSourceRange();
3223   }
3224 
3225   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3226     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3227     llvm::APSInt Result(32);
3228     if (Scope->isIntegerConstantExpr(Result, Context) &&
3229         !ScopeModel->isValid(Result.getZExtValue())) {
3230       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3231           << Scope->getSourceRange();
3232     }
3233     SubExprs.push_back(Scope);
3234   }
3235 
3236   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3237                                             SubExprs, ResultType, Op,
3238                                             TheCall->getRParenLoc());
3239 
3240   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3241        Op == AtomicExpr::AO__c11_atomic_store ||
3242        Op == AtomicExpr::AO__opencl_atomic_load ||
3243        Op == AtomicExpr::AO__opencl_atomic_store ) &&
3244       Context.AtomicUsesUnsupportedLibcall(AE))
3245     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3246         << ((Op == AtomicExpr::AO__c11_atomic_load ||
3247             Op == AtomicExpr::AO__opencl_atomic_load)
3248                 ? 0 : 1);
3249 
3250   return AE;
3251 }
3252 
3253 /// checkBuiltinArgument - Given a call to a builtin function, perform
3254 /// normal type-checking on the given argument, updating the call in
3255 /// place.  This is useful when a builtin function requires custom
3256 /// type-checking for some of its arguments but not necessarily all of
3257 /// them.
3258 ///
3259 /// Returns true on error.
3260 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3261   FunctionDecl *Fn = E->getDirectCallee();
3262   assert(Fn && "builtin call without direct callee!");
3263 
3264   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3265   InitializedEntity Entity =
3266     InitializedEntity::InitializeParameter(S.Context, Param);
3267 
3268   ExprResult Arg = E->getArg(0);
3269   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3270   if (Arg.isInvalid())
3271     return true;
3272 
3273   E->setArg(ArgIndex, Arg.get());
3274   return false;
3275 }
3276 
3277 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3278 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3279 /// type of its first argument.  The main ActOnCallExpr routines have already
3280 /// promoted the types of arguments because all of these calls are prototyped as
3281 /// void(...).
3282 ///
3283 /// This function goes through and does final semantic checking for these
3284 /// builtins,
3285 ExprResult
3286 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3287   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3288   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3289   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3290 
3291   // Ensure that we have at least one argument to do type inference from.
3292   if (TheCall->getNumArgs() < 1) {
3293     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3294       << 0 << 1 << TheCall->getNumArgs()
3295       << TheCall->getCallee()->getSourceRange();
3296     return ExprError();
3297   }
3298 
3299   // Inspect the first argument of the atomic builtin.  This should always be
3300   // a pointer type, whose element is an integral scalar or pointer type.
3301   // Because it is a pointer type, we don't have to worry about any implicit
3302   // casts here.
3303   // FIXME: We don't allow floating point scalars as input.
3304   Expr *FirstArg = TheCall->getArg(0);
3305   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3306   if (FirstArgResult.isInvalid())
3307     return ExprError();
3308   FirstArg = FirstArgResult.get();
3309   TheCall->setArg(0, FirstArg);
3310 
3311   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3312   if (!pointerType) {
3313     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3314       << FirstArg->getType() << FirstArg->getSourceRange();
3315     return ExprError();
3316   }
3317 
3318   QualType ValType = pointerType->getPointeeType();
3319   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3320       !ValType->isBlockPointerType()) {
3321     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3322       << FirstArg->getType() << FirstArg->getSourceRange();
3323     return ExprError();
3324   }
3325 
3326   switch (ValType.getObjCLifetime()) {
3327   case Qualifiers::OCL_None:
3328   case Qualifiers::OCL_ExplicitNone:
3329     // okay
3330     break;
3331 
3332   case Qualifiers::OCL_Weak:
3333   case Qualifiers::OCL_Strong:
3334   case Qualifiers::OCL_Autoreleasing:
3335     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3336       << ValType << FirstArg->getSourceRange();
3337     return ExprError();
3338   }
3339 
3340   // Strip any qualifiers off ValType.
3341   ValType = ValType.getUnqualifiedType();
3342 
3343   // The majority of builtins return a value, but a few have special return
3344   // types, so allow them to override appropriately below.
3345   QualType ResultType = ValType;
3346 
3347   // We need to figure out which concrete builtin this maps onto.  For example,
3348   // __sync_fetch_and_add with a 2 byte object turns into
3349   // __sync_fetch_and_add_2.
3350 #define BUILTIN_ROW(x) \
3351   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3352     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3353 
3354   static const unsigned BuiltinIndices[][5] = {
3355     BUILTIN_ROW(__sync_fetch_and_add),
3356     BUILTIN_ROW(__sync_fetch_and_sub),
3357     BUILTIN_ROW(__sync_fetch_and_or),
3358     BUILTIN_ROW(__sync_fetch_and_and),
3359     BUILTIN_ROW(__sync_fetch_and_xor),
3360     BUILTIN_ROW(__sync_fetch_and_nand),
3361 
3362     BUILTIN_ROW(__sync_add_and_fetch),
3363     BUILTIN_ROW(__sync_sub_and_fetch),
3364     BUILTIN_ROW(__sync_and_and_fetch),
3365     BUILTIN_ROW(__sync_or_and_fetch),
3366     BUILTIN_ROW(__sync_xor_and_fetch),
3367     BUILTIN_ROW(__sync_nand_and_fetch),
3368 
3369     BUILTIN_ROW(__sync_val_compare_and_swap),
3370     BUILTIN_ROW(__sync_bool_compare_and_swap),
3371     BUILTIN_ROW(__sync_lock_test_and_set),
3372     BUILTIN_ROW(__sync_lock_release),
3373     BUILTIN_ROW(__sync_swap)
3374   };
3375 #undef BUILTIN_ROW
3376 
3377   // Determine the index of the size.
3378   unsigned SizeIndex;
3379   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3380   case 1: SizeIndex = 0; break;
3381   case 2: SizeIndex = 1; break;
3382   case 4: SizeIndex = 2; break;
3383   case 8: SizeIndex = 3; break;
3384   case 16: SizeIndex = 4; break;
3385   default:
3386     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3387       << FirstArg->getType() << FirstArg->getSourceRange();
3388     return ExprError();
3389   }
3390 
3391   // Each of these builtins has one pointer argument, followed by some number of
3392   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3393   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3394   // as the number of fixed args.
3395   unsigned BuiltinID = FDecl->getBuiltinID();
3396   unsigned BuiltinIndex, NumFixed = 1;
3397   bool WarnAboutSemanticsChange = false;
3398   switch (BuiltinID) {
3399   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3400   case Builtin::BI__sync_fetch_and_add:
3401   case Builtin::BI__sync_fetch_and_add_1:
3402   case Builtin::BI__sync_fetch_and_add_2:
3403   case Builtin::BI__sync_fetch_and_add_4:
3404   case Builtin::BI__sync_fetch_and_add_8:
3405   case Builtin::BI__sync_fetch_and_add_16:
3406     BuiltinIndex = 0;
3407     break;
3408 
3409   case Builtin::BI__sync_fetch_and_sub:
3410   case Builtin::BI__sync_fetch_and_sub_1:
3411   case Builtin::BI__sync_fetch_and_sub_2:
3412   case Builtin::BI__sync_fetch_and_sub_4:
3413   case Builtin::BI__sync_fetch_and_sub_8:
3414   case Builtin::BI__sync_fetch_and_sub_16:
3415     BuiltinIndex = 1;
3416     break;
3417 
3418   case Builtin::BI__sync_fetch_and_or:
3419   case Builtin::BI__sync_fetch_and_or_1:
3420   case Builtin::BI__sync_fetch_and_or_2:
3421   case Builtin::BI__sync_fetch_and_or_4:
3422   case Builtin::BI__sync_fetch_and_or_8:
3423   case Builtin::BI__sync_fetch_and_or_16:
3424     BuiltinIndex = 2;
3425     break;
3426 
3427   case Builtin::BI__sync_fetch_and_and:
3428   case Builtin::BI__sync_fetch_and_and_1:
3429   case Builtin::BI__sync_fetch_and_and_2:
3430   case Builtin::BI__sync_fetch_and_and_4:
3431   case Builtin::BI__sync_fetch_and_and_8:
3432   case Builtin::BI__sync_fetch_and_and_16:
3433     BuiltinIndex = 3;
3434     break;
3435 
3436   case Builtin::BI__sync_fetch_and_xor:
3437   case Builtin::BI__sync_fetch_and_xor_1:
3438   case Builtin::BI__sync_fetch_and_xor_2:
3439   case Builtin::BI__sync_fetch_and_xor_4:
3440   case Builtin::BI__sync_fetch_and_xor_8:
3441   case Builtin::BI__sync_fetch_and_xor_16:
3442     BuiltinIndex = 4;
3443     break;
3444 
3445   case Builtin::BI__sync_fetch_and_nand:
3446   case Builtin::BI__sync_fetch_and_nand_1:
3447   case Builtin::BI__sync_fetch_and_nand_2:
3448   case Builtin::BI__sync_fetch_and_nand_4:
3449   case Builtin::BI__sync_fetch_and_nand_8:
3450   case Builtin::BI__sync_fetch_and_nand_16:
3451     BuiltinIndex = 5;
3452     WarnAboutSemanticsChange = true;
3453     break;
3454 
3455   case Builtin::BI__sync_add_and_fetch:
3456   case Builtin::BI__sync_add_and_fetch_1:
3457   case Builtin::BI__sync_add_and_fetch_2:
3458   case Builtin::BI__sync_add_and_fetch_4:
3459   case Builtin::BI__sync_add_and_fetch_8:
3460   case Builtin::BI__sync_add_and_fetch_16:
3461     BuiltinIndex = 6;
3462     break;
3463 
3464   case Builtin::BI__sync_sub_and_fetch:
3465   case Builtin::BI__sync_sub_and_fetch_1:
3466   case Builtin::BI__sync_sub_and_fetch_2:
3467   case Builtin::BI__sync_sub_and_fetch_4:
3468   case Builtin::BI__sync_sub_and_fetch_8:
3469   case Builtin::BI__sync_sub_and_fetch_16:
3470     BuiltinIndex = 7;
3471     break;
3472 
3473   case Builtin::BI__sync_and_and_fetch:
3474   case Builtin::BI__sync_and_and_fetch_1:
3475   case Builtin::BI__sync_and_and_fetch_2:
3476   case Builtin::BI__sync_and_and_fetch_4:
3477   case Builtin::BI__sync_and_and_fetch_8:
3478   case Builtin::BI__sync_and_and_fetch_16:
3479     BuiltinIndex = 8;
3480     break;
3481 
3482   case Builtin::BI__sync_or_and_fetch:
3483   case Builtin::BI__sync_or_and_fetch_1:
3484   case Builtin::BI__sync_or_and_fetch_2:
3485   case Builtin::BI__sync_or_and_fetch_4:
3486   case Builtin::BI__sync_or_and_fetch_8:
3487   case Builtin::BI__sync_or_and_fetch_16:
3488     BuiltinIndex = 9;
3489     break;
3490 
3491   case Builtin::BI__sync_xor_and_fetch:
3492   case Builtin::BI__sync_xor_and_fetch_1:
3493   case Builtin::BI__sync_xor_and_fetch_2:
3494   case Builtin::BI__sync_xor_and_fetch_4:
3495   case Builtin::BI__sync_xor_and_fetch_8:
3496   case Builtin::BI__sync_xor_and_fetch_16:
3497     BuiltinIndex = 10;
3498     break;
3499 
3500   case Builtin::BI__sync_nand_and_fetch:
3501   case Builtin::BI__sync_nand_and_fetch_1:
3502   case Builtin::BI__sync_nand_and_fetch_2:
3503   case Builtin::BI__sync_nand_and_fetch_4:
3504   case Builtin::BI__sync_nand_and_fetch_8:
3505   case Builtin::BI__sync_nand_and_fetch_16:
3506     BuiltinIndex = 11;
3507     WarnAboutSemanticsChange = true;
3508     break;
3509 
3510   case Builtin::BI__sync_val_compare_and_swap:
3511   case Builtin::BI__sync_val_compare_and_swap_1:
3512   case Builtin::BI__sync_val_compare_and_swap_2:
3513   case Builtin::BI__sync_val_compare_and_swap_4:
3514   case Builtin::BI__sync_val_compare_and_swap_8:
3515   case Builtin::BI__sync_val_compare_and_swap_16:
3516     BuiltinIndex = 12;
3517     NumFixed = 2;
3518     break;
3519 
3520   case Builtin::BI__sync_bool_compare_and_swap:
3521   case Builtin::BI__sync_bool_compare_and_swap_1:
3522   case Builtin::BI__sync_bool_compare_and_swap_2:
3523   case Builtin::BI__sync_bool_compare_and_swap_4:
3524   case Builtin::BI__sync_bool_compare_and_swap_8:
3525   case Builtin::BI__sync_bool_compare_and_swap_16:
3526     BuiltinIndex = 13;
3527     NumFixed = 2;
3528     ResultType = Context.BoolTy;
3529     break;
3530 
3531   case Builtin::BI__sync_lock_test_and_set:
3532   case Builtin::BI__sync_lock_test_and_set_1:
3533   case Builtin::BI__sync_lock_test_and_set_2:
3534   case Builtin::BI__sync_lock_test_and_set_4:
3535   case Builtin::BI__sync_lock_test_and_set_8:
3536   case Builtin::BI__sync_lock_test_and_set_16:
3537     BuiltinIndex = 14;
3538     break;
3539 
3540   case Builtin::BI__sync_lock_release:
3541   case Builtin::BI__sync_lock_release_1:
3542   case Builtin::BI__sync_lock_release_2:
3543   case Builtin::BI__sync_lock_release_4:
3544   case Builtin::BI__sync_lock_release_8:
3545   case Builtin::BI__sync_lock_release_16:
3546     BuiltinIndex = 15;
3547     NumFixed = 0;
3548     ResultType = Context.VoidTy;
3549     break;
3550 
3551   case Builtin::BI__sync_swap:
3552   case Builtin::BI__sync_swap_1:
3553   case Builtin::BI__sync_swap_2:
3554   case Builtin::BI__sync_swap_4:
3555   case Builtin::BI__sync_swap_8:
3556   case Builtin::BI__sync_swap_16:
3557     BuiltinIndex = 16;
3558     break;
3559   }
3560 
3561   // Now that we know how many fixed arguments we expect, first check that we
3562   // have at least that many.
3563   if (TheCall->getNumArgs() < 1+NumFixed) {
3564     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3565       << 0 << 1+NumFixed << TheCall->getNumArgs()
3566       << TheCall->getCallee()->getSourceRange();
3567     return ExprError();
3568   }
3569 
3570   if (WarnAboutSemanticsChange) {
3571     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3572       << TheCall->getCallee()->getSourceRange();
3573   }
3574 
3575   // Get the decl for the concrete builtin from this, we can tell what the
3576   // concrete integer type we should convert to is.
3577   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3578   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3579   FunctionDecl *NewBuiltinDecl;
3580   if (NewBuiltinID == BuiltinID)
3581     NewBuiltinDecl = FDecl;
3582   else {
3583     // Perform builtin lookup to avoid redeclaring it.
3584     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3585     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3586     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3587     assert(Res.getFoundDecl());
3588     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3589     if (!NewBuiltinDecl)
3590       return ExprError();
3591   }
3592 
3593   // The first argument --- the pointer --- has a fixed type; we
3594   // deduce the types of the rest of the arguments accordingly.  Walk
3595   // the remaining arguments, converting them to the deduced value type.
3596   for (unsigned i = 0; i != NumFixed; ++i) {
3597     ExprResult Arg = TheCall->getArg(i+1);
3598 
3599     // GCC does an implicit conversion to the pointer or integer ValType.  This
3600     // can fail in some cases (1i -> int**), check for this error case now.
3601     // Initialize the argument.
3602     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3603                                                    ValType, /*consume*/ false);
3604     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3605     if (Arg.isInvalid())
3606       return ExprError();
3607 
3608     // Okay, we have something that *can* be converted to the right type.  Check
3609     // to see if there is a potentially weird extension going on here.  This can
3610     // happen when you do an atomic operation on something like an char* and
3611     // pass in 42.  The 42 gets converted to char.  This is even more strange
3612     // for things like 45.123 -> char, etc.
3613     // FIXME: Do this check.
3614     TheCall->setArg(i+1, Arg.get());
3615   }
3616 
3617   ASTContext& Context = this->getASTContext();
3618 
3619   // Create a new DeclRefExpr to refer to the new decl.
3620   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3621       Context,
3622       DRE->getQualifierLoc(),
3623       SourceLocation(),
3624       NewBuiltinDecl,
3625       /*enclosing*/ false,
3626       DRE->getLocation(),
3627       Context.BuiltinFnTy,
3628       DRE->getValueKind());
3629 
3630   // Set the callee in the CallExpr.
3631   // FIXME: This loses syntactic information.
3632   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3633   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3634                                               CK_BuiltinFnToFnPtr);
3635   TheCall->setCallee(PromotedCall.get());
3636 
3637   // Change the result type of the call to match the original value type. This
3638   // is arbitrary, but the codegen for these builtins ins design to handle it
3639   // gracefully.
3640   TheCall->setType(ResultType);
3641 
3642   return TheCallResult;
3643 }
3644 
3645 /// SemaBuiltinNontemporalOverloaded - We have a call to
3646 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3647 /// overloaded function based on the pointer type of its last argument.
3648 ///
3649 /// This function goes through and does final semantic checking for these
3650 /// builtins.
3651 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3652   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3653   DeclRefExpr *DRE =
3654       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3655   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3656   unsigned BuiltinID = FDecl->getBuiltinID();
3657   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3658           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3659          "Unexpected nontemporal load/store builtin!");
3660   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3661   unsigned numArgs = isStore ? 2 : 1;
3662 
3663   // Ensure that we have the proper number of arguments.
3664   if (checkArgCount(*this, TheCall, numArgs))
3665     return ExprError();
3666 
3667   // Inspect the last argument of the nontemporal builtin.  This should always
3668   // be a pointer type, from which we imply the type of the memory access.
3669   // Because it is a pointer type, we don't have to worry about any implicit
3670   // casts here.
3671   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3672   ExprResult PointerArgResult =
3673       DefaultFunctionArrayLvalueConversion(PointerArg);
3674 
3675   if (PointerArgResult.isInvalid())
3676     return ExprError();
3677   PointerArg = PointerArgResult.get();
3678   TheCall->setArg(numArgs - 1, PointerArg);
3679 
3680   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3681   if (!pointerType) {
3682     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3683         << PointerArg->getType() << PointerArg->getSourceRange();
3684     return ExprError();
3685   }
3686 
3687   QualType ValType = pointerType->getPointeeType();
3688 
3689   // Strip any qualifiers off ValType.
3690   ValType = ValType.getUnqualifiedType();
3691   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3692       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3693       !ValType->isVectorType()) {
3694     Diag(DRE->getLocStart(),
3695          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3696         << PointerArg->getType() << PointerArg->getSourceRange();
3697     return ExprError();
3698   }
3699 
3700   if (!isStore) {
3701     TheCall->setType(ValType);
3702     return TheCallResult;
3703   }
3704 
3705   ExprResult ValArg = TheCall->getArg(0);
3706   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3707       Context, ValType, /*consume*/ false);
3708   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3709   if (ValArg.isInvalid())
3710     return ExprError();
3711 
3712   TheCall->setArg(0, ValArg.get());
3713   TheCall->setType(Context.VoidTy);
3714   return TheCallResult;
3715 }
3716 
3717 /// CheckObjCString - Checks that the argument to the builtin
3718 /// CFString constructor is correct
3719 /// Note: It might also make sense to do the UTF-16 conversion here (would
3720 /// simplify the backend).
3721 bool Sema::CheckObjCString(Expr *Arg) {
3722   Arg = Arg->IgnoreParenCasts();
3723   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3724 
3725   if (!Literal || !Literal->isAscii()) {
3726     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3727       << Arg->getSourceRange();
3728     return true;
3729   }
3730 
3731   if (Literal->containsNonAsciiOrNull()) {
3732     StringRef String = Literal->getString();
3733     unsigned NumBytes = String.size();
3734     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3735     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3736     llvm::UTF16 *ToPtr = &ToBuf[0];
3737 
3738     llvm::ConversionResult Result =
3739         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3740                                  ToPtr + NumBytes, llvm::strictConversion);
3741     // Check for conversion failure.
3742     if (Result != llvm::conversionOK)
3743       Diag(Arg->getLocStart(),
3744            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3745   }
3746   return false;
3747 }
3748 
3749 /// CheckObjCString - Checks that the format string argument to the os_log()
3750 /// and os_trace() functions is correct, and converts it to const char *.
3751 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3752   Arg = Arg->IgnoreParenCasts();
3753   auto *Literal = dyn_cast<StringLiteral>(Arg);
3754   if (!Literal) {
3755     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3756       Literal = ObjcLiteral->getString();
3757     }
3758   }
3759 
3760   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3761     return ExprError(
3762         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3763         << Arg->getSourceRange());
3764   }
3765 
3766   ExprResult Result(Literal);
3767   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3768   InitializedEntity Entity =
3769       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3770   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3771   return Result;
3772 }
3773 
3774 /// Check that the user is calling the appropriate va_start builtin for the
3775 /// target and calling convention.
3776 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3777   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3778   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3779   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3780   bool IsWindows = TT.isOSWindows();
3781   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3782   if (IsX64 || IsAArch64) {
3783     clang::CallingConv CC = CC_C;
3784     if (const FunctionDecl *FD = S.getCurFunctionDecl())
3785       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3786     if (IsMSVAStart) {
3787       // Don't allow this in System V ABI functions.
3788       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3789         return S.Diag(Fn->getLocStart(),
3790                       diag::err_ms_va_start_used_in_sysv_function);
3791     } else {
3792       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3793       // On x64 Windows, don't allow this in System V ABI functions.
3794       // (Yes, that means there's no corresponding way to support variadic
3795       // System V ABI functions on Windows.)
3796       if ((IsWindows && CC == CC_X86_64SysV) ||
3797           (!IsWindows && CC == CC_Win64))
3798         return S.Diag(Fn->getLocStart(),
3799                       diag::err_va_start_used_in_wrong_abi_function)
3800                << !IsWindows;
3801     }
3802     return false;
3803   }
3804 
3805   if (IsMSVAStart)
3806     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3807   return false;
3808 }
3809 
3810 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3811                                              ParmVarDecl **LastParam = nullptr) {
3812   // Determine whether the current function, block, or obj-c method is variadic
3813   // and get its parameter list.
3814   bool IsVariadic = false;
3815   ArrayRef<ParmVarDecl *> Params;
3816   DeclContext *Caller = S.CurContext;
3817   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3818     IsVariadic = Block->isVariadic();
3819     Params = Block->parameters();
3820   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3821     IsVariadic = FD->isVariadic();
3822     Params = FD->parameters();
3823   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3824     IsVariadic = MD->isVariadic();
3825     // FIXME: This isn't correct for methods (results in bogus warning).
3826     Params = MD->parameters();
3827   } else if (isa<CapturedDecl>(Caller)) {
3828     // We don't support va_start in a CapturedDecl.
3829     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3830     return true;
3831   } else {
3832     // This must be some other declcontext that parses exprs.
3833     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3834     return true;
3835   }
3836 
3837   if (!IsVariadic) {
3838     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3839     return true;
3840   }
3841 
3842   if (LastParam)
3843     *LastParam = Params.empty() ? nullptr : Params.back();
3844 
3845   return false;
3846 }
3847 
3848 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3849 /// for validity.  Emit an error and return true on failure; return false
3850 /// on success.
3851 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3852   Expr *Fn = TheCall->getCallee();
3853 
3854   if (checkVAStartABI(*this, BuiltinID, Fn))
3855     return true;
3856 
3857   if (TheCall->getNumArgs() > 2) {
3858     Diag(TheCall->getArg(2)->getLocStart(),
3859          diag::err_typecheck_call_too_many_args)
3860       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3861       << Fn->getSourceRange()
3862       << SourceRange(TheCall->getArg(2)->getLocStart(),
3863                      (*(TheCall->arg_end()-1))->getLocEnd());
3864     return true;
3865   }
3866 
3867   if (TheCall->getNumArgs() < 2) {
3868     return Diag(TheCall->getLocEnd(),
3869       diag::err_typecheck_call_too_few_args_at_least)
3870       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3871   }
3872 
3873   // Type-check the first argument normally.
3874   if (checkBuiltinArgument(*this, TheCall, 0))
3875     return true;
3876 
3877   // Check that the current function is variadic, and get its last parameter.
3878   ParmVarDecl *LastParam;
3879   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3880     return true;
3881 
3882   // Verify that the second argument to the builtin is the last argument of the
3883   // current function or method.
3884   bool SecondArgIsLastNamedArgument = false;
3885   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3886 
3887   // These are valid if SecondArgIsLastNamedArgument is false after the next
3888   // block.
3889   QualType Type;
3890   SourceLocation ParamLoc;
3891   bool IsCRegister = false;
3892 
3893   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3894     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3895       SecondArgIsLastNamedArgument = PV == LastParam;
3896 
3897       Type = PV->getType();
3898       ParamLoc = PV->getLocation();
3899       IsCRegister =
3900           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3901     }
3902   }
3903 
3904   if (!SecondArgIsLastNamedArgument)
3905     Diag(TheCall->getArg(1)->getLocStart(),
3906          diag::warn_second_arg_of_va_start_not_last_named_param);
3907   else if (IsCRegister || Type->isReferenceType() ||
3908            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3909              // Promotable integers are UB, but enumerations need a bit of
3910              // extra checking to see what their promotable type actually is.
3911              if (!Type->isPromotableIntegerType())
3912                return false;
3913              if (!Type->isEnumeralType())
3914                return true;
3915              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3916              return !(ED &&
3917                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3918            }()) {
3919     unsigned Reason = 0;
3920     if (Type->isReferenceType())  Reason = 1;
3921     else if (IsCRegister)         Reason = 2;
3922     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3923     Diag(ParamLoc, diag::note_parameter_type) << Type;
3924   }
3925 
3926   TheCall->setType(Context.VoidTy);
3927   return false;
3928 }
3929 
3930 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
3931   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3932   //                 const char *named_addr);
3933 
3934   Expr *Func = Call->getCallee();
3935 
3936   if (Call->getNumArgs() < 3)
3937     return Diag(Call->getLocEnd(),
3938                 diag::err_typecheck_call_too_few_args_at_least)
3939            << 0 /*function call*/ << 3 << Call->getNumArgs();
3940 
3941   // Type-check the first argument normally.
3942   if (checkBuiltinArgument(*this, Call, 0))
3943     return true;
3944 
3945   // Check that the current function is variadic.
3946   if (checkVAStartIsInVariadicFunction(*this, Func))
3947     return true;
3948 
3949   // __va_start on Windows does not validate the parameter qualifiers
3950 
3951   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
3952   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
3953 
3954   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
3955   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
3956 
3957   const QualType &ConstCharPtrTy =
3958       Context.getPointerType(Context.CharTy.withConst());
3959   if (!Arg1Ty->isPointerType() ||
3960       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
3961     Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
3962         << Arg1->getType() << ConstCharPtrTy
3963         << 1 /* different class */
3964         << 0 /* qualifier difference */
3965         << 3 /* parameter mismatch */
3966         << 2 << Arg1->getType() << ConstCharPtrTy;
3967 
3968   const QualType SizeTy = Context.getSizeType();
3969   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
3970     Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
3971         << Arg2->getType() << SizeTy
3972         << 1 /* different class */
3973         << 0 /* qualifier difference */
3974         << 3 /* parameter mismatch */
3975         << 3 << Arg2->getType() << SizeTy;
3976 
3977   return false;
3978 }
3979 
3980 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3981 /// friends.  This is declared to take (...), so we have to check everything.
3982 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3983   if (TheCall->getNumArgs() < 2)
3984     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3985       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3986   if (TheCall->getNumArgs() > 2)
3987     return Diag(TheCall->getArg(2)->getLocStart(),
3988                 diag::err_typecheck_call_too_many_args)
3989       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3990       << SourceRange(TheCall->getArg(2)->getLocStart(),
3991                      (*(TheCall->arg_end()-1))->getLocEnd());
3992 
3993   ExprResult OrigArg0 = TheCall->getArg(0);
3994   ExprResult OrigArg1 = TheCall->getArg(1);
3995 
3996   // Do standard promotions between the two arguments, returning their common
3997   // type.
3998   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3999   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4000     return true;
4001 
4002   // Make sure any conversions are pushed back into the call; this is
4003   // type safe since unordered compare builtins are declared as "_Bool
4004   // foo(...)".
4005   TheCall->setArg(0, OrigArg0.get());
4006   TheCall->setArg(1, OrigArg1.get());
4007 
4008   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4009     return false;
4010 
4011   // If the common type isn't a real floating type, then the arguments were
4012   // invalid for this operation.
4013   if (Res.isNull() || !Res->isRealFloatingType())
4014     return Diag(OrigArg0.get()->getLocStart(),
4015                 diag::err_typecheck_call_invalid_ordered_compare)
4016       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4017       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4018 
4019   return false;
4020 }
4021 
4022 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4023 /// __builtin_isnan and friends.  This is declared to take (...), so we have
4024 /// to check everything. We expect the last argument to be a floating point
4025 /// value.
4026 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4027   if (TheCall->getNumArgs() < NumArgs)
4028     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4029       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4030   if (TheCall->getNumArgs() > NumArgs)
4031     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4032                 diag::err_typecheck_call_too_many_args)
4033       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4034       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4035                      (*(TheCall->arg_end()-1))->getLocEnd());
4036 
4037   Expr *OrigArg = TheCall->getArg(NumArgs-1);
4038 
4039   if (OrigArg->isTypeDependent())
4040     return false;
4041 
4042   // This operation requires a non-_Complex floating-point number.
4043   if (!OrigArg->getType()->isRealFloatingType())
4044     return Diag(OrigArg->getLocStart(),
4045                 diag::err_typecheck_call_invalid_unary_fp)
4046       << OrigArg->getType() << OrigArg->getSourceRange();
4047 
4048   // If this is an implicit conversion from float -> float or double, remove it.
4049   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4050     // Only remove standard FloatCasts, leaving other casts inplace
4051     if (Cast->getCastKind() == CK_FloatingCast) {
4052       Expr *CastArg = Cast->getSubExpr();
4053       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4054           assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4055                   Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4056                "promotion from float to either float or double is the only expected cast here");
4057         Cast->setSubExpr(nullptr);
4058         TheCall->setArg(NumArgs-1, CastArg);
4059       }
4060     }
4061   }
4062 
4063   return false;
4064 }
4065 
4066 // Customized Sema Checking for VSX builtins that have the following signature:
4067 // vector [...] builtinName(vector [...], vector [...], const int);
4068 // Which takes the same type of vectors (any legal vector type) for the first
4069 // two arguments and takes compile time constant for the third argument.
4070 // Example builtins are :
4071 // vector double vec_xxpermdi(vector double, vector double, int);
4072 // vector short vec_xxsldwi(vector short, vector short, int);
4073 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4074   unsigned ExpectedNumArgs = 3;
4075   if (TheCall->getNumArgs() < ExpectedNumArgs)
4076     return Diag(TheCall->getLocEnd(),
4077                 diag::err_typecheck_call_too_few_args_at_least)
4078            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
4079            << TheCall->getSourceRange();
4080 
4081   if (TheCall->getNumArgs() > ExpectedNumArgs)
4082     return Diag(TheCall->getLocEnd(),
4083                 diag::err_typecheck_call_too_many_args_at_most)
4084            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4085            << TheCall->getSourceRange();
4086 
4087   // Check the third argument is a compile time constant
4088   llvm::APSInt Value;
4089   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4090     return Diag(TheCall->getLocStart(),
4091                 diag::err_vsx_builtin_nonconstant_argument)
4092            << 3 /* argument index */ << TheCall->getDirectCallee()
4093            << SourceRange(TheCall->getArg(2)->getLocStart(),
4094                           TheCall->getArg(2)->getLocEnd());
4095 
4096   QualType Arg1Ty = TheCall->getArg(0)->getType();
4097   QualType Arg2Ty = TheCall->getArg(1)->getType();
4098 
4099   // Check the type of argument 1 and argument 2 are vectors.
4100   SourceLocation BuiltinLoc = TheCall->getLocStart();
4101   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4102       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4103     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4104            << TheCall->getDirectCallee()
4105            << SourceRange(TheCall->getArg(0)->getLocStart(),
4106                           TheCall->getArg(1)->getLocEnd());
4107   }
4108 
4109   // Check the first two arguments are the same type.
4110   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4111     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4112            << TheCall->getDirectCallee()
4113            << SourceRange(TheCall->getArg(0)->getLocStart(),
4114                           TheCall->getArg(1)->getLocEnd());
4115   }
4116 
4117   // When default clang type checking is turned off and the customized type
4118   // checking is used, the returning type of the function must be explicitly
4119   // set. Otherwise it is _Bool by default.
4120   TheCall->setType(Arg1Ty);
4121 
4122   return false;
4123 }
4124 
4125 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4126 // This is declared to take (...), so we have to check everything.
4127 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4128   if (TheCall->getNumArgs() < 2)
4129     return ExprError(Diag(TheCall->getLocEnd(),
4130                           diag::err_typecheck_call_too_few_args_at_least)
4131                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4132                      << TheCall->getSourceRange());
4133 
4134   // Determine which of the following types of shufflevector we're checking:
4135   // 1) unary, vector mask: (lhs, mask)
4136   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4137   QualType resType = TheCall->getArg(0)->getType();
4138   unsigned numElements = 0;
4139 
4140   if (!TheCall->getArg(0)->isTypeDependent() &&
4141       !TheCall->getArg(1)->isTypeDependent()) {
4142     QualType LHSType = TheCall->getArg(0)->getType();
4143     QualType RHSType = TheCall->getArg(1)->getType();
4144 
4145     if (!LHSType->isVectorType() || !RHSType->isVectorType())
4146       return ExprError(Diag(TheCall->getLocStart(),
4147                             diag::err_vec_builtin_non_vector)
4148                        << TheCall->getDirectCallee()
4149                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4150                                       TheCall->getArg(1)->getLocEnd()));
4151 
4152     numElements = LHSType->getAs<VectorType>()->getNumElements();
4153     unsigned numResElements = TheCall->getNumArgs() - 2;
4154 
4155     // Check to see if we have a call with 2 vector arguments, the unary shuffle
4156     // with mask.  If so, verify that RHS is an integer vector type with the
4157     // same number of elts as lhs.
4158     if (TheCall->getNumArgs() == 2) {
4159       if (!RHSType->hasIntegerRepresentation() ||
4160           RHSType->getAs<VectorType>()->getNumElements() != numElements)
4161         return ExprError(Diag(TheCall->getLocStart(),
4162                               diag::err_vec_builtin_incompatible_vector)
4163                          << TheCall->getDirectCallee()
4164                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4165                                         TheCall->getArg(1)->getLocEnd()));
4166     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4167       return ExprError(Diag(TheCall->getLocStart(),
4168                             diag::err_vec_builtin_incompatible_vector)
4169                        << TheCall->getDirectCallee()
4170                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4171                                       TheCall->getArg(1)->getLocEnd()));
4172     } else if (numElements != numResElements) {
4173       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4174       resType = Context.getVectorType(eltType, numResElements,
4175                                       VectorType::GenericVector);
4176     }
4177   }
4178 
4179   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4180     if (TheCall->getArg(i)->isTypeDependent() ||
4181         TheCall->getArg(i)->isValueDependent())
4182       continue;
4183 
4184     llvm::APSInt Result(32);
4185     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4186       return ExprError(Diag(TheCall->getLocStart(),
4187                             diag::err_shufflevector_nonconstant_argument)
4188                        << TheCall->getArg(i)->getSourceRange());
4189 
4190     // Allow -1 which will be translated to undef in the IR.
4191     if (Result.isSigned() && Result.isAllOnesValue())
4192       continue;
4193 
4194     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4195       return ExprError(Diag(TheCall->getLocStart(),
4196                             diag::err_shufflevector_argument_too_large)
4197                        << TheCall->getArg(i)->getSourceRange());
4198   }
4199 
4200   SmallVector<Expr*, 32> exprs;
4201 
4202   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4203     exprs.push_back(TheCall->getArg(i));
4204     TheCall->setArg(i, nullptr);
4205   }
4206 
4207   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4208                                          TheCall->getCallee()->getLocStart(),
4209                                          TheCall->getRParenLoc());
4210 }
4211 
4212 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4213 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4214                                        SourceLocation BuiltinLoc,
4215                                        SourceLocation RParenLoc) {
4216   ExprValueKind VK = VK_RValue;
4217   ExprObjectKind OK = OK_Ordinary;
4218   QualType DstTy = TInfo->getType();
4219   QualType SrcTy = E->getType();
4220 
4221   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4222     return ExprError(Diag(BuiltinLoc,
4223                           diag::err_convertvector_non_vector)
4224                      << E->getSourceRange());
4225   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4226     return ExprError(Diag(BuiltinLoc,
4227                           diag::err_convertvector_non_vector_type));
4228 
4229   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4230     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4231     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4232     if (SrcElts != DstElts)
4233       return ExprError(Diag(BuiltinLoc,
4234                             diag::err_convertvector_incompatible_vector)
4235                        << E->getSourceRange());
4236   }
4237 
4238   return new (Context)
4239       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4240 }
4241 
4242 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4243 // This is declared to take (const void*, ...) and can take two
4244 // optional constant int args.
4245 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4246   unsigned NumArgs = TheCall->getNumArgs();
4247 
4248   if (NumArgs > 3)
4249     return Diag(TheCall->getLocEnd(),
4250              diag::err_typecheck_call_too_many_args_at_most)
4251              << 0 /*function call*/ << 3 << NumArgs
4252              << TheCall->getSourceRange();
4253 
4254   // Argument 0 is checked for us and the remaining arguments must be
4255   // constant integers.
4256   for (unsigned i = 1; i != NumArgs; ++i)
4257     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4258       return true;
4259 
4260   return false;
4261 }
4262 
4263 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4264 // __assume does not evaluate its arguments, and should warn if its argument
4265 // has side effects.
4266 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4267   Expr *Arg = TheCall->getArg(0);
4268   if (Arg->isInstantiationDependent()) return false;
4269 
4270   if (Arg->HasSideEffects(Context))
4271     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4272       << Arg->getSourceRange()
4273       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4274 
4275   return false;
4276 }
4277 
4278 /// Handle __builtin_alloca_with_align. This is declared
4279 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4280 /// than 8.
4281 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4282   // The alignment must be a constant integer.
4283   Expr *Arg = TheCall->getArg(1);
4284 
4285   // We can't check the value of a dependent argument.
4286   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4287     if (const auto *UE =
4288             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4289       if (UE->getKind() == UETT_AlignOf)
4290         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4291           << Arg->getSourceRange();
4292 
4293     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4294 
4295     if (!Result.isPowerOf2())
4296       return Diag(TheCall->getLocStart(),
4297                   diag::err_alignment_not_power_of_two)
4298            << Arg->getSourceRange();
4299 
4300     if (Result < Context.getCharWidth())
4301       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4302            << (unsigned)Context.getCharWidth()
4303            << Arg->getSourceRange();
4304 
4305     if (Result > INT32_MAX)
4306       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4307            << INT32_MAX
4308            << Arg->getSourceRange();
4309   }
4310 
4311   return false;
4312 }
4313 
4314 /// Handle __builtin_assume_aligned. This is declared
4315 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4316 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4317   unsigned NumArgs = TheCall->getNumArgs();
4318 
4319   if (NumArgs > 3)
4320     return Diag(TheCall->getLocEnd(),
4321              diag::err_typecheck_call_too_many_args_at_most)
4322              << 0 /*function call*/ << 3 << NumArgs
4323              << TheCall->getSourceRange();
4324 
4325   // The alignment must be a constant integer.
4326   Expr *Arg = TheCall->getArg(1);
4327 
4328   // We can't check the value of a dependent argument.
4329   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4330     llvm::APSInt Result;
4331     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4332       return true;
4333 
4334     if (!Result.isPowerOf2())
4335       return Diag(TheCall->getLocStart(),
4336                   diag::err_alignment_not_power_of_two)
4337            << Arg->getSourceRange();
4338   }
4339 
4340   if (NumArgs > 2) {
4341     ExprResult Arg(TheCall->getArg(2));
4342     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4343       Context.getSizeType(), false);
4344     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4345     if (Arg.isInvalid()) return true;
4346     TheCall->setArg(2, Arg.get());
4347   }
4348 
4349   return false;
4350 }
4351 
4352 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4353   unsigned BuiltinID =
4354       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4355   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4356 
4357   unsigned NumArgs = TheCall->getNumArgs();
4358   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4359   if (NumArgs < NumRequiredArgs) {
4360     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4361            << 0 /* function call */ << NumRequiredArgs << NumArgs
4362            << TheCall->getSourceRange();
4363   }
4364   if (NumArgs >= NumRequiredArgs + 0x100) {
4365     return Diag(TheCall->getLocEnd(),
4366                 diag::err_typecheck_call_too_many_args_at_most)
4367            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4368            << TheCall->getSourceRange();
4369   }
4370   unsigned i = 0;
4371 
4372   // For formatting call, check buffer arg.
4373   if (!IsSizeCall) {
4374     ExprResult Arg(TheCall->getArg(i));
4375     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4376         Context, Context.VoidPtrTy, false);
4377     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4378     if (Arg.isInvalid())
4379       return true;
4380     TheCall->setArg(i, Arg.get());
4381     i++;
4382   }
4383 
4384   // Check string literal arg.
4385   unsigned FormatIdx = i;
4386   {
4387     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4388     if (Arg.isInvalid())
4389       return true;
4390     TheCall->setArg(i, Arg.get());
4391     i++;
4392   }
4393 
4394   // Make sure variadic args are scalar.
4395   unsigned FirstDataArg = i;
4396   while (i < NumArgs) {
4397     ExprResult Arg = DefaultVariadicArgumentPromotion(
4398         TheCall->getArg(i), VariadicFunction, nullptr);
4399     if (Arg.isInvalid())
4400       return true;
4401     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4402     if (ArgSize.getQuantity() >= 0x100) {
4403       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4404              << i << (int)ArgSize.getQuantity() << 0xff
4405              << TheCall->getSourceRange();
4406     }
4407     TheCall->setArg(i, Arg.get());
4408     i++;
4409   }
4410 
4411   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4412   // call to avoid duplicate diagnostics.
4413   if (!IsSizeCall) {
4414     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4415     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4416     bool Success = CheckFormatArguments(
4417         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4418         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4419         CheckedVarArgs);
4420     if (!Success)
4421       return true;
4422   }
4423 
4424   if (IsSizeCall) {
4425     TheCall->setType(Context.getSizeType());
4426   } else {
4427     TheCall->setType(Context.VoidPtrTy);
4428   }
4429   return false;
4430 }
4431 
4432 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4433 /// TheCall is a constant expression.
4434 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4435                                   llvm::APSInt &Result) {
4436   Expr *Arg = TheCall->getArg(ArgNum);
4437   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4438   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4439 
4440   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4441 
4442   if (!Arg->isIntegerConstantExpr(Result, Context))
4443     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4444                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4445 
4446   return false;
4447 }
4448 
4449 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4450 /// TheCall is a constant expression in the range [Low, High].
4451 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4452                                        int Low, int High) {
4453   llvm::APSInt Result;
4454 
4455   // We can't check the value of a dependent argument.
4456   Expr *Arg = TheCall->getArg(ArgNum);
4457   if (Arg->isTypeDependent() || Arg->isValueDependent())
4458     return false;
4459 
4460   // Check constant-ness first.
4461   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4462     return true;
4463 
4464   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4465     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4466       << Low << High << Arg->getSourceRange();
4467 
4468   return false;
4469 }
4470 
4471 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4472 /// TheCall is a constant expression is a multiple of Num..
4473 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4474                                           unsigned Num) {
4475   llvm::APSInt Result;
4476 
4477   // We can't check the value of a dependent argument.
4478   Expr *Arg = TheCall->getArg(ArgNum);
4479   if (Arg->isTypeDependent() || Arg->isValueDependent())
4480     return false;
4481 
4482   // Check constant-ness first.
4483   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4484     return true;
4485 
4486   if (Result.getSExtValue() % Num != 0)
4487     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4488       << Num << Arg->getSourceRange();
4489 
4490   return false;
4491 }
4492 
4493 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4494 /// TheCall is an ARM/AArch64 special register string literal.
4495 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4496                                     int ArgNum, unsigned ExpectedFieldNum,
4497                                     bool AllowName) {
4498   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4499                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4500                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4501                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4502                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4503                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4504   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4505                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4506                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4507                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4508                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4509                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4510   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4511 
4512   // We can't check the value of a dependent argument.
4513   Expr *Arg = TheCall->getArg(ArgNum);
4514   if (Arg->isTypeDependent() || Arg->isValueDependent())
4515     return false;
4516 
4517   // Check if the argument is a string literal.
4518   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4519     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4520            << Arg->getSourceRange();
4521 
4522   // Check the type of special register given.
4523   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4524   SmallVector<StringRef, 6> Fields;
4525   Reg.split(Fields, ":");
4526 
4527   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4528     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4529            << Arg->getSourceRange();
4530 
4531   // If the string is the name of a register then we cannot check that it is
4532   // valid here but if the string is of one the forms described in ACLE then we
4533   // can check that the supplied fields are integers and within the valid
4534   // ranges.
4535   if (Fields.size() > 1) {
4536     bool FiveFields = Fields.size() == 5;
4537 
4538     bool ValidString = true;
4539     if (IsARMBuiltin) {
4540       ValidString &= Fields[0].startswith_lower("cp") ||
4541                      Fields[0].startswith_lower("p");
4542       if (ValidString)
4543         Fields[0] =
4544           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4545 
4546       ValidString &= Fields[2].startswith_lower("c");
4547       if (ValidString)
4548         Fields[2] = Fields[2].drop_front(1);
4549 
4550       if (FiveFields) {
4551         ValidString &= Fields[3].startswith_lower("c");
4552         if (ValidString)
4553           Fields[3] = Fields[3].drop_front(1);
4554       }
4555     }
4556 
4557     SmallVector<int, 5> Ranges;
4558     if (FiveFields)
4559       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4560     else
4561       Ranges.append({15, 7, 15});
4562 
4563     for (unsigned i=0; i<Fields.size(); ++i) {
4564       int IntField;
4565       ValidString &= !Fields[i].getAsInteger(10, IntField);
4566       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4567     }
4568 
4569     if (!ValidString)
4570       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4571              << Arg->getSourceRange();
4572 
4573   } else if (IsAArch64Builtin && Fields.size() == 1) {
4574     // If the register name is one of those that appear in the condition below
4575     // and the special register builtin being used is one of the write builtins,
4576     // then we require that the argument provided for writing to the register
4577     // is an integer constant expression. This is because it will be lowered to
4578     // an MSR (immediate) instruction, so we need to know the immediate at
4579     // compile time.
4580     if (TheCall->getNumArgs() != 2)
4581       return false;
4582 
4583     std::string RegLower = Reg.lower();
4584     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4585         RegLower != "pan" && RegLower != "uao")
4586       return false;
4587 
4588     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4589   }
4590 
4591   return false;
4592 }
4593 
4594 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4595 /// This checks that the target supports __builtin_longjmp and
4596 /// that val is a constant 1.
4597 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4598   if (!Context.getTargetInfo().hasSjLjLowering())
4599     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4600              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4601 
4602   Expr *Arg = TheCall->getArg(1);
4603   llvm::APSInt Result;
4604 
4605   // TODO: This is less than ideal. Overload this to take a value.
4606   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4607     return true;
4608 
4609   if (Result != 1)
4610     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4611              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4612 
4613   return false;
4614 }
4615 
4616 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4617 /// This checks that the target supports __builtin_setjmp.
4618 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4619   if (!Context.getTargetInfo().hasSjLjLowering())
4620     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4621              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4622   return false;
4623 }
4624 
4625 namespace {
4626 class UncoveredArgHandler {
4627   enum { Unknown = -1, AllCovered = -2 };
4628   signed FirstUncoveredArg;
4629   SmallVector<const Expr *, 4> DiagnosticExprs;
4630 
4631 public:
4632   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4633 
4634   bool hasUncoveredArg() const {
4635     return (FirstUncoveredArg >= 0);
4636   }
4637 
4638   unsigned getUncoveredArg() const {
4639     assert(hasUncoveredArg() && "no uncovered argument");
4640     return FirstUncoveredArg;
4641   }
4642 
4643   void setAllCovered() {
4644     // A string has been found with all arguments covered, so clear out
4645     // the diagnostics.
4646     DiagnosticExprs.clear();
4647     FirstUncoveredArg = AllCovered;
4648   }
4649 
4650   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4651     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4652 
4653     // Don't update if a previous string covers all arguments.
4654     if (FirstUncoveredArg == AllCovered)
4655       return;
4656 
4657     // UncoveredArgHandler tracks the highest uncovered argument index
4658     // and with it all the strings that match this index.
4659     if (NewFirstUncoveredArg == FirstUncoveredArg)
4660       DiagnosticExprs.push_back(StrExpr);
4661     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4662       DiagnosticExprs.clear();
4663       DiagnosticExprs.push_back(StrExpr);
4664       FirstUncoveredArg = NewFirstUncoveredArg;
4665     }
4666   }
4667 
4668   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4669 };
4670 
4671 enum StringLiteralCheckType {
4672   SLCT_NotALiteral,
4673   SLCT_UncheckedLiteral,
4674   SLCT_CheckedLiteral
4675 };
4676 } // end anonymous namespace
4677 
4678 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4679                                      BinaryOperatorKind BinOpKind,
4680                                      bool AddendIsRight) {
4681   unsigned BitWidth = Offset.getBitWidth();
4682   unsigned AddendBitWidth = Addend.getBitWidth();
4683   // There might be negative interim results.
4684   if (Addend.isUnsigned()) {
4685     Addend = Addend.zext(++AddendBitWidth);
4686     Addend.setIsSigned(true);
4687   }
4688   // Adjust the bit width of the APSInts.
4689   if (AddendBitWidth > BitWidth) {
4690     Offset = Offset.sext(AddendBitWidth);
4691     BitWidth = AddendBitWidth;
4692   } else if (BitWidth > AddendBitWidth) {
4693     Addend = Addend.sext(BitWidth);
4694   }
4695 
4696   bool Ov = false;
4697   llvm::APSInt ResOffset = Offset;
4698   if (BinOpKind == BO_Add)
4699     ResOffset = Offset.sadd_ov(Addend, Ov);
4700   else {
4701     assert(AddendIsRight && BinOpKind == BO_Sub &&
4702            "operator must be add or sub with addend on the right");
4703     ResOffset = Offset.ssub_ov(Addend, Ov);
4704   }
4705 
4706   // We add an offset to a pointer here so we should support an offset as big as
4707   // possible.
4708   if (Ov) {
4709     assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4710     Offset = Offset.sext(2 * BitWidth);
4711     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4712     return;
4713   }
4714 
4715   Offset = ResOffset;
4716 }
4717 
4718 namespace {
4719 // This is a wrapper class around StringLiteral to support offsetted string
4720 // literals as format strings. It takes the offset into account when returning
4721 // the string and its length or the source locations to display notes correctly.
4722 class FormatStringLiteral {
4723   const StringLiteral *FExpr;
4724   int64_t Offset;
4725 
4726  public:
4727   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4728       : FExpr(fexpr), Offset(Offset) {}
4729 
4730   StringRef getString() const {
4731     return FExpr->getString().drop_front(Offset);
4732   }
4733 
4734   unsigned getByteLength() const {
4735     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4736   }
4737   unsigned getLength() const { return FExpr->getLength() - Offset; }
4738   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4739 
4740   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4741 
4742   QualType getType() const { return FExpr->getType(); }
4743 
4744   bool isAscii() const { return FExpr->isAscii(); }
4745   bool isWide() const { return FExpr->isWide(); }
4746   bool isUTF8() const { return FExpr->isUTF8(); }
4747   bool isUTF16() const { return FExpr->isUTF16(); }
4748   bool isUTF32() const { return FExpr->isUTF32(); }
4749   bool isPascal() const { return FExpr->isPascal(); }
4750 
4751   SourceLocation getLocationOfByte(
4752       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4753       const TargetInfo &Target, unsigned *StartToken = nullptr,
4754       unsigned *StartTokenByteOffset = nullptr) const {
4755     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4756                                     StartToken, StartTokenByteOffset);
4757   }
4758 
4759   SourceLocation getLocStart() const LLVM_READONLY {
4760     return FExpr->getLocStart().getLocWithOffset(Offset);
4761   }
4762   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4763 };
4764 }  // end anonymous namespace
4765 
4766 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4767                               const Expr *OrigFormatExpr,
4768                               ArrayRef<const Expr *> Args,
4769                               bool HasVAListArg, unsigned format_idx,
4770                               unsigned firstDataArg,
4771                               Sema::FormatStringType Type,
4772                               bool inFunctionCall,
4773                               Sema::VariadicCallType CallType,
4774                               llvm::SmallBitVector &CheckedVarArgs,
4775                               UncoveredArgHandler &UncoveredArg);
4776 
4777 // Determine if an expression is a string literal or constant string.
4778 // If this function returns false on the arguments to a function expecting a
4779 // format string, we will usually need to emit a warning.
4780 // True string literals are then checked by CheckFormatString.
4781 static StringLiteralCheckType
4782 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4783                       bool HasVAListArg, unsigned format_idx,
4784                       unsigned firstDataArg, Sema::FormatStringType Type,
4785                       Sema::VariadicCallType CallType, bool InFunctionCall,
4786                       llvm::SmallBitVector &CheckedVarArgs,
4787                       UncoveredArgHandler &UncoveredArg,
4788                       llvm::APSInt Offset) {
4789  tryAgain:
4790   assert(Offset.isSigned() && "invalid offset");
4791 
4792   if (E->isTypeDependent() || E->isValueDependent())
4793     return SLCT_NotALiteral;
4794 
4795   E = E->IgnoreParenCasts();
4796 
4797   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4798     // Technically -Wformat-nonliteral does not warn about this case.
4799     // The behavior of printf and friends in this case is implementation
4800     // dependent.  Ideally if the format string cannot be null then
4801     // it should have a 'nonnull' attribute in the function prototype.
4802     return SLCT_UncheckedLiteral;
4803 
4804   switch (E->getStmtClass()) {
4805   case Stmt::BinaryConditionalOperatorClass:
4806   case Stmt::ConditionalOperatorClass: {
4807     // The expression is a literal if both sub-expressions were, and it was
4808     // completely checked only if both sub-expressions were checked.
4809     const AbstractConditionalOperator *C =
4810         cast<AbstractConditionalOperator>(E);
4811 
4812     // Determine whether it is necessary to check both sub-expressions, for
4813     // example, because the condition expression is a constant that can be
4814     // evaluated at compile time.
4815     bool CheckLeft = true, CheckRight = true;
4816 
4817     bool Cond;
4818     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4819       if (Cond)
4820         CheckRight = false;
4821       else
4822         CheckLeft = false;
4823     }
4824 
4825     // We need to maintain the offsets for the right and the left hand side
4826     // separately to check if every possible indexed expression is a valid
4827     // string literal. They might have different offsets for different string
4828     // literals in the end.
4829     StringLiteralCheckType Left;
4830     if (!CheckLeft)
4831       Left = SLCT_UncheckedLiteral;
4832     else {
4833       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4834                                    HasVAListArg, format_idx, firstDataArg,
4835                                    Type, CallType, InFunctionCall,
4836                                    CheckedVarArgs, UncoveredArg, Offset);
4837       if (Left == SLCT_NotALiteral || !CheckRight) {
4838         return Left;
4839       }
4840     }
4841 
4842     StringLiteralCheckType Right =
4843         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4844                               HasVAListArg, format_idx, firstDataArg,
4845                               Type, CallType, InFunctionCall, CheckedVarArgs,
4846                               UncoveredArg, Offset);
4847 
4848     return (CheckLeft && Left < Right) ? Left : Right;
4849   }
4850 
4851   case Stmt::ImplicitCastExprClass: {
4852     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4853     goto tryAgain;
4854   }
4855 
4856   case Stmt::OpaqueValueExprClass:
4857     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4858       E = src;
4859       goto tryAgain;
4860     }
4861     return SLCT_NotALiteral;
4862 
4863   case Stmt::PredefinedExprClass:
4864     // While __func__, etc., are technically not string literals, they
4865     // cannot contain format specifiers and thus are not a security
4866     // liability.
4867     return SLCT_UncheckedLiteral;
4868 
4869   case Stmt::DeclRefExprClass: {
4870     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4871 
4872     // As an exception, do not flag errors for variables binding to
4873     // const string literals.
4874     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4875       bool isConstant = false;
4876       QualType T = DR->getType();
4877 
4878       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4879         isConstant = AT->getElementType().isConstant(S.Context);
4880       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4881         isConstant = T.isConstant(S.Context) &&
4882                      PT->getPointeeType().isConstant(S.Context);
4883       } else if (T->isObjCObjectPointerType()) {
4884         // In ObjC, there is usually no "const ObjectPointer" type,
4885         // so don't check if the pointee type is constant.
4886         isConstant = T.isConstant(S.Context);
4887       }
4888 
4889       if (isConstant) {
4890         if (const Expr *Init = VD->getAnyInitializer()) {
4891           // Look through initializers like const char c[] = { "foo" }
4892           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4893             if (InitList->isStringLiteralInit())
4894               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4895           }
4896           return checkFormatStringExpr(S, Init, Args,
4897                                        HasVAListArg, format_idx,
4898                                        firstDataArg, Type, CallType,
4899                                        /*InFunctionCall*/ false, CheckedVarArgs,
4900                                        UncoveredArg, Offset);
4901         }
4902       }
4903 
4904       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4905       // special check to see if the format string is a function parameter
4906       // of the function calling the printf function.  If the function
4907       // has an attribute indicating it is a printf-like function, then we
4908       // should suppress warnings concerning non-literals being used in a call
4909       // to a vprintf function.  For example:
4910       //
4911       // void
4912       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4913       //      va_list ap;
4914       //      va_start(ap, fmt);
4915       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4916       //      ...
4917       // }
4918       if (HasVAListArg) {
4919         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4920           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4921             int PVIndex = PV->getFunctionScopeIndex() + 1;
4922             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4923               // adjust for implicit parameter
4924               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4925                 if (MD->isInstance())
4926                   ++PVIndex;
4927               // We also check if the formats are compatible.
4928               // We can't pass a 'scanf' string to a 'printf' function.
4929               if (PVIndex == PVFormat->getFormatIdx() &&
4930                   Type == S.GetFormatStringType(PVFormat))
4931                 return SLCT_UncheckedLiteral;
4932             }
4933           }
4934         }
4935       }
4936     }
4937 
4938     return SLCT_NotALiteral;
4939   }
4940 
4941   case Stmt::CallExprClass:
4942   case Stmt::CXXMemberCallExprClass: {
4943     const CallExpr *CE = cast<CallExpr>(E);
4944     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4945       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4946         unsigned ArgIndex = FA->getFormatIdx();
4947         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4948           if (MD->isInstance())
4949             --ArgIndex;
4950         const Expr *Arg = CE->getArg(ArgIndex - 1);
4951 
4952         return checkFormatStringExpr(S, Arg, Args,
4953                                      HasVAListArg, format_idx, firstDataArg,
4954                                      Type, CallType, InFunctionCall,
4955                                      CheckedVarArgs, UncoveredArg, Offset);
4956       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4957         unsigned BuiltinID = FD->getBuiltinID();
4958         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4959             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4960           const Expr *Arg = CE->getArg(0);
4961           return checkFormatStringExpr(S, Arg, Args,
4962                                        HasVAListArg, format_idx,
4963                                        firstDataArg, Type, CallType,
4964                                        InFunctionCall, CheckedVarArgs,
4965                                        UncoveredArg, Offset);
4966         }
4967       }
4968     }
4969 
4970     return SLCT_NotALiteral;
4971   }
4972   case Stmt::ObjCMessageExprClass: {
4973     const auto *ME = cast<ObjCMessageExpr>(E);
4974     if (const auto *ND = ME->getMethodDecl()) {
4975       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4976         unsigned ArgIndex = FA->getFormatIdx();
4977         const Expr *Arg = ME->getArg(ArgIndex - 1);
4978         return checkFormatStringExpr(
4979             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4980             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4981       }
4982     }
4983 
4984     return SLCT_NotALiteral;
4985   }
4986   case Stmt::ObjCStringLiteralClass:
4987   case Stmt::StringLiteralClass: {
4988     const StringLiteral *StrE = nullptr;
4989 
4990     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4991       StrE = ObjCFExpr->getString();
4992     else
4993       StrE = cast<StringLiteral>(E);
4994 
4995     if (StrE) {
4996       if (Offset.isNegative() || Offset > StrE->getLength()) {
4997         // TODO: It would be better to have an explicit warning for out of
4998         // bounds literals.
4999         return SLCT_NotALiteral;
5000       }
5001       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5002       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5003                         firstDataArg, Type, InFunctionCall, CallType,
5004                         CheckedVarArgs, UncoveredArg);
5005       return SLCT_CheckedLiteral;
5006     }
5007 
5008     return SLCT_NotALiteral;
5009   }
5010   case Stmt::BinaryOperatorClass: {
5011     llvm::APSInt LResult;
5012     llvm::APSInt RResult;
5013 
5014     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5015 
5016     // A string literal + an int offset is still a string literal.
5017     if (BinOp->isAdditiveOp()) {
5018       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5019       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5020 
5021       if (LIsInt != RIsInt) {
5022         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5023 
5024         if (LIsInt) {
5025           if (BinOpKind == BO_Add) {
5026             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5027             E = BinOp->getRHS();
5028             goto tryAgain;
5029           }
5030         } else {
5031           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5032           E = BinOp->getLHS();
5033           goto tryAgain;
5034         }
5035       }
5036     }
5037 
5038     return SLCT_NotALiteral;
5039   }
5040   case Stmt::UnaryOperatorClass: {
5041     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5042     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5043     if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
5044       llvm::APSInt IndexResult;
5045       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5046         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5047         E = ASE->getBase();
5048         goto tryAgain;
5049       }
5050     }
5051 
5052     return SLCT_NotALiteral;
5053   }
5054 
5055   default:
5056     return SLCT_NotALiteral;
5057   }
5058 }
5059 
5060 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5061   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5062       .Case("scanf", FST_Scanf)
5063       .Cases("printf", "printf0", FST_Printf)
5064       .Cases("NSString", "CFString", FST_NSString)
5065       .Case("strftime", FST_Strftime)
5066       .Case("strfmon", FST_Strfmon)
5067       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5068       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5069       .Case("os_trace", FST_OSLog)
5070       .Case("os_log", FST_OSLog)
5071       .Default(FST_Unknown);
5072 }
5073 
5074 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5075 /// functions) for correct use of format strings.
5076 /// Returns true if a format string has been fully checked.
5077 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5078                                 ArrayRef<const Expr *> Args,
5079                                 bool IsCXXMember,
5080                                 VariadicCallType CallType,
5081                                 SourceLocation Loc, SourceRange Range,
5082                                 llvm::SmallBitVector &CheckedVarArgs) {
5083   FormatStringInfo FSI;
5084   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5085     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5086                                 FSI.FirstDataArg, GetFormatStringType(Format),
5087                                 CallType, Loc, Range, CheckedVarArgs);
5088   return false;
5089 }
5090 
5091 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5092                                 bool HasVAListArg, unsigned format_idx,
5093                                 unsigned firstDataArg, FormatStringType Type,
5094                                 VariadicCallType CallType,
5095                                 SourceLocation Loc, SourceRange Range,
5096                                 llvm::SmallBitVector &CheckedVarArgs) {
5097   // CHECK: printf/scanf-like function is called with no format string.
5098   if (format_idx >= Args.size()) {
5099     Diag(Loc, diag::warn_missing_format_string) << Range;
5100     return false;
5101   }
5102 
5103   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5104 
5105   // CHECK: format string is not a string literal.
5106   //
5107   // Dynamically generated format strings are difficult to
5108   // automatically vet at compile time.  Requiring that format strings
5109   // are string literals: (1) permits the checking of format strings by
5110   // the compiler and thereby (2) can practically remove the source of
5111   // many format string exploits.
5112 
5113   // Format string can be either ObjC string (e.g. @"%d") or
5114   // C string (e.g. "%d")
5115   // ObjC string uses the same format specifiers as C string, so we can use
5116   // the same format string checking logic for both ObjC and C strings.
5117   UncoveredArgHandler UncoveredArg;
5118   StringLiteralCheckType CT =
5119       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5120                             format_idx, firstDataArg, Type, CallType,
5121                             /*IsFunctionCall*/ true, CheckedVarArgs,
5122                             UncoveredArg,
5123                             /*no string offset*/ llvm::APSInt(64, false) = 0);
5124 
5125   // Generate a diagnostic where an uncovered argument is detected.
5126   if (UncoveredArg.hasUncoveredArg()) {
5127     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5128     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5129     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5130   }
5131 
5132   if (CT != SLCT_NotALiteral)
5133     // Literal format string found, check done!
5134     return CT == SLCT_CheckedLiteral;
5135 
5136   // Strftime is particular as it always uses a single 'time' argument,
5137   // so it is safe to pass a non-literal string.
5138   if (Type == FST_Strftime)
5139     return false;
5140 
5141   // Do not emit diag when the string param is a macro expansion and the
5142   // format is either NSString or CFString. This is a hack to prevent
5143   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5144   // which are usually used in place of NS and CF string literals.
5145   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5146   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5147     return false;
5148 
5149   // If there are no arguments specified, warn with -Wformat-security, otherwise
5150   // warn only with -Wformat-nonliteral.
5151   if (Args.size() == firstDataArg) {
5152     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5153       << OrigFormatExpr->getSourceRange();
5154     switch (Type) {
5155     default:
5156       break;
5157     case FST_Kprintf:
5158     case FST_FreeBSDKPrintf:
5159     case FST_Printf:
5160       Diag(FormatLoc, diag::note_format_security_fixit)
5161         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5162       break;
5163     case FST_NSString:
5164       Diag(FormatLoc, diag::note_format_security_fixit)
5165         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5166       break;
5167     }
5168   } else {
5169     Diag(FormatLoc, diag::warn_format_nonliteral)
5170       << OrigFormatExpr->getSourceRange();
5171   }
5172   return false;
5173 }
5174 
5175 namespace {
5176 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5177 protected:
5178   Sema &S;
5179   const FormatStringLiteral *FExpr;
5180   const Expr *OrigFormatExpr;
5181   const Sema::FormatStringType FSType;
5182   const unsigned FirstDataArg;
5183   const unsigned NumDataArgs;
5184   const char *Beg; // Start of format string.
5185   const bool HasVAListArg;
5186   ArrayRef<const Expr *> Args;
5187   unsigned FormatIdx;
5188   llvm::SmallBitVector CoveredArgs;
5189   bool usesPositionalArgs;
5190   bool atFirstArg;
5191   bool inFunctionCall;
5192   Sema::VariadicCallType CallType;
5193   llvm::SmallBitVector &CheckedVarArgs;
5194   UncoveredArgHandler &UncoveredArg;
5195 
5196 public:
5197   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5198                      const Expr *origFormatExpr,
5199                      const Sema::FormatStringType type, unsigned firstDataArg,
5200                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5201                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5202                      bool inFunctionCall, Sema::VariadicCallType callType,
5203                      llvm::SmallBitVector &CheckedVarArgs,
5204                      UncoveredArgHandler &UncoveredArg)
5205       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5206         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5207         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5208         usesPositionalArgs(false), atFirstArg(true),
5209         inFunctionCall(inFunctionCall), CallType(callType),
5210         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5211     CoveredArgs.resize(numDataArgs);
5212     CoveredArgs.reset();
5213   }
5214 
5215   void DoneProcessing();
5216 
5217   void HandleIncompleteSpecifier(const char *startSpecifier,
5218                                  unsigned specifierLen) override;
5219 
5220   void HandleInvalidLengthModifier(
5221                            const analyze_format_string::FormatSpecifier &FS,
5222                            const analyze_format_string::ConversionSpecifier &CS,
5223                            const char *startSpecifier, unsigned specifierLen,
5224                            unsigned DiagID);
5225 
5226   void HandleNonStandardLengthModifier(
5227                     const analyze_format_string::FormatSpecifier &FS,
5228                     const char *startSpecifier, unsigned specifierLen);
5229 
5230   void HandleNonStandardConversionSpecifier(
5231                     const analyze_format_string::ConversionSpecifier &CS,
5232                     const char *startSpecifier, unsigned specifierLen);
5233 
5234   void HandlePosition(const char *startPos, unsigned posLen) override;
5235 
5236   void HandleInvalidPosition(const char *startSpecifier,
5237                              unsigned specifierLen,
5238                              analyze_format_string::PositionContext p) override;
5239 
5240   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5241 
5242   void HandleNullChar(const char *nullCharacter) override;
5243 
5244   template <typename Range>
5245   static void
5246   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5247                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5248                        bool IsStringLocation, Range StringRange,
5249                        ArrayRef<FixItHint> Fixit = None);
5250 
5251 protected:
5252   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5253                                         const char *startSpec,
5254                                         unsigned specifierLen,
5255                                         const char *csStart, unsigned csLen);
5256 
5257   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5258                                          const char *startSpec,
5259                                          unsigned specifierLen);
5260 
5261   SourceRange getFormatStringRange();
5262   CharSourceRange getSpecifierRange(const char *startSpecifier,
5263                                     unsigned specifierLen);
5264   SourceLocation getLocationOfByte(const char *x);
5265 
5266   const Expr *getDataArg(unsigned i) const;
5267 
5268   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5269                     const analyze_format_string::ConversionSpecifier &CS,
5270                     const char *startSpecifier, unsigned specifierLen,
5271                     unsigned argIndex);
5272 
5273   template <typename Range>
5274   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5275                             bool IsStringLocation, Range StringRange,
5276                             ArrayRef<FixItHint> Fixit = None);
5277 };
5278 } // end anonymous namespace
5279 
5280 SourceRange CheckFormatHandler::getFormatStringRange() {
5281   return OrigFormatExpr->getSourceRange();
5282 }
5283 
5284 CharSourceRange CheckFormatHandler::
5285 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5286   SourceLocation Start = getLocationOfByte(startSpecifier);
5287   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5288 
5289   // Advance the end SourceLocation by one due to half-open ranges.
5290   End = End.getLocWithOffset(1);
5291 
5292   return CharSourceRange::getCharRange(Start, End);
5293 }
5294 
5295 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5296   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5297                                   S.getLangOpts(), S.Context.getTargetInfo());
5298 }
5299 
5300 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5301                                                    unsigned specifierLen){
5302   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5303                        getLocationOfByte(startSpecifier),
5304                        /*IsStringLocation*/true,
5305                        getSpecifierRange(startSpecifier, specifierLen));
5306 }
5307 
5308 void CheckFormatHandler::HandleInvalidLengthModifier(
5309     const analyze_format_string::FormatSpecifier &FS,
5310     const analyze_format_string::ConversionSpecifier &CS,
5311     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5312   using namespace analyze_format_string;
5313 
5314   const LengthModifier &LM = FS.getLengthModifier();
5315   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5316 
5317   // See if we know how to fix this length modifier.
5318   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5319   if (FixedLM) {
5320     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5321                          getLocationOfByte(LM.getStart()),
5322                          /*IsStringLocation*/true,
5323                          getSpecifierRange(startSpecifier, specifierLen));
5324 
5325     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5326       << FixedLM->toString()
5327       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5328 
5329   } else {
5330     FixItHint Hint;
5331     if (DiagID == diag::warn_format_nonsensical_length)
5332       Hint = FixItHint::CreateRemoval(LMRange);
5333 
5334     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5335                          getLocationOfByte(LM.getStart()),
5336                          /*IsStringLocation*/true,
5337                          getSpecifierRange(startSpecifier, specifierLen),
5338                          Hint);
5339   }
5340 }
5341 
5342 void CheckFormatHandler::HandleNonStandardLengthModifier(
5343     const analyze_format_string::FormatSpecifier &FS,
5344     const char *startSpecifier, unsigned specifierLen) {
5345   using namespace analyze_format_string;
5346 
5347   const LengthModifier &LM = FS.getLengthModifier();
5348   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5349 
5350   // See if we know how to fix this length modifier.
5351   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5352   if (FixedLM) {
5353     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5354                            << LM.toString() << 0,
5355                          getLocationOfByte(LM.getStart()),
5356                          /*IsStringLocation*/true,
5357                          getSpecifierRange(startSpecifier, specifierLen));
5358 
5359     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5360       << FixedLM->toString()
5361       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5362 
5363   } else {
5364     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5365                            << LM.toString() << 0,
5366                          getLocationOfByte(LM.getStart()),
5367                          /*IsStringLocation*/true,
5368                          getSpecifierRange(startSpecifier, specifierLen));
5369   }
5370 }
5371 
5372 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5373     const analyze_format_string::ConversionSpecifier &CS,
5374     const char *startSpecifier, unsigned specifierLen) {
5375   using namespace analyze_format_string;
5376 
5377   // See if we know how to fix this conversion specifier.
5378   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5379   if (FixedCS) {
5380     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5381                           << CS.toString() << /*conversion specifier*/1,
5382                          getLocationOfByte(CS.getStart()),
5383                          /*IsStringLocation*/true,
5384                          getSpecifierRange(startSpecifier, specifierLen));
5385 
5386     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5387     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5388       << FixedCS->toString()
5389       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5390   } else {
5391     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5392                           << CS.toString() << /*conversion specifier*/1,
5393                          getLocationOfByte(CS.getStart()),
5394                          /*IsStringLocation*/true,
5395                          getSpecifierRange(startSpecifier, specifierLen));
5396   }
5397 }
5398 
5399 void CheckFormatHandler::HandlePosition(const char *startPos,
5400                                         unsigned posLen) {
5401   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5402                                getLocationOfByte(startPos),
5403                                /*IsStringLocation*/true,
5404                                getSpecifierRange(startPos, posLen));
5405 }
5406 
5407 void
5408 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5409                                      analyze_format_string::PositionContext p) {
5410   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5411                          << (unsigned) p,
5412                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5413                        getSpecifierRange(startPos, posLen));
5414 }
5415 
5416 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5417                                             unsigned posLen) {
5418   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5419                                getLocationOfByte(startPos),
5420                                /*IsStringLocation*/true,
5421                                getSpecifierRange(startPos, posLen));
5422 }
5423 
5424 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5425   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5426     // The presence of a null character is likely an error.
5427     EmitFormatDiagnostic(
5428       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5429       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5430       getFormatStringRange());
5431   }
5432 }
5433 
5434 // Note that this may return NULL if there was an error parsing or building
5435 // one of the argument expressions.
5436 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5437   return Args[FirstDataArg + i];
5438 }
5439 
5440 void CheckFormatHandler::DoneProcessing() {
5441   // Does the number of data arguments exceed the number of
5442   // format conversions in the format string?
5443   if (!HasVAListArg) {
5444       // Find any arguments that weren't covered.
5445     CoveredArgs.flip();
5446     signed notCoveredArg = CoveredArgs.find_first();
5447     if (notCoveredArg >= 0) {
5448       assert((unsigned)notCoveredArg < NumDataArgs);
5449       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5450     } else {
5451       UncoveredArg.setAllCovered();
5452     }
5453   }
5454 }
5455 
5456 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5457                                    const Expr *ArgExpr) {
5458   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5459          "Invalid state");
5460 
5461   if (!ArgExpr)
5462     return;
5463 
5464   SourceLocation Loc = ArgExpr->getLocStart();
5465 
5466   if (S.getSourceManager().isInSystemMacro(Loc))
5467     return;
5468 
5469   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5470   for (auto E : DiagnosticExprs)
5471     PDiag << E->getSourceRange();
5472 
5473   CheckFormatHandler::EmitFormatDiagnostic(
5474                                   S, IsFunctionCall, DiagnosticExprs[0],
5475                                   PDiag, Loc, /*IsStringLocation*/false,
5476                                   DiagnosticExprs[0]->getSourceRange());
5477 }
5478 
5479 bool
5480 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5481                                                      SourceLocation Loc,
5482                                                      const char *startSpec,
5483                                                      unsigned specifierLen,
5484                                                      const char *csStart,
5485                                                      unsigned csLen) {
5486   bool keepGoing = true;
5487   if (argIndex < NumDataArgs) {
5488     // Consider the argument coverered, even though the specifier doesn't
5489     // make sense.
5490     CoveredArgs.set(argIndex);
5491   }
5492   else {
5493     // If argIndex exceeds the number of data arguments we
5494     // don't issue a warning because that is just a cascade of warnings (and
5495     // they may have intended '%%' anyway). We don't want to continue processing
5496     // the format string after this point, however, as we will like just get
5497     // gibberish when trying to match arguments.
5498     keepGoing = false;
5499   }
5500 
5501   StringRef Specifier(csStart, csLen);
5502 
5503   // If the specifier in non-printable, it could be the first byte of a UTF-8
5504   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5505   // hex value.
5506   std::string CodePointStr;
5507   if (!llvm::sys::locale::isPrint(*csStart)) {
5508     llvm::UTF32 CodePoint;
5509     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5510     const llvm::UTF8 *E =
5511         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5512     llvm::ConversionResult Result =
5513         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5514 
5515     if (Result != llvm::conversionOK) {
5516       unsigned char FirstChar = *csStart;
5517       CodePoint = (llvm::UTF32)FirstChar;
5518     }
5519 
5520     llvm::raw_string_ostream OS(CodePointStr);
5521     if (CodePoint < 256)
5522       OS << "\\x" << llvm::format("%02x", CodePoint);
5523     else if (CodePoint <= 0xFFFF)
5524       OS << "\\u" << llvm::format("%04x", CodePoint);
5525     else
5526       OS << "\\U" << llvm::format("%08x", CodePoint);
5527     OS.flush();
5528     Specifier = CodePointStr;
5529   }
5530 
5531   EmitFormatDiagnostic(
5532       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5533       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5534 
5535   return keepGoing;
5536 }
5537 
5538 void
5539 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5540                                                       const char *startSpec,
5541                                                       unsigned specifierLen) {
5542   EmitFormatDiagnostic(
5543     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5544     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5545 }
5546 
5547 bool
5548 CheckFormatHandler::CheckNumArgs(
5549   const analyze_format_string::FormatSpecifier &FS,
5550   const analyze_format_string::ConversionSpecifier &CS,
5551   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5552 
5553   if (argIndex >= NumDataArgs) {
5554     PartialDiagnostic PDiag = FS.usesPositionalArg()
5555       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5556            << (argIndex+1) << NumDataArgs)
5557       : S.PDiag(diag::warn_printf_insufficient_data_args);
5558     EmitFormatDiagnostic(
5559       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5560       getSpecifierRange(startSpecifier, specifierLen));
5561 
5562     // Since more arguments than conversion tokens are given, by extension
5563     // all arguments are covered, so mark this as so.
5564     UncoveredArg.setAllCovered();
5565     return false;
5566   }
5567   return true;
5568 }
5569 
5570 template<typename Range>
5571 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5572                                               SourceLocation Loc,
5573                                               bool IsStringLocation,
5574                                               Range StringRange,
5575                                               ArrayRef<FixItHint> FixIt) {
5576   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5577                        Loc, IsStringLocation, StringRange, FixIt);
5578 }
5579 
5580 /// \brief If the format string is not within the funcion call, emit a note
5581 /// so that the function call and string are in diagnostic messages.
5582 ///
5583 /// \param InFunctionCall if true, the format string is within the function
5584 /// call and only one diagnostic message will be produced.  Otherwise, an
5585 /// extra note will be emitted pointing to location of the format string.
5586 ///
5587 /// \param ArgumentExpr the expression that is passed as the format string
5588 /// argument in the function call.  Used for getting locations when two
5589 /// diagnostics are emitted.
5590 ///
5591 /// \param PDiag the callee should already have provided any strings for the
5592 /// diagnostic message.  This function only adds locations and fixits
5593 /// to diagnostics.
5594 ///
5595 /// \param Loc primary location for diagnostic.  If two diagnostics are
5596 /// required, one will be at Loc and a new SourceLocation will be created for
5597 /// the other one.
5598 ///
5599 /// \param IsStringLocation if true, Loc points to the format string should be
5600 /// used for the note.  Otherwise, Loc points to the argument list and will
5601 /// be used with PDiag.
5602 ///
5603 /// \param StringRange some or all of the string to highlight.  This is
5604 /// templated so it can accept either a CharSourceRange or a SourceRange.
5605 ///
5606 /// \param FixIt optional fix it hint for the format string.
5607 template <typename Range>
5608 void CheckFormatHandler::EmitFormatDiagnostic(
5609     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5610     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5611     Range StringRange, ArrayRef<FixItHint> FixIt) {
5612   if (InFunctionCall) {
5613     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5614     D << StringRange;
5615     D << FixIt;
5616   } else {
5617     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5618       << ArgumentExpr->getSourceRange();
5619 
5620     const Sema::SemaDiagnosticBuilder &Note =
5621       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5622              diag::note_format_string_defined);
5623 
5624     Note << StringRange;
5625     Note << FixIt;
5626   }
5627 }
5628 
5629 //===--- CHECK: Printf format string checking ------------------------------===//
5630 
5631 namespace {
5632 class CheckPrintfHandler : public CheckFormatHandler {
5633 public:
5634   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5635                      const Expr *origFormatExpr,
5636                      const Sema::FormatStringType type, unsigned firstDataArg,
5637                      unsigned numDataArgs, bool isObjC, const char *beg,
5638                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5639                      unsigned formatIdx, bool inFunctionCall,
5640                      Sema::VariadicCallType CallType,
5641                      llvm::SmallBitVector &CheckedVarArgs,
5642                      UncoveredArgHandler &UncoveredArg)
5643       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5644                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5645                            inFunctionCall, CallType, CheckedVarArgs,
5646                            UncoveredArg) {}
5647 
5648   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5649 
5650   /// Returns true if '%@' specifiers are allowed in the format string.
5651   bool allowsObjCArg() const {
5652     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5653            FSType == Sema::FST_OSTrace;
5654   }
5655 
5656   bool HandleInvalidPrintfConversionSpecifier(
5657                                       const analyze_printf::PrintfSpecifier &FS,
5658                                       const char *startSpecifier,
5659                                       unsigned specifierLen) override;
5660 
5661   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5662                              const char *startSpecifier,
5663                              unsigned specifierLen) override;
5664   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5665                        const char *StartSpecifier,
5666                        unsigned SpecifierLen,
5667                        const Expr *E);
5668 
5669   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5670                     const char *startSpecifier, unsigned specifierLen);
5671   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5672                            const analyze_printf::OptionalAmount &Amt,
5673                            unsigned type,
5674                            const char *startSpecifier, unsigned specifierLen);
5675   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5676                   const analyze_printf::OptionalFlag &flag,
5677                   const char *startSpecifier, unsigned specifierLen);
5678   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5679                          const analyze_printf::OptionalFlag &ignoredFlag,
5680                          const analyze_printf::OptionalFlag &flag,
5681                          const char *startSpecifier, unsigned specifierLen);
5682   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5683                            const Expr *E);
5684 
5685   void HandleEmptyObjCModifierFlag(const char *startFlag,
5686                                    unsigned flagLen) override;
5687 
5688   void HandleInvalidObjCModifierFlag(const char *startFlag,
5689                                             unsigned flagLen) override;
5690 
5691   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5692                                            const char *flagsEnd,
5693                                            const char *conversionPosition)
5694                                              override;
5695 };
5696 } // end anonymous namespace
5697 
5698 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5699                                       const analyze_printf::PrintfSpecifier &FS,
5700                                       const char *startSpecifier,
5701                                       unsigned specifierLen) {
5702   const analyze_printf::PrintfConversionSpecifier &CS =
5703     FS.getConversionSpecifier();
5704 
5705   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5706                                           getLocationOfByte(CS.getStart()),
5707                                           startSpecifier, specifierLen,
5708                                           CS.getStart(), CS.getLength());
5709 }
5710 
5711 bool CheckPrintfHandler::HandleAmount(
5712                                const analyze_format_string::OptionalAmount &Amt,
5713                                unsigned k, const char *startSpecifier,
5714                                unsigned specifierLen) {
5715   if (Amt.hasDataArgument()) {
5716     if (!HasVAListArg) {
5717       unsigned argIndex = Amt.getArgIndex();
5718       if (argIndex >= NumDataArgs) {
5719         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5720                                << k,
5721                              getLocationOfByte(Amt.getStart()),
5722                              /*IsStringLocation*/true,
5723                              getSpecifierRange(startSpecifier, specifierLen));
5724         // Don't do any more checking.  We will just emit
5725         // spurious errors.
5726         return false;
5727       }
5728 
5729       // Type check the data argument.  It should be an 'int'.
5730       // Although not in conformance with C99, we also allow the argument to be
5731       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5732       // doesn't emit a warning for that case.
5733       CoveredArgs.set(argIndex);
5734       const Expr *Arg = getDataArg(argIndex);
5735       if (!Arg)
5736         return false;
5737 
5738       QualType T = Arg->getType();
5739 
5740       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5741       assert(AT.isValid());
5742 
5743       if (!AT.matchesType(S.Context, T)) {
5744         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5745                                << k << AT.getRepresentativeTypeName(S.Context)
5746                                << T << Arg->getSourceRange(),
5747                              getLocationOfByte(Amt.getStart()),
5748                              /*IsStringLocation*/true,
5749                              getSpecifierRange(startSpecifier, specifierLen));
5750         // Don't do any more checking.  We will just emit
5751         // spurious errors.
5752         return false;
5753       }
5754     }
5755   }
5756   return true;
5757 }
5758 
5759 void CheckPrintfHandler::HandleInvalidAmount(
5760                                       const analyze_printf::PrintfSpecifier &FS,
5761                                       const analyze_printf::OptionalAmount &Amt,
5762                                       unsigned type,
5763                                       const char *startSpecifier,
5764                                       unsigned specifierLen) {
5765   const analyze_printf::PrintfConversionSpecifier &CS =
5766     FS.getConversionSpecifier();
5767 
5768   FixItHint fixit =
5769     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5770       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5771                                  Amt.getConstantLength()))
5772       : FixItHint();
5773 
5774   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5775                          << type << CS.toString(),
5776                        getLocationOfByte(Amt.getStart()),
5777                        /*IsStringLocation*/true,
5778                        getSpecifierRange(startSpecifier, specifierLen),
5779                        fixit);
5780 }
5781 
5782 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5783                                     const analyze_printf::OptionalFlag &flag,
5784                                     const char *startSpecifier,
5785                                     unsigned specifierLen) {
5786   // Warn about pointless flag with a fixit removal.
5787   const analyze_printf::PrintfConversionSpecifier &CS =
5788     FS.getConversionSpecifier();
5789   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5790                          << flag.toString() << CS.toString(),
5791                        getLocationOfByte(flag.getPosition()),
5792                        /*IsStringLocation*/true,
5793                        getSpecifierRange(startSpecifier, specifierLen),
5794                        FixItHint::CreateRemoval(
5795                          getSpecifierRange(flag.getPosition(), 1)));
5796 }
5797 
5798 void CheckPrintfHandler::HandleIgnoredFlag(
5799                                 const analyze_printf::PrintfSpecifier &FS,
5800                                 const analyze_printf::OptionalFlag &ignoredFlag,
5801                                 const analyze_printf::OptionalFlag &flag,
5802                                 const char *startSpecifier,
5803                                 unsigned specifierLen) {
5804   // Warn about ignored flag with a fixit removal.
5805   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5806                          << ignoredFlag.toString() << flag.toString(),
5807                        getLocationOfByte(ignoredFlag.getPosition()),
5808                        /*IsStringLocation*/true,
5809                        getSpecifierRange(startSpecifier, specifierLen),
5810                        FixItHint::CreateRemoval(
5811                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5812 }
5813 
5814 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5815 //                            bool IsStringLocation, Range StringRange,
5816 //                            ArrayRef<FixItHint> Fixit = None);
5817 
5818 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5819                                                      unsigned flagLen) {
5820   // Warn about an empty flag.
5821   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5822                        getLocationOfByte(startFlag),
5823                        /*IsStringLocation*/true,
5824                        getSpecifierRange(startFlag, flagLen));
5825 }
5826 
5827 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5828                                                        unsigned flagLen) {
5829   // Warn about an invalid flag.
5830   auto Range = getSpecifierRange(startFlag, flagLen);
5831   StringRef flag(startFlag, flagLen);
5832   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5833                       getLocationOfByte(startFlag),
5834                       /*IsStringLocation*/true,
5835                       Range, FixItHint::CreateRemoval(Range));
5836 }
5837 
5838 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5839     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5840     // Warn about using '[...]' without a '@' conversion.
5841     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5842     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5843     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5844                          getLocationOfByte(conversionPosition),
5845                          /*IsStringLocation*/true,
5846                          Range, FixItHint::CreateRemoval(Range));
5847 }
5848 
5849 // Determines if the specified is a C++ class or struct containing
5850 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5851 // "c_str()").
5852 template<typename MemberKind>
5853 static llvm::SmallPtrSet<MemberKind*, 1>
5854 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5855   const RecordType *RT = Ty->getAs<RecordType>();
5856   llvm::SmallPtrSet<MemberKind*, 1> Results;
5857 
5858   if (!RT)
5859     return Results;
5860   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5861   if (!RD || !RD->getDefinition())
5862     return Results;
5863 
5864   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5865                  Sema::LookupMemberName);
5866   R.suppressDiagnostics();
5867 
5868   // We just need to include all members of the right kind turned up by the
5869   // filter, at this point.
5870   if (S.LookupQualifiedName(R, RT->getDecl()))
5871     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5872       NamedDecl *decl = (*I)->getUnderlyingDecl();
5873       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5874         Results.insert(FK);
5875     }
5876   return Results;
5877 }
5878 
5879 /// Check if we could call '.c_str()' on an object.
5880 ///
5881 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5882 /// allow the call, or if it would be ambiguous).
5883 bool Sema::hasCStrMethod(const Expr *E) {
5884   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5885   MethodSet Results =
5886       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5887   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5888        MI != ME; ++MI)
5889     if ((*MI)->getMinRequiredArguments() == 0)
5890       return true;
5891   return false;
5892 }
5893 
5894 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5895 // better diagnostic if so. AT is assumed to be valid.
5896 // Returns true when a c_str() conversion method is found.
5897 bool CheckPrintfHandler::checkForCStrMembers(
5898     const analyze_printf::ArgType &AT, const Expr *E) {
5899   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5900 
5901   MethodSet Results =
5902       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5903 
5904   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5905        MI != ME; ++MI) {
5906     const CXXMethodDecl *Method = *MI;
5907     if (Method->getMinRequiredArguments() == 0 &&
5908         AT.matchesType(S.Context, Method->getReturnType())) {
5909       // FIXME: Suggest parens if the expression needs them.
5910       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5911       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5912           << "c_str()"
5913           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5914       return true;
5915     }
5916   }
5917 
5918   return false;
5919 }
5920 
5921 bool
5922 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5923                                             &FS,
5924                                           const char *startSpecifier,
5925                                           unsigned specifierLen) {
5926   using namespace analyze_format_string;
5927   using namespace analyze_printf;
5928   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5929 
5930   if (FS.consumesDataArgument()) {
5931     if (atFirstArg) {
5932         atFirstArg = false;
5933         usesPositionalArgs = FS.usesPositionalArg();
5934     }
5935     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5936       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5937                                         startSpecifier, specifierLen);
5938       return false;
5939     }
5940   }
5941 
5942   // First check if the field width, precision, and conversion specifier
5943   // have matching data arguments.
5944   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5945                     startSpecifier, specifierLen)) {
5946     return false;
5947   }
5948 
5949   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5950                     startSpecifier, specifierLen)) {
5951     return false;
5952   }
5953 
5954   if (!CS.consumesDataArgument()) {
5955     // FIXME: Technically specifying a precision or field width here
5956     // makes no sense.  Worth issuing a warning at some point.
5957     return true;
5958   }
5959 
5960   // Consume the argument.
5961   unsigned argIndex = FS.getArgIndex();
5962   if (argIndex < NumDataArgs) {
5963     // The check to see if the argIndex is valid will come later.
5964     // We set the bit here because we may exit early from this
5965     // function if we encounter some other error.
5966     CoveredArgs.set(argIndex);
5967   }
5968 
5969   // FreeBSD kernel extensions.
5970   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5971       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5972     // We need at least two arguments.
5973     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5974       return false;
5975 
5976     // Claim the second argument.
5977     CoveredArgs.set(argIndex + 1);
5978 
5979     // Type check the first argument (int for %b, pointer for %D)
5980     const Expr *Ex = getDataArg(argIndex);
5981     const analyze_printf::ArgType &AT =
5982       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5983         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5984     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5985       EmitFormatDiagnostic(
5986         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5987         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5988         << false << Ex->getSourceRange(),
5989         Ex->getLocStart(), /*IsStringLocation*/false,
5990         getSpecifierRange(startSpecifier, specifierLen));
5991 
5992     // Type check the second argument (char * for both %b and %D)
5993     Ex = getDataArg(argIndex + 1);
5994     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5995     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5996       EmitFormatDiagnostic(
5997         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5998         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5999         << false << Ex->getSourceRange(),
6000         Ex->getLocStart(), /*IsStringLocation*/false,
6001         getSpecifierRange(startSpecifier, specifierLen));
6002 
6003      return true;
6004   }
6005 
6006   // Check for using an Objective-C specific conversion specifier
6007   // in a non-ObjC literal.
6008   if (!allowsObjCArg() && CS.isObjCArg()) {
6009     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6010                                                   specifierLen);
6011   }
6012 
6013   // %P can only be used with os_log.
6014   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6015     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6016                                                   specifierLen);
6017   }
6018 
6019   // %n is not allowed with os_log.
6020   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6021     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6022                          getLocationOfByte(CS.getStart()),
6023                          /*IsStringLocation*/ false,
6024                          getSpecifierRange(startSpecifier, specifierLen));
6025 
6026     return true;
6027   }
6028 
6029   // Only scalars are allowed for os_trace.
6030   if (FSType == Sema::FST_OSTrace &&
6031       (CS.getKind() == ConversionSpecifier::PArg ||
6032        CS.getKind() == ConversionSpecifier::sArg ||
6033        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6034     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6035                                                   specifierLen);
6036   }
6037 
6038   // Check for use of public/private annotation outside of os_log().
6039   if (FSType != Sema::FST_OSLog) {
6040     if (FS.isPublic().isSet()) {
6041       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6042                                << "public",
6043                            getLocationOfByte(FS.isPublic().getPosition()),
6044                            /*IsStringLocation*/ false,
6045                            getSpecifierRange(startSpecifier, specifierLen));
6046     }
6047     if (FS.isPrivate().isSet()) {
6048       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6049                                << "private",
6050                            getLocationOfByte(FS.isPrivate().getPosition()),
6051                            /*IsStringLocation*/ false,
6052                            getSpecifierRange(startSpecifier, specifierLen));
6053     }
6054   }
6055 
6056   // Check for invalid use of field width
6057   if (!FS.hasValidFieldWidth()) {
6058     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6059         startSpecifier, specifierLen);
6060   }
6061 
6062   // Check for invalid use of precision
6063   if (!FS.hasValidPrecision()) {
6064     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6065         startSpecifier, specifierLen);
6066   }
6067 
6068   // Precision is mandatory for %P specifier.
6069   if (CS.getKind() == ConversionSpecifier::PArg &&
6070       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6071     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6072                          getLocationOfByte(startSpecifier),
6073                          /*IsStringLocation*/ false,
6074                          getSpecifierRange(startSpecifier, specifierLen));
6075   }
6076 
6077   // Check each flag does not conflict with any other component.
6078   if (!FS.hasValidThousandsGroupingPrefix())
6079     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6080   if (!FS.hasValidLeadingZeros())
6081     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6082   if (!FS.hasValidPlusPrefix())
6083     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6084   if (!FS.hasValidSpacePrefix())
6085     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6086   if (!FS.hasValidAlternativeForm())
6087     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6088   if (!FS.hasValidLeftJustified())
6089     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6090 
6091   // Check that flags are not ignored by another flag
6092   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6093     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6094         startSpecifier, specifierLen);
6095   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6096     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6097             startSpecifier, specifierLen);
6098 
6099   // Check the length modifier is valid with the given conversion specifier.
6100   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6101     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6102                                 diag::warn_format_nonsensical_length);
6103   else if (!FS.hasStandardLengthModifier())
6104     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6105   else if (!FS.hasStandardLengthConversionCombination())
6106     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6107                                 diag::warn_format_non_standard_conversion_spec);
6108 
6109   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6110     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6111 
6112   // The remaining checks depend on the data arguments.
6113   if (HasVAListArg)
6114     return true;
6115 
6116   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6117     return false;
6118 
6119   const Expr *Arg = getDataArg(argIndex);
6120   if (!Arg)
6121     return true;
6122 
6123   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6124 }
6125 
6126 static bool requiresParensToAddCast(const Expr *E) {
6127   // FIXME: We should have a general way to reason about operator
6128   // precedence and whether parens are actually needed here.
6129   // Take care of a few common cases where they aren't.
6130   const Expr *Inside = E->IgnoreImpCasts();
6131   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6132     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6133 
6134   switch (Inside->getStmtClass()) {
6135   case Stmt::ArraySubscriptExprClass:
6136   case Stmt::CallExprClass:
6137   case Stmt::CharacterLiteralClass:
6138   case Stmt::CXXBoolLiteralExprClass:
6139   case Stmt::DeclRefExprClass:
6140   case Stmt::FloatingLiteralClass:
6141   case Stmt::IntegerLiteralClass:
6142   case Stmt::MemberExprClass:
6143   case Stmt::ObjCArrayLiteralClass:
6144   case Stmt::ObjCBoolLiteralExprClass:
6145   case Stmt::ObjCBoxedExprClass:
6146   case Stmt::ObjCDictionaryLiteralClass:
6147   case Stmt::ObjCEncodeExprClass:
6148   case Stmt::ObjCIvarRefExprClass:
6149   case Stmt::ObjCMessageExprClass:
6150   case Stmt::ObjCPropertyRefExprClass:
6151   case Stmt::ObjCStringLiteralClass:
6152   case Stmt::ObjCSubscriptRefExprClass:
6153   case Stmt::ParenExprClass:
6154   case Stmt::StringLiteralClass:
6155   case Stmt::UnaryOperatorClass:
6156     return false;
6157   default:
6158     return true;
6159   }
6160 }
6161 
6162 static std::pair<QualType, StringRef>
6163 shouldNotPrintDirectly(const ASTContext &Context,
6164                        QualType IntendedTy,
6165                        const Expr *E) {
6166   // Use a 'while' to peel off layers of typedefs.
6167   QualType TyTy = IntendedTy;
6168   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6169     StringRef Name = UserTy->getDecl()->getName();
6170     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6171       .Case("CFIndex", Context.getNSIntegerType())
6172       .Case("NSInteger", Context.getNSIntegerType())
6173       .Case("NSUInteger", Context.getNSUIntegerType())
6174       .Case("SInt32", Context.IntTy)
6175       .Case("UInt32", Context.UnsignedIntTy)
6176       .Default(QualType());
6177 
6178     if (!CastTy.isNull())
6179       return std::make_pair(CastTy, Name);
6180 
6181     TyTy = UserTy->desugar();
6182   }
6183 
6184   // Strip parens if necessary.
6185   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6186     return shouldNotPrintDirectly(Context,
6187                                   PE->getSubExpr()->getType(),
6188                                   PE->getSubExpr());
6189 
6190   // If this is a conditional expression, then its result type is constructed
6191   // via usual arithmetic conversions and thus there might be no necessary
6192   // typedef sugar there.  Recurse to operands to check for NSInteger &
6193   // Co. usage condition.
6194   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6195     QualType TrueTy, FalseTy;
6196     StringRef TrueName, FalseName;
6197 
6198     std::tie(TrueTy, TrueName) =
6199       shouldNotPrintDirectly(Context,
6200                              CO->getTrueExpr()->getType(),
6201                              CO->getTrueExpr());
6202     std::tie(FalseTy, FalseName) =
6203       shouldNotPrintDirectly(Context,
6204                              CO->getFalseExpr()->getType(),
6205                              CO->getFalseExpr());
6206 
6207     if (TrueTy == FalseTy)
6208       return std::make_pair(TrueTy, TrueName);
6209     else if (TrueTy.isNull())
6210       return std::make_pair(FalseTy, FalseName);
6211     else if (FalseTy.isNull())
6212       return std::make_pair(TrueTy, TrueName);
6213   }
6214 
6215   return std::make_pair(QualType(), StringRef());
6216 }
6217 
6218 bool
6219 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6220                                     const char *StartSpecifier,
6221                                     unsigned SpecifierLen,
6222                                     const Expr *E) {
6223   using namespace analyze_format_string;
6224   using namespace analyze_printf;
6225   // Now type check the data expression that matches the
6226   // format specifier.
6227   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6228   if (!AT.isValid())
6229     return true;
6230 
6231   QualType ExprTy = E->getType();
6232   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6233     ExprTy = TET->getUnderlyingExpr()->getType();
6234   }
6235 
6236   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6237 
6238   if (match == analyze_printf::ArgType::Match) {
6239     return true;
6240   }
6241 
6242   // Look through argument promotions for our error message's reported type.
6243   // This includes the integral and floating promotions, but excludes array
6244   // and function pointer decay; seeing that an argument intended to be a
6245   // string has type 'char [6]' is probably more confusing than 'char *'.
6246   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6247     if (ICE->getCastKind() == CK_IntegralCast ||
6248         ICE->getCastKind() == CK_FloatingCast) {
6249       E = ICE->getSubExpr();
6250       ExprTy = E->getType();
6251 
6252       // Check if we didn't match because of an implicit cast from a 'char'
6253       // or 'short' to an 'int'.  This is done because printf is a varargs
6254       // function.
6255       if (ICE->getType() == S.Context.IntTy ||
6256           ICE->getType() == S.Context.UnsignedIntTy) {
6257         // All further checking is done on the subexpression.
6258         if (AT.matchesType(S.Context, ExprTy))
6259           return true;
6260       }
6261     }
6262   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6263     // Special case for 'a', which has type 'int' in C.
6264     // Note, however, that we do /not/ want to treat multibyte constants like
6265     // 'MooV' as characters! This form is deprecated but still exists.
6266     if (ExprTy == S.Context.IntTy)
6267       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6268         ExprTy = S.Context.CharTy;
6269   }
6270 
6271   // Look through enums to their underlying type.
6272   bool IsEnum = false;
6273   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6274     ExprTy = EnumTy->getDecl()->getIntegerType();
6275     IsEnum = true;
6276   }
6277 
6278   // %C in an Objective-C context prints a unichar, not a wchar_t.
6279   // If the argument is an integer of some kind, believe the %C and suggest
6280   // a cast instead of changing the conversion specifier.
6281   QualType IntendedTy = ExprTy;
6282   if (isObjCContext() &&
6283       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6284     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6285         !ExprTy->isCharType()) {
6286       // 'unichar' is defined as a typedef of unsigned short, but we should
6287       // prefer using the typedef if it is visible.
6288       IntendedTy = S.Context.UnsignedShortTy;
6289 
6290       // While we are here, check if the value is an IntegerLiteral that happens
6291       // to be within the valid range.
6292       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6293         const llvm::APInt &V = IL->getValue();
6294         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6295           return true;
6296       }
6297 
6298       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6299                           Sema::LookupOrdinaryName);
6300       if (S.LookupName(Result, S.getCurScope())) {
6301         NamedDecl *ND = Result.getFoundDecl();
6302         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6303           if (TD->getUnderlyingType() == IntendedTy)
6304             IntendedTy = S.Context.getTypedefType(TD);
6305       }
6306     }
6307   }
6308 
6309   // Special-case some of Darwin's platform-independence types by suggesting
6310   // casts to primitive types that are known to be large enough.
6311   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6312   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6313     QualType CastTy;
6314     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6315     if (!CastTy.isNull()) {
6316       IntendedTy = CastTy;
6317       ShouldNotPrintDirectly = true;
6318     }
6319   }
6320 
6321   // We may be able to offer a FixItHint if it is a supported type.
6322   PrintfSpecifier fixedFS = FS;
6323   bool success =
6324       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6325 
6326   if (success) {
6327     // Get the fix string from the fixed format specifier
6328     SmallString<16> buf;
6329     llvm::raw_svector_ostream os(buf);
6330     fixedFS.toString(os);
6331 
6332     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6333 
6334     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6335       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6336       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6337         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6338       }
6339       // In this case, the specifier is wrong and should be changed to match
6340       // the argument.
6341       EmitFormatDiagnostic(S.PDiag(diag)
6342                                << AT.getRepresentativeTypeName(S.Context)
6343                                << IntendedTy << IsEnum << E->getSourceRange(),
6344                            E->getLocStart(),
6345                            /*IsStringLocation*/ false, SpecRange,
6346                            FixItHint::CreateReplacement(SpecRange, os.str()));
6347     } else {
6348       // The canonical type for formatting this value is different from the
6349       // actual type of the expression. (This occurs, for example, with Darwin's
6350       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6351       // should be printed as 'long' for 64-bit compatibility.)
6352       // Rather than emitting a normal format/argument mismatch, we want to
6353       // add a cast to the recommended type (and correct the format string
6354       // if necessary).
6355       SmallString<16> CastBuf;
6356       llvm::raw_svector_ostream CastFix(CastBuf);
6357       CastFix << "(";
6358       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6359       CastFix << ")";
6360 
6361       SmallVector<FixItHint,4> Hints;
6362       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6363         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6364 
6365       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6366         // If there's already a cast present, just replace it.
6367         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6368         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6369 
6370       } else if (!requiresParensToAddCast(E)) {
6371         // If the expression has high enough precedence,
6372         // just write the C-style cast.
6373         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6374                                                    CastFix.str()));
6375       } else {
6376         // Otherwise, add parens around the expression as well as the cast.
6377         CastFix << "(";
6378         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6379                                                    CastFix.str()));
6380 
6381         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6382         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6383       }
6384 
6385       if (ShouldNotPrintDirectly) {
6386         // The expression has a type that should not be printed directly.
6387         // We extract the name from the typedef because we don't want to show
6388         // the underlying type in the diagnostic.
6389         StringRef Name;
6390         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6391           Name = TypedefTy->getDecl()->getName();
6392         else
6393           Name = CastTyName;
6394         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6395                                << Name << IntendedTy << IsEnum
6396                                << E->getSourceRange(),
6397                              E->getLocStart(), /*IsStringLocation=*/false,
6398                              SpecRange, Hints);
6399       } else {
6400         // In this case, the expression could be printed using a different
6401         // specifier, but we've decided that the specifier is probably correct
6402         // and we should cast instead. Just use the normal warning message.
6403         EmitFormatDiagnostic(
6404           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6405             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6406             << E->getSourceRange(),
6407           E->getLocStart(), /*IsStringLocation*/false,
6408           SpecRange, Hints);
6409       }
6410     }
6411   } else {
6412     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6413                                                    SpecifierLen);
6414     // Since the warning for passing non-POD types to variadic functions
6415     // was deferred until now, we emit a warning for non-POD
6416     // arguments here.
6417     switch (S.isValidVarArgType(ExprTy)) {
6418     case Sema::VAK_Valid:
6419     case Sema::VAK_ValidInCXX11: {
6420       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6421       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6422         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6423       }
6424 
6425       EmitFormatDiagnostic(
6426           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6427                         << IsEnum << CSR << E->getSourceRange(),
6428           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6429       break;
6430     }
6431     case Sema::VAK_Undefined:
6432     case Sema::VAK_MSVCUndefined:
6433       EmitFormatDiagnostic(
6434         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6435           << S.getLangOpts().CPlusPlus11
6436           << ExprTy
6437           << CallType
6438           << AT.getRepresentativeTypeName(S.Context)
6439           << CSR
6440           << E->getSourceRange(),
6441         E->getLocStart(), /*IsStringLocation*/false, CSR);
6442       checkForCStrMembers(AT, E);
6443       break;
6444 
6445     case Sema::VAK_Invalid:
6446       if (ExprTy->isObjCObjectType())
6447         EmitFormatDiagnostic(
6448           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6449             << S.getLangOpts().CPlusPlus11
6450             << ExprTy
6451             << CallType
6452             << AT.getRepresentativeTypeName(S.Context)
6453             << CSR
6454             << E->getSourceRange(),
6455           E->getLocStart(), /*IsStringLocation*/false, CSR);
6456       else
6457         // FIXME: If this is an initializer list, suggest removing the braces
6458         // or inserting a cast to the target type.
6459         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6460           << isa<InitListExpr>(E) << ExprTy << CallType
6461           << AT.getRepresentativeTypeName(S.Context)
6462           << E->getSourceRange();
6463       break;
6464     }
6465 
6466     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6467            "format string specifier index out of range");
6468     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6469   }
6470 
6471   return true;
6472 }
6473 
6474 //===--- CHECK: Scanf format string checking ------------------------------===//
6475 
6476 namespace {
6477 class CheckScanfHandler : public CheckFormatHandler {
6478 public:
6479   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6480                     const Expr *origFormatExpr, Sema::FormatStringType type,
6481                     unsigned firstDataArg, unsigned numDataArgs,
6482                     const char *beg, bool hasVAListArg,
6483                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6484                     bool inFunctionCall, Sema::VariadicCallType CallType,
6485                     llvm::SmallBitVector &CheckedVarArgs,
6486                     UncoveredArgHandler &UncoveredArg)
6487       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6488                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6489                            inFunctionCall, CallType, CheckedVarArgs,
6490                            UncoveredArg) {}
6491 
6492   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6493                             const char *startSpecifier,
6494                             unsigned specifierLen) override;
6495 
6496   bool HandleInvalidScanfConversionSpecifier(
6497           const analyze_scanf::ScanfSpecifier &FS,
6498           const char *startSpecifier,
6499           unsigned specifierLen) override;
6500 
6501   void HandleIncompleteScanList(const char *start, const char *end) override;
6502 };
6503 } // end anonymous namespace
6504 
6505 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6506                                                  const char *end) {
6507   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6508                        getLocationOfByte(end), /*IsStringLocation*/true,
6509                        getSpecifierRange(start, end - start));
6510 }
6511 
6512 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6513                                         const analyze_scanf::ScanfSpecifier &FS,
6514                                         const char *startSpecifier,
6515                                         unsigned specifierLen) {
6516 
6517   const analyze_scanf::ScanfConversionSpecifier &CS =
6518     FS.getConversionSpecifier();
6519 
6520   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6521                                           getLocationOfByte(CS.getStart()),
6522                                           startSpecifier, specifierLen,
6523                                           CS.getStart(), CS.getLength());
6524 }
6525 
6526 bool CheckScanfHandler::HandleScanfSpecifier(
6527                                        const analyze_scanf::ScanfSpecifier &FS,
6528                                        const char *startSpecifier,
6529                                        unsigned specifierLen) {
6530   using namespace analyze_scanf;
6531   using namespace analyze_format_string;
6532 
6533   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6534 
6535   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6536   // be used to decide if we are using positional arguments consistently.
6537   if (FS.consumesDataArgument()) {
6538     if (atFirstArg) {
6539       atFirstArg = false;
6540       usesPositionalArgs = FS.usesPositionalArg();
6541     }
6542     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6543       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6544                                         startSpecifier, specifierLen);
6545       return false;
6546     }
6547   }
6548 
6549   // Check if the field with is non-zero.
6550   const OptionalAmount &Amt = FS.getFieldWidth();
6551   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6552     if (Amt.getConstantAmount() == 0) {
6553       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6554                                                    Amt.getConstantLength());
6555       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6556                            getLocationOfByte(Amt.getStart()),
6557                            /*IsStringLocation*/true, R,
6558                            FixItHint::CreateRemoval(R));
6559     }
6560   }
6561 
6562   if (!FS.consumesDataArgument()) {
6563     // FIXME: Technically specifying a precision or field width here
6564     // makes no sense.  Worth issuing a warning at some point.
6565     return true;
6566   }
6567 
6568   // Consume the argument.
6569   unsigned argIndex = FS.getArgIndex();
6570   if (argIndex < NumDataArgs) {
6571       // The check to see if the argIndex is valid will come later.
6572       // We set the bit here because we may exit early from this
6573       // function if we encounter some other error.
6574     CoveredArgs.set(argIndex);
6575   }
6576 
6577   // Check the length modifier is valid with the given conversion specifier.
6578   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6579     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6580                                 diag::warn_format_nonsensical_length);
6581   else if (!FS.hasStandardLengthModifier())
6582     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6583   else if (!FS.hasStandardLengthConversionCombination())
6584     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6585                                 diag::warn_format_non_standard_conversion_spec);
6586 
6587   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6588     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6589 
6590   // The remaining checks depend on the data arguments.
6591   if (HasVAListArg)
6592     return true;
6593 
6594   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6595     return false;
6596 
6597   // Check that the argument type matches the format specifier.
6598   const Expr *Ex = getDataArg(argIndex);
6599   if (!Ex)
6600     return true;
6601 
6602   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6603 
6604   if (!AT.isValid()) {
6605     return true;
6606   }
6607 
6608   analyze_format_string::ArgType::MatchKind match =
6609       AT.matchesType(S.Context, Ex->getType());
6610   if (match == analyze_format_string::ArgType::Match) {
6611     return true;
6612   }
6613 
6614   ScanfSpecifier fixedFS = FS;
6615   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6616                                  S.getLangOpts(), S.Context);
6617 
6618   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6619   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6620     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6621   }
6622 
6623   if (success) {
6624     // Get the fix string from the fixed format specifier.
6625     SmallString<128> buf;
6626     llvm::raw_svector_ostream os(buf);
6627     fixedFS.toString(os);
6628 
6629     EmitFormatDiagnostic(
6630         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6631                       << Ex->getType() << false << Ex->getSourceRange(),
6632         Ex->getLocStart(),
6633         /*IsStringLocation*/ false,
6634         getSpecifierRange(startSpecifier, specifierLen),
6635         FixItHint::CreateReplacement(
6636             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6637   } else {
6638     EmitFormatDiagnostic(S.PDiag(diag)
6639                              << AT.getRepresentativeTypeName(S.Context)
6640                              << Ex->getType() << false << Ex->getSourceRange(),
6641                          Ex->getLocStart(),
6642                          /*IsStringLocation*/ false,
6643                          getSpecifierRange(startSpecifier, specifierLen));
6644   }
6645 
6646   return true;
6647 }
6648 
6649 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6650                               const Expr *OrigFormatExpr,
6651                               ArrayRef<const Expr *> Args,
6652                               bool HasVAListArg, unsigned format_idx,
6653                               unsigned firstDataArg,
6654                               Sema::FormatStringType Type,
6655                               bool inFunctionCall,
6656                               Sema::VariadicCallType CallType,
6657                               llvm::SmallBitVector &CheckedVarArgs,
6658                               UncoveredArgHandler &UncoveredArg) {
6659   // CHECK: is the format string a wide literal?
6660   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6661     CheckFormatHandler::EmitFormatDiagnostic(
6662       S, inFunctionCall, Args[format_idx],
6663       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6664       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6665     return;
6666   }
6667 
6668   // Str - The format string.  NOTE: this is NOT null-terminated!
6669   StringRef StrRef = FExpr->getString();
6670   const char *Str = StrRef.data();
6671   // Account for cases where the string literal is truncated in a declaration.
6672   const ConstantArrayType *T =
6673     S.Context.getAsConstantArrayType(FExpr->getType());
6674   assert(T && "String literal not of constant array type!");
6675   size_t TypeSize = T->getSize().getZExtValue();
6676   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6677   const unsigned numDataArgs = Args.size() - firstDataArg;
6678 
6679   // Emit a warning if the string literal is truncated and does not contain an
6680   // embedded null character.
6681   if (TypeSize <= StrRef.size() &&
6682       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6683     CheckFormatHandler::EmitFormatDiagnostic(
6684         S, inFunctionCall, Args[format_idx],
6685         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6686         FExpr->getLocStart(),
6687         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6688     return;
6689   }
6690 
6691   // CHECK: empty format string?
6692   if (StrLen == 0 && numDataArgs > 0) {
6693     CheckFormatHandler::EmitFormatDiagnostic(
6694       S, inFunctionCall, Args[format_idx],
6695       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6696       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6697     return;
6698   }
6699 
6700   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6701       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6702       Type == Sema::FST_OSTrace) {
6703     CheckPrintfHandler H(
6704         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6705         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6706         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6707         CheckedVarArgs, UncoveredArg);
6708 
6709     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6710                                                   S.getLangOpts(),
6711                                                   S.Context.getTargetInfo(),
6712                                             Type == Sema::FST_FreeBSDKPrintf))
6713       H.DoneProcessing();
6714   } else if (Type == Sema::FST_Scanf) {
6715     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6716                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6717                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6718 
6719     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6720                                                  S.getLangOpts(),
6721                                                  S.Context.getTargetInfo()))
6722       H.DoneProcessing();
6723   } // TODO: handle other formats
6724 }
6725 
6726 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6727   // Str - The format string.  NOTE: this is NOT null-terminated!
6728   StringRef StrRef = FExpr->getString();
6729   const char *Str = StrRef.data();
6730   // Account for cases where the string literal is truncated in a declaration.
6731   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6732   assert(T && "String literal not of constant array type!");
6733   size_t TypeSize = T->getSize().getZExtValue();
6734   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6735   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6736                                                          getLangOpts(),
6737                                                          Context.getTargetInfo());
6738 }
6739 
6740 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6741 
6742 // Returns the related absolute value function that is larger, of 0 if one
6743 // does not exist.
6744 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6745   switch (AbsFunction) {
6746   default:
6747     return 0;
6748 
6749   case Builtin::BI__builtin_abs:
6750     return Builtin::BI__builtin_labs;
6751   case Builtin::BI__builtin_labs:
6752     return Builtin::BI__builtin_llabs;
6753   case Builtin::BI__builtin_llabs:
6754     return 0;
6755 
6756   case Builtin::BI__builtin_fabsf:
6757     return Builtin::BI__builtin_fabs;
6758   case Builtin::BI__builtin_fabs:
6759     return Builtin::BI__builtin_fabsl;
6760   case Builtin::BI__builtin_fabsl:
6761     return 0;
6762 
6763   case Builtin::BI__builtin_cabsf:
6764     return Builtin::BI__builtin_cabs;
6765   case Builtin::BI__builtin_cabs:
6766     return Builtin::BI__builtin_cabsl;
6767   case Builtin::BI__builtin_cabsl:
6768     return 0;
6769 
6770   case Builtin::BIabs:
6771     return Builtin::BIlabs;
6772   case Builtin::BIlabs:
6773     return Builtin::BIllabs;
6774   case Builtin::BIllabs:
6775     return 0;
6776 
6777   case Builtin::BIfabsf:
6778     return Builtin::BIfabs;
6779   case Builtin::BIfabs:
6780     return Builtin::BIfabsl;
6781   case Builtin::BIfabsl:
6782     return 0;
6783 
6784   case Builtin::BIcabsf:
6785    return Builtin::BIcabs;
6786   case Builtin::BIcabs:
6787     return Builtin::BIcabsl;
6788   case Builtin::BIcabsl:
6789     return 0;
6790   }
6791 }
6792 
6793 // Returns the argument type of the absolute value function.
6794 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6795                                              unsigned AbsType) {
6796   if (AbsType == 0)
6797     return QualType();
6798 
6799   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6800   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6801   if (Error != ASTContext::GE_None)
6802     return QualType();
6803 
6804   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6805   if (!FT)
6806     return QualType();
6807 
6808   if (FT->getNumParams() != 1)
6809     return QualType();
6810 
6811   return FT->getParamType(0);
6812 }
6813 
6814 // Returns the best absolute value function, or zero, based on type and
6815 // current absolute value function.
6816 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6817                                    unsigned AbsFunctionKind) {
6818   unsigned BestKind = 0;
6819   uint64_t ArgSize = Context.getTypeSize(ArgType);
6820   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6821        Kind = getLargerAbsoluteValueFunction(Kind)) {
6822     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6823     if (Context.getTypeSize(ParamType) >= ArgSize) {
6824       if (BestKind == 0)
6825         BestKind = Kind;
6826       else if (Context.hasSameType(ParamType, ArgType)) {
6827         BestKind = Kind;
6828         break;
6829       }
6830     }
6831   }
6832   return BestKind;
6833 }
6834 
6835 enum AbsoluteValueKind {
6836   AVK_Integer,
6837   AVK_Floating,
6838   AVK_Complex
6839 };
6840 
6841 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6842   if (T->isIntegralOrEnumerationType())
6843     return AVK_Integer;
6844   if (T->isRealFloatingType())
6845     return AVK_Floating;
6846   if (T->isAnyComplexType())
6847     return AVK_Complex;
6848 
6849   llvm_unreachable("Type not integer, floating, or complex");
6850 }
6851 
6852 // Changes the absolute value function to a different type.  Preserves whether
6853 // the function is a builtin.
6854 static unsigned changeAbsFunction(unsigned AbsKind,
6855                                   AbsoluteValueKind ValueKind) {
6856   switch (ValueKind) {
6857   case AVK_Integer:
6858     switch (AbsKind) {
6859     default:
6860       return 0;
6861     case Builtin::BI__builtin_fabsf:
6862     case Builtin::BI__builtin_fabs:
6863     case Builtin::BI__builtin_fabsl:
6864     case Builtin::BI__builtin_cabsf:
6865     case Builtin::BI__builtin_cabs:
6866     case Builtin::BI__builtin_cabsl:
6867       return Builtin::BI__builtin_abs;
6868     case Builtin::BIfabsf:
6869     case Builtin::BIfabs:
6870     case Builtin::BIfabsl:
6871     case Builtin::BIcabsf:
6872     case Builtin::BIcabs:
6873     case Builtin::BIcabsl:
6874       return Builtin::BIabs;
6875     }
6876   case AVK_Floating:
6877     switch (AbsKind) {
6878     default:
6879       return 0;
6880     case Builtin::BI__builtin_abs:
6881     case Builtin::BI__builtin_labs:
6882     case Builtin::BI__builtin_llabs:
6883     case Builtin::BI__builtin_cabsf:
6884     case Builtin::BI__builtin_cabs:
6885     case Builtin::BI__builtin_cabsl:
6886       return Builtin::BI__builtin_fabsf;
6887     case Builtin::BIabs:
6888     case Builtin::BIlabs:
6889     case Builtin::BIllabs:
6890     case Builtin::BIcabsf:
6891     case Builtin::BIcabs:
6892     case Builtin::BIcabsl:
6893       return Builtin::BIfabsf;
6894     }
6895   case AVK_Complex:
6896     switch (AbsKind) {
6897     default:
6898       return 0;
6899     case Builtin::BI__builtin_abs:
6900     case Builtin::BI__builtin_labs:
6901     case Builtin::BI__builtin_llabs:
6902     case Builtin::BI__builtin_fabsf:
6903     case Builtin::BI__builtin_fabs:
6904     case Builtin::BI__builtin_fabsl:
6905       return Builtin::BI__builtin_cabsf;
6906     case Builtin::BIabs:
6907     case Builtin::BIlabs:
6908     case Builtin::BIllabs:
6909     case Builtin::BIfabsf:
6910     case Builtin::BIfabs:
6911     case Builtin::BIfabsl:
6912       return Builtin::BIcabsf;
6913     }
6914   }
6915   llvm_unreachable("Unable to convert function");
6916 }
6917 
6918 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6919   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6920   if (!FnInfo)
6921     return 0;
6922 
6923   switch (FDecl->getBuiltinID()) {
6924   default:
6925     return 0;
6926   case Builtin::BI__builtin_abs:
6927   case Builtin::BI__builtin_fabs:
6928   case Builtin::BI__builtin_fabsf:
6929   case Builtin::BI__builtin_fabsl:
6930   case Builtin::BI__builtin_labs:
6931   case Builtin::BI__builtin_llabs:
6932   case Builtin::BI__builtin_cabs:
6933   case Builtin::BI__builtin_cabsf:
6934   case Builtin::BI__builtin_cabsl:
6935   case Builtin::BIabs:
6936   case Builtin::BIlabs:
6937   case Builtin::BIllabs:
6938   case Builtin::BIfabs:
6939   case Builtin::BIfabsf:
6940   case Builtin::BIfabsl:
6941   case Builtin::BIcabs:
6942   case Builtin::BIcabsf:
6943   case Builtin::BIcabsl:
6944     return FDecl->getBuiltinID();
6945   }
6946   llvm_unreachable("Unknown Builtin type");
6947 }
6948 
6949 // If the replacement is valid, emit a note with replacement function.
6950 // Additionally, suggest including the proper header if not already included.
6951 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6952                             unsigned AbsKind, QualType ArgType) {
6953   bool EmitHeaderHint = true;
6954   const char *HeaderName = nullptr;
6955   const char *FunctionName = nullptr;
6956   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6957     FunctionName = "std::abs";
6958     if (ArgType->isIntegralOrEnumerationType()) {
6959       HeaderName = "cstdlib";
6960     } else if (ArgType->isRealFloatingType()) {
6961       HeaderName = "cmath";
6962     } else {
6963       llvm_unreachable("Invalid Type");
6964     }
6965 
6966     // Lookup all std::abs
6967     if (NamespaceDecl *Std = S.getStdNamespace()) {
6968       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6969       R.suppressDiagnostics();
6970       S.LookupQualifiedName(R, Std);
6971 
6972       for (const auto *I : R) {
6973         const FunctionDecl *FDecl = nullptr;
6974         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6975           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6976         } else {
6977           FDecl = dyn_cast<FunctionDecl>(I);
6978         }
6979         if (!FDecl)
6980           continue;
6981 
6982         // Found std::abs(), check that they are the right ones.
6983         if (FDecl->getNumParams() != 1)
6984           continue;
6985 
6986         // Check that the parameter type can handle the argument.
6987         QualType ParamType = FDecl->getParamDecl(0)->getType();
6988         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6989             S.Context.getTypeSize(ArgType) <=
6990                 S.Context.getTypeSize(ParamType)) {
6991           // Found a function, don't need the header hint.
6992           EmitHeaderHint = false;
6993           break;
6994         }
6995       }
6996     }
6997   } else {
6998     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6999     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7000 
7001     if (HeaderName) {
7002       DeclarationName DN(&S.Context.Idents.get(FunctionName));
7003       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7004       R.suppressDiagnostics();
7005       S.LookupName(R, S.getCurScope());
7006 
7007       if (R.isSingleResult()) {
7008         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7009         if (FD && FD->getBuiltinID() == AbsKind) {
7010           EmitHeaderHint = false;
7011         } else {
7012           return;
7013         }
7014       } else if (!R.empty()) {
7015         return;
7016       }
7017     }
7018   }
7019 
7020   S.Diag(Loc, diag::note_replace_abs_function)
7021       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7022 
7023   if (!HeaderName)
7024     return;
7025 
7026   if (!EmitHeaderHint)
7027     return;
7028 
7029   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7030                                                     << FunctionName;
7031 }
7032 
7033 template <std::size_t StrLen>
7034 static bool IsStdFunction(const FunctionDecl *FDecl,
7035                           const char (&Str)[StrLen]) {
7036   if (!FDecl)
7037     return false;
7038   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7039     return false;
7040   if (!FDecl->isInStdNamespace())
7041     return false;
7042 
7043   return true;
7044 }
7045 
7046 // Warn when using the wrong abs() function.
7047 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7048                                       const FunctionDecl *FDecl) {
7049   if (Call->getNumArgs() != 1)
7050     return;
7051 
7052   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7053   bool IsStdAbs = IsStdFunction(FDecl, "abs");
7054   if (AbsKind == 0 && !IsStdAbs)
7055     return;
7056 
7057   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7058   QualType ParamType = Call->getArg(0)->getType();
7059 
7060   // Unsigned types cannot be negative.  Suggest removing the absolute value
7061   // function call.
7062   if (ArgType->isUnsignedIntegerType()) {
7063     const char *FunctionName =
7064         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7065     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7066     Diag(Call->getExprLoc(), diag::note_remove_abs)
7067         << FunctionName
7068         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7069     return;
7070   }
7071 
7072   // Taking the absolute value of a pointer is very suspicious, they probably
7073   // wanted to index into an array, dereference a pointer, call a function, etc.
7074   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7075     unsigned DiagType = 0;
7076     if (ArgType->isFunctionType())
7077       DiagType = 1;
7078     else if (ArgType->isArrayType())
7079       DiagType = 2;
7080 
7081     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7082     return;
7083   }
7084 
7085   // std::abs has overloads which prevent most of the absolute value problems
7086   // from occurring.
7087   if (IsStdAbs)
7088     return;
7089 
7090   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7091   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7092 
7093   // The argument and parameter are the same kind.  Check if they are the right
7094   // size.
7095   if (ArgValueKind == ParamValueKind) {
7096     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7097       return;
7098 
7099     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7100     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7101         << FDecl << ArgType << ParamType;
7102 
7103     if (NewAbsKind == 0)
7104       return;
7105 
7106     emitReplacement(*this, Call->getExprLoc(),
7107                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7108     return;
7109   }
7110 
7111   // ArgValueKind != ParamValueKind
7112   // The wrong type of absolute value function was used.  Attempt to find the
7113   // proper one.
7114   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7115   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7116   if (NewAbsKind == 0)
7117     return;
7118 
7119   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7120       << FDecl << ParamValueKind << ArgValueKind;
7121 
7122   emitReplacement(*this, Call->getExprLoc(),
7123                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7124 }
7125 
7126 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7127 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7128                                 const FunctionDecl *FDecl) {
7129   if (!Call || !FDecl) return;
7130 
7131   // Ignore template specializations and macros.
7132   if (inTemplateInstantiation()) return;
7133   if (Call->getExprLoc().isMacroID()) return;
7134 
7135   // Only care about the one template argument, two function parameter std::max
7136   if (Call->getNumArgs() != 2) return;
7137   if (!IsStdFunction(FDecl, "max")) return;
7138   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7139   if (!ArgList) return;
7140   if (ArgList->size() != 1) return;
7141 
7142   // Check that template type argument is unsigned integer.
7143   const auto& TA = ArgList->get(0);
7144   if (TA.getKind() != TemplateArgument::Type) return;
7145   QualType ArgType = TA.getAsType();
7146   if (!ArgType->isUnsignedIntegerType()) return;
7147 
7148   // See if either argument is a literal zero.
7149   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7150     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7151     if (!MTE) return false;
7152     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7153     if (!Num) return false;
7154     if (Num->getValue() != 0) return false;
7155     return true;
7156   };
7157 
7158   const Expr *FirstArg = Call->getArg(0);
7159   const Expr *SecondArg = Call->getArg(1);
7160   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7161   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7162 
7163   // Only warn when exactly one argument is zero.
7164   if (IsFirstArgZero == IsSecondArgZero) return;
7165 
7166   SourceRange FirstRange = FirstArg->getSourceRange();
7167   SourceRange SecondRange = SecondArg->getSourceRange();
7168 
7169   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7170 
7171   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7172       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7173 
7174   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7175   SourceRange RemovalRange;
7176   if (IsFirstArgZero) {
7177     RemovalRange = SourceRange(FirstRange.getBegin(),
7178                                SecondRange.getBegin().getLocWithOffset(-1));
7179   } else {
7180     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7181                                SecondRange.getEnd());
7182   }
7183 
7184   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7185         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7186         << FixItHint::CreateRemoval(RemovalRange);
7187 }
7188 
7189 //===--- CHECK: Standard memory functions ---------------------------------===//
7190 
7191 /// \brief Takes the expression passed to the size_t parameter of functions
7192 /// such as memcmp, strncat, etc and warns if it's a comparison.
7193 ///
7194 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7195 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7196                                            IdentifierInfo *FnName,
7197                                            SourceLocation FnLoc,
7198                                            SourceLocation RParenLoc) {
7199   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7200   if (!Size)
7201     return false;
7202 
7203   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7204   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7205     return false;
7206 
7207   SourceRange SizeRange = Size->getSourceRange();
7208   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7209       << SizeRange << FnName;
7210   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7211       << FnName << FixItHint::CreateInsertion(
7212                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7213       << FixItHint::CreateRemoval(RParenLoc);
7214   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7215       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7216       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7217                                     ")");
7218 
7219   return true;
7220 }
7221 
7222 /// \brief Determine whether the given type is or contains a dynamic class type
7223 /// (e.g., whether it has a vtable).
7224 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7225                                                      bool &IsContained) {
7226   // Look through array types while ignoring qualifiers.
7227   const Type *Ty = T->getBaseElementTypeUnsafe();
7228   IsContained = false;
7229 
7230   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7231   RD = RD ? RD->getDefinition() : nullptr;
7232   if (!RD || RD->isInvalidDecl())
7233     return nullptr;
7234 
7235   if (RD->isDynamicClass())
7236     return RD;
7237 
7238   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7239   // It's impossible for a class to transitively contain itself by value, so
7240   // infinite recursion is impossible.
7241   for (auto *FD : RD->fields()) {
7242     bool SubContained;
7243     if (const CXXRecordDecl *ContainedRD =
7244             getContainedDynamicClass(FD->getType(), SubContained)) {
7245       IsContained = true;
7246       return ContainedRD;
7247     }
7248   }
7249 
7250   return nullptr;
7251 }
7252 
7253 /// \brief If E is a sizeof expression, returns its argument expression,
7254 /// otherwise returns NULL.
7255 static const Expr *getSizeOfExprArg(const Expr *E) {
7256   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7257       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7258     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7259       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7260 
7261   return nullptr;
7262 }
7263 
7264 /// \brief If E is a sizeof expression, returns its argument type.
7265 static QualType getSizeOfArgType(const Expr *E) {
7266   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7267       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7268     if (SizeOf->getKind() == clang::UETT_SizeOf)
7269       return SizeOf->getTypeOfArgument();
7270 
7271   return QualType();
7272 }
7273 
7274 /// \brief Check for dangerous or invalid arguments to memset().
7275 ///
7276 /// This issues warnings on known problematic, dangerous or unspecified
7277 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7278 /// function calls.
7279 ///
7280 /// \param Call The call expression to diagnose.
7281 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7282                                    unsigned BId,
7283                                    IdentifierInfo *FnName) {
7284   assert(BId != 0);
7285 
7286   // It is possible to have a non-standard definition of memset.  Validate
7287   // we have enough arguments, and if not, abort further checking.
7288   unsigned ExpectedNumArgs =
7289       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7290   if (Call->getNumArgs() < ExpectedNumArgs)
7291     return;
7292 
7293   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7294                       BId == Builtin::BIstrndup ? 1 : 2);
7295   unsigned LenArg =
7296       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7297   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7298 
7299   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7300                                      Call->getLocStart(), Call->getRParenLoc()))
7301     return;
7302 
7303   // We have special checking when the length is a sizeof expression.
7304   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7305   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7306   llvm::FoldingSetNodeID SizeOfArgID;
7307 
7308   // Although widely used, 'bzero' is not a standard function. Be more strict
7309   // with the argument types before allowing diagnostics and only allow the
7310   // form bzero(ptr, sizeof(...)).
7311   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7312   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7313     return;
7314 
7315   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7316     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7317     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7318 
7319     QualType DestTy = Dest->getType();
7320     QualType PointeeTy;
7321     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7322       PointeeTy = DestPtrTy->getPointeeType();
7323 
7324       // Never warn about void type pointers. This can be used to suppress
7325       // false positives.
7326       if (PointeeTy->isVoidType())
7327         continue;
7328 
7329       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7330       // actually comparing the expressions for equality. Because computing the
7331       // expression IDs can be expensive, we only do this if the diagnostic is
7332       // enabled.
7333       if (SizeOfArg &&
7334           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7335                            SizeOfArg->getExprLoc())) {
7336         // We only compute IDs for expressions if the warning is enabled, and
7337         // cache the sizeof arg's ID.
7338         if (SizeOfArgID == llvm::FoldingSetNodeID())
7339           SizeOfArg->Profile(SizeOfArgID, Context, true);
7340         llvm::FoldingSetNodeID DestID;
7341         Dest->Profile(DestID, Context, true);
7342         if (DestID == SizeOfArgID) {
7343           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7344           //       over sizeof(src) as well.
7345           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7346           StringRef ReadableName = FnName->getName();
7347 
7348           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7349             if (UnaryOp->getOpcode() == UO_AddrOf)
7350               ActionIdx = 1; // If its an address-of operator, just remove it.
7351           if (!PointeeTy->isIncompleteType() &&
7352               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7353             ActionIdx = 2; // If the pointee's size is sizeof(char),
7354                            // suggest an explicit length.
7355 
7356           // If the function is defined as a builtin macro, do not show macro
7357           // expansion.
7358           SourceLocation SL = SizeOfArg->getExprLoc();
7359           SourceRange DSR = Dest->getSourceRange();
7360           SourceRange SSR = SizeOfArg->getSourceRange();
7361           SourceManager &SM = getSourceManager();
7362 
7363           if (SM.isMacroArgExpansion(SL)) {
7364             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7365             SL = SM.getSpellingLoc(SL);
7366             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7367                              SM.getSpellingLoc(DSR.getEnd()));
7368             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7369                              SM.getSpellingLoc(SSR.getEnd()));
7370           }
7371 
7372           DiagRuntimeBehavior(SL, SizeOfArg,
7373                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7374                                 << ReadableName
7375                                 << PointeeTy
7376                                 << DestTy
7377                                 << DSR
7378                                 << SSR);
7379           DiagRuntimeBehavior(SL, SizeOfArg,
7380                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7381                                 << ActionIdx
7382                                 << SSR);
7383 
7384           break;
7385         }
7386       }
7387 
7388       // Also check for cases where the sizeof argument is the exact same
7389       // type as the memory argument, and where it points to a user-defined
7390       // record type.
7391       if (SizeOfArgTy != QualType()) {
7392         if (PointeeTy->isRecordType() &&
7393             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7394           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7395                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7396                                 << FnName << SizeOfArgTy << ArgIdx
7397                                 << PointeeTy << Dest->getSourceRange()
7398                                 << LenExpr->getSourceRange());
7399           break;
7400         }
7401       }
7402     } else if (DestTy->isArrayType()) {
7403       PointeeTy = DestTy;
7404     }
7405 
7406     if (PointeeTy == QualType())
7407       continue;
7408 
7409     // Always complain about dynamic classes.
7410     bool IsContained;
7411     if (const CXXRecordDecl *ContainedRD =
7412             getContainedDynamicClass(PointeeTy, IsContained)) {
7413 
7414       unsigned OperationType = 0;
7415       // "overwritten" if we're warning about the destination for any call
7416       // but memcmp; otherwise a verb appropriate to the call.
7417       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7418         if (BId == Builtin::BImemcpy)
7419           OperationType = 1;
7420         else if(BId == Builtin::BImemmove)
7421           OperationType = 2;
7422         else if (BId == Builtin::BImemcmp)
7423           OperationType = 3;
7424       }
7425 
7426       DiagRuntimeBehavior(
7427         Dest->getExprLoc(), Dest,
7428         PDiag(diag::warn_dyn_class_memaccess)
7429           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7430           << FnName << IsContained << ContainedRD << OperationType
7431           << Call->getCallee()->getSourceRange());
7432     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7433              BId != Builtin::BImemset)
7434       DiagRuntimeBehavior(
7435         Dest->getExprLoc(), Dest,
7436         PDiag(diag::warn_arc_object_memaccess)
7437           << ArgIdx << FnName << PointeeTy
7438           << Call->getCallee()->getSourceRange());
7439     else
7440       continue;
7441 
7442     DiagRuntimeBehavior(
7443       Dest->getExprLoc(), Dest,
7444       PDiag(diag::note_bad_memaccess_silence)
7445         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7446     break;
7447   }
7448 }
7449 
7450 // A little helper routine: ignore addition and subtraction of integer literals.
7451 // This intentionally does not ignore all integer constant expressions because
7452 // we don't want to remove sizeof().
7453 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7454   Ex = Ex->IgnoreParenCasts();
7455 
7456   for (;;) {
7457     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7458     if (!BO || !BO->isAdditiveOp())
7459       break;
7460 
7461     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7462     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7463 
7464     if (isa<IntegerLiteral>(RHS))
7465       Ex = LHS;
7466     else if (isa<IntegerLiteral>(LHS))
7467       Ex = RHS;
7468     else
7469       break;
7470   }
7471 
7472   return Ex;
7473 }
7474 
7475 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7476                                                       ASTContext &Context) {
7477   // Only handle constant-sized or VLAs, but not flexible members.
7478   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7479     // Only issue the FIXIT for arrays of size > 1.
7480     if (CAT->getSize().getSExtValue() <= 1)
7481       return false;
7482   } else if (!Ty->isVariableArrayType()) {
7483     return false;
7484   }
7485   return true;
7486 }
7487 
7488 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7489 // be the size of the source, instead of the destination.
7490 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7491                                     IdentifierInfo *FnName) {
7492 
7493   // Don't crash if the user has the wrong number of arguments
7494   unsigned NumArgs = Call->getNumArgs();
7495   if ((NumArgs != 3) && (NumArgs != 4))
7496     return;
7497 
7498   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7499   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7500   const Expr *CompareWithSrc = nullptr;
7501 
7502   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7503                                      Call->getLocStart(), Call->getRParenLoc()))
7504     return;
7505 
7506   // Look for 'strlcpy(dst, x, sizeof(x))'
7507   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7508     CompareWithSrc = Ex;
7509   else {
7510     // Look for 'strlcpy(dst, x, strlen(x))'
7511     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7512       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7513           SizeCall->getNumArgs() == 1)
7514         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7515     }
7516   }
7517 
7518   if (!CompareWithSrc)
7519     return;
7520 
7521   // Determine if the argument to sizeof/strlen is equal to the source
7522   // argument.  In principle there's all kinds of things you could do
7523   // here, for instance creating an == expression and evaluating it with
7524   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7525   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7526   if (!SrcArgDRE)
7527     return;
7528 
7529   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7530   if (!CompareWithSrcDRE ||
7531       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7532     return;
7533 
7534   const Expr *OriginalSizeArg = Call->getArg(2);
7535   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7536     << OriginalSizeArg->getSourceRange() << FnName;
7537 
7538   // Output a FIXIT hint if the destination is an array (rather than a
7539   // pointer to an array).  This could be enhanced to handle some
7540   // pointers if we know the actual size, like if DstArg is 'array+2'
7541   // we could say 'sizeof(array)-2'.
7542   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7543   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7544     return;
7545 
7546   SmallString<128> sizeString;
7547   llvm::raw_svector_ostream OS(sizeString);
7548   OS << "sizeof(";
7549   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7550   OS << ")";
7551 
7552   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7553     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7554                                     OS.str());
7555 }
7556 
7557 /// Check if two expressions refer to the same declaration.
7558 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7559   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7560     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7561       return D1->getDecl() == D2->getDecl();
7562   return false;
7563 }
7564 
7565 static const Expr *getStrlenExprArg(const Expr *E) {
7566   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7567     const FunctionDecl *FD = CE->getDirectCallee();
7568     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7569       return nullptr;
7570     return CE->getArg(0)->IgnoreParenCasts();
7571   }
7572   return nullptr;
7573 }
7574 
7575 // Warn on anti-patterns as the 'size' argument to strncat.
7576 // The correct size argument should look like following:
7577 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7578 void Sema::CheckStrncatArguments(const CallExpr *CE,
7579                                  IdentifierInfo *FnName) {
7580   // Don't crash if the user has the wrong number of arguments.
7581   if (CE->getNumArgs() < 3)
7582     return;
7583   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7584   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7585   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7586 
7587   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7588                                      CE->getRParenLoc()))
7589     return;
7590 
7591   // Identify common expressions, which are wrongly used as the size argument
7592   // to strncat and may lead to buffer overflows.
7593   unsigned PatternType = 0;
7594   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7595     // - sizeof(dst)
7596     if (referToTheSameDecl(SizeOfArg, DstArg))
7597       PatternType = 1;
7598     // - sizeof(src)
7599     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7600       PatternType = 2;
7601   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7602     if (BE->getOpcode() == BO_Sub) {
7603       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7604       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7605       // - sizeof(dst) - strlen(dst)
7606       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7607           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7608         PatternType = 1;
7609       // - sizeof(src) - (anything)
7610       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7611         PatternType = 2;
7612     }
7613   }
7614 
7615   if (PatternType == 0)
7616     return;
7617 
7618   // Generate the diagnostic.
7619   SourceLocation SL = LenArg->getLocStart();
7620   SourceRange SR = LenArg->getSourceRange();
7621   SourceManager &SM = getSourceManager();
7622 
7623   // If the function is defined as a builtin macro, do not show macro expansion.
7624   if (SM.isMacroArgExpansion(SL)) {
7625     SL = SM.getSpellingLoc(SL);
7626     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7627                      SM.getSpellingLoc(SR.getEnd()));
7628   }
7629 
7630   // Check if the destination is an array (rather than a pointer to an array).
7631   QualType DstTy = DstArg->getType();
7632   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7633                                                                     Context);
7634   if (!isKnownSizeArray) {
7635     if (PatternType == 1)
7636       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7637     else
7638       Diag(SL, diag::warn_strncat_src_size) << SR;
7639     return;
7640   }
7641 
7642   if (PatternType == 1)
7643     Diag(SL, diag::warn_strncat_large_size) << SR;
7644   else
7645     Diag(SL, diag::warn_strncat_src_size) << SR;
7646 
7647   SmallString<128> sizeString;
7648   llvm::raw_svector_ostream OS(sizeString);
7649   OS << "sizeof(";
7650   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7651   OS << ") - ";
7652   OS << "strlen(";
7653   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7654   OS << ") - 1";
7655 
7656   Diag(SL, diag::note_strncat_wrong_size)
7657     << FixItHint::CreateReplacement(SR, OS.str());
7658 }
7659 
7660 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7661 
7662 static const Expr *EvalVal(const Expr *E,
7663                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7664                            const Decl *ParentDecl);
7665 static const Expr *EvalAddr(const Expr *E,
7666                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7667                             const Decl *ParentDecl);
7668 
7669 /// CheckReturnStackAddr - Check if a return statement returns the address
7670 ///   of a stack variable.
7671 static void
7672 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7673                      SourceLocation ReturnLoc) {
7674 
7675   const Expr *stackE = nullptr;
7676   SmallVector<const DeclRefExpr *, 8> refVars;
7677 
7678   // Perform checking for returned stack addresses, local blocks,
7679   // label addresses or references to temporaries.
7680   if (lhsType->isPointerType() ||
7681       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7682     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7683   } else if (lhsType->isReferenceType()) {
7684     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7685   }
7686 
7687   if (!stackE)
7688     return; // Nothing suspicious was found.
7689 
7690   // Parameters are initialized in the calling scope, so taking the address
7691   // of a parameter reference doesn't need a warning.
7692   for (auto *DRE : refVars)
7693     if (isa<ParmVarDecl>(DRE->getDecl()))
7694       return;
7695 
7696   SourceLocation diagLoc;
7697   SourceRange diagRange;
7698   if (refVars.empty()) {
7699     diagLoc = stackE->getLocStart();
7700     diagRange = stackE->getSourceRange();
7701   } else {
7702     // We followed through a reference variable. 'stackE' contains the
7703     // problematic expression but we will warn at the return statement pointing
7704     // at the reference variable. We will later display the "trail" of
7705     // reference variables using notes.
7706     diagLoc = refVars[0]->getLocStart();
7707     diagRange = refVars[0]->getSourceRange();
7708   }
7709 
7710   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7711     // address of local var
7712     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7713      << DR->getDecl()->getDeclName() << diagRange;
7714   } else if (isa<BlockExpr>(stackE)) { // local block.
7715     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7716   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7717     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7718   } else { // local temporary.
7719     // If there is an LValue->RValue conversion, then the value of the
7720     // reference type is used, not the reference.
7721     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7722       if (ICE->getCastKind() == CK_LValueToRValue) {
7723         return;
7724       }
7725     }
7726     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7727      << lhsType->isReferenceType() << diagRange;
7728   }
7729 
7730   // Display the "trail" of reference variables that we followed until we
7731   // found the problematic expression using notes.
7732   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7733     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7734     // If this var binds to another reference var, show the range of the next
7735     // var, otherwise the var binds to the problematic expression, in which case
7736     // show the range of the expression.
7737     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7738                                     : stackE->getSourceRange();
7739     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7740         << VD->getDeclName() << range;
7741   }
7742 }
7743 
7744 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7745 ///  check if the expression in a return statement evaluates to an address
7746 ///  to a location on the stack, a local block, an address of a label, or a
7747 ///  reference to local temporary. The recursion is used to traverse the
7748 ///  AST of the return expression, with recursion backtracking when we
7749 ///  encounter a subexpression that (1) clearly does not lead to one of the
7750 ///  above problematic expressions (2) is something we cannot determine leads to
7751 ///  a problematic expression based on such local checking.
7752 ///
7753 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7754 ///  the expression that they point to. Such variables are added to the
7755 ///  'refVars' vector so that we know what the reference variable "trail" was.
7756 ///
7757 ///  EvalAddr processes expressions that are pointers that are used as
7758 ///  references (and not L-values).  EvalVal handles all other values.
7759 ///  At the base case of the recursion is a check for the above problematic
7760 ///  expressions.
7761 ///
7762 ///  This implementation handles:
7763 ///
7764 ///   * pointer-to-pointer casts
7765 ///   * implicit conversions from array references to pointers
7766 ///   * taking the address of fields
7767 ///   * arbitrary interplay between "&" and "*" operators
7768 ///   * pointer arithmetic from an address of a stack variable
7769 ///   * taking the address of an array element where the array is on the stack
7770 static const Expr *EvalAddr(const Expr *E,
7771                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7772                             const Decl *ParentDecl) {
7773   if (E->isTypeDependent())
7774     return nullptr;
7775 
7776   // We should only be called for evaluating pointer expressions.
7777   assert((E->getType()->isAnyPointerType() ||
7778           E->getType()->isBlockPointerType() ||
7779           E->getType()->isObjCQualifiedIdType()) &&
7780          "EvalAddr only works on pointers");
7781 
7782   E = E->IgnoreParens();
7783 
7784   // Our "symbolic interpreter" is just a dispatch off the currently
7785   // viewed AST node.  We then recursively traverse the AST by calling
7786   // EvalAddr and EvalVal appropriately.
7787   switch (E->getStmtClass()) {
7788   case Stmt::DeclRefExprClass: {
7789     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7790 
7791     // If we leave the immediate function, the lifetime isn't about to end.
7792     if (DR->refersToEnclosingVariableOrCapture())
7793       return nullptr;
7794 
7795     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7796       // If this is a reference variable, follow through to the expression that
7797       // it points to.
7798       if (V->hasLocalStorage() &&
7799           V->getType()->isReferenceType() && V->hasInit()) {
7800         // Add the reference variable to the "trail".
7801         refVars.push_back(DR);
7802         return EvalAddr(V->getInit(), refVars, ParentDecl);
7803       }
7804 
7805     return nullptr;
7806   }
7807 
7808   case Stmt::UnaryOperatorClass: {
7809     // The only unary operator that make sense to handle here
7810     // is AddrOf.  All others don't make sense as pointers.
7811     const UnaryOperator *U = cast<UnaryOperator>(E);
7812 
7813     if (U->getOpcode() == UO_AddrOf)
7814       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7815     return nullptr;
7816   }
7817 
7818   case Stmt::BinaryOperatorClass: {
7819     // Handle pointer arithmetic.  All other binary operators are not valid
7820     // in this context.
7821     const BinaryOperator *B = cast<BinaryOperator>(E);
7822     BinaryOperatorKind op = B->getOpcode();
7823 
7824     if (op != BO_Add && op != BO_Sub)
7825       return nullptr;
7826 
7827     const Expr *Base = B->getLHS();
7828 
7829     // Determine which argument is the real pointer base.  It could be
7830     // the RHS argument instead of the LHS.
7831     if (!Base->getType()->isPointerType())
7832       Base = B->getRHS();
7833 
7834     assert(Base->getType()->isPointerType());
7835     return EvalAddr(Base, refVars, ParentDecl);
7836   }
7837 
7838   // For conditional operators we need to see if either the LHS or RHS are
7839   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7840   case Stmt::ConditionalOperatorClass: {
7841     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7842 
7843     // Handle the GNU extension for missing LHS.
7844     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7845     if (const Expr *LHSExpr = C->getLHS()) {
7846       // In C++, we can have a throw-expression, which has 'void' type.
7847       if (!LHSExpr->getType()->isVoidType())
7848         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7849           return LHS;
7850     }
7851 
7852     // In C++, we can have a throw-expression, which has 'void' type.
7853     if (C->getRHS()->getType()->isVoidType())
7854       return nullptr;
7855 
7856     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7857   }
7858 
7859   case Stmt::BlockExprClass:
7860     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7861       return E; // local block.
7862     return nullptr;
7863 
7864   case Stmt::AddrLabelExprClass:
7865     return E; // address of label.
7866 
7867   case Stmt::ExprWithCleanupsClass:
7868     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7869                     ParentDecl);
7870 
7871   // For casts, we need to handle conversions from arrays to
7872   // pointer values, and pointer-to-pointer conversions.
7873   case Stmt::ImplicitCastExprClass:
7874   case Stmt::CStyleCastExprClass:
7875   case Stmt::CXXFunctionalCastExprClass:
7876   case Stmt::ObjCBridgedCastExprClass:
7877   case Stmt::CXXStaticCastExprClass:
7878   case Stmt::CXXDynamicCastExprClass:
7879   case Stmt::CXXConstCastExprClass:
7880   case Stmt::CXXReinterpretCastExprClass: {
7881     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7882     switch (cast<CastExpr>(E)->getCastKind()) {
7883     case CK_LValueToRValue:
7884     case CK_NoOp:
7885     case CK_BaseToDerived:
7886     case CK_DerivedToBase:
7887     case CK_UncheckedDerivedToBase:
7888     case CK_Dynamic:
7889     case CK_CPointerToObjCPointerCast:
7890     case CK_BlockPointerToObjCPointerCast:
7891     case CK_AnyPointerToBlockPointerCast:
7892       return EvalAddr(SubExpr, refVars, ParentDecl);
7893 
7894     case CK_ArrayToPointerDecay:
7895       return EvalVal(SubExpr, refVars, ParentDecl);
7896 
7897     case CK_BitCast:
7898       if (SubExpr->getType()->isAnyPointerType() ||
7899           SubExpr->getType()->isBlockPointerType() ||
7900           SubExpr->getType()->isObjCQualifiedIdType())
7901         return EvalAddr(SubExpr, refVars, ParentDecl);
7902       else
7903         return nullptr;
7904 
7905     default:
7906       return nullptr;
7907     }
7908   }
7909 
7910   case Stmt::MaterializeTemporaryExprClass:
7911     if (const Expr *Result =
7912             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7913                      refVars, ParentDecl))
7914       return Result;
7915     return E;
7916 
7917   // Everything else: we simply don't reason about them.
7918   default:
7919     return nullptr;
7920   }
7921 }
7922 
7923 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7924 ///   See the comments for EvalAddr for more details.
7925 static const Expr *EvalVal(const Expr *E,
7926                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7927                            const Decl *ParentDecl) {
7928   do {
7929     // We should only be called for evaluating non-pointer expressions, or
7930     // expressions with a pointer type that are not used as references but
7931     // instead
7932     // are l-values (e.g., DeclRefExpr with a pointer type).
7933 
7934     // Our "symbolic interpreter" is just a dispatch off the currently
7935     // viewed AST node.  We then recursively traverse the AST by calling
7936     // EvalAddr and EvalVal appropriately.
7937 
7938     E = E->IgnoreParens();
7939     switch (E->getStmtClass()) {
7940     case Stmt::ImplicitCastExprClass: {
7941       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7942       if (IE->getValueKind() == VK_LValue) {
7943         E = IE->getSubExpr();
7944         continue;
7945       }
7946       return nullptr;
7947     }
7948 
7949     case Stmt::ExprWithCleanupsClass:
7950       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7951                      ParentDecl);
7952 
7953     case Stmt::DeclRefExprClass: {
7954       // When we hit a DeclRefExpr we are looking at code that refers to a
7955       // variable's name. If it's not a reference variable we check if it has
7956       // local storage within the function, and if so, return the expression.
7957       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7958 
7959       // If we leave the immediate function, the lifetime isn't about to end.
7960       if (DR->refersToEnclosingVariableOrCapture())
7961         return nullptr;
7962 
7963       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7964         // Check if it refers to itself, e.g. "int& i = i;".
7965         if (V == ParentDecl)
7966           return DR;
7967 
7968         if (V->hasLocalStorage()) {
7969           if (!V->getType()->isReferenceType())
7970             return DR;
7971 
7972           // Reference variable, follow through to the expression that
7973           // it points to.
7974           if (V->hasInit()) {
7975             // Add the reference variable to the "trail".
7976             refVars.push_back(DR);
7977             return EvalVal(V->getInit(), refVars, V);
7978           }
7979         }
7980       }
7981 
7982       return nullptr;
7983     }
7984 
7985     case Stmt::UnaryOperatorClass: {
7986       // The only unary operator that make sense to handle here
7987       // is Deref.  All others don't resolve to a "name."  This includes
7988       // handling all sorts of rvalues passed to a unary operator.
7989       const UnaryOperator *U = cast<UnaryOperator>(E);
7990 
7991       if (U->getOpcode() == UO_Deref)
7992         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7993 
7994       return nullptr;
7995     }
7996 
7997     case Stmt::ArraySubscriptExprClass: {
7998       // Array subscripts are potential references to data on the stack.  We
7999       // retrieve the DeclRefExpr* for the array variable if it indeed
8000       // has local storage.
8001       const auto *ASE = cast<ArraySubscriptExpr>(E);
8002       if (ASE->isTypeDependent())
8003         return nullptr;
8004       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8005     }
8006 
8007     case Stmt::OMPArraySectionExprClass: {
8008       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8009                       ParentDecl);
8010     }
8011 
8012     case Stmt::ConditionalOperatorClass: {
8013       // For conditional operators we need to see if either the LHS or RHS are
8014       // non-NULL Expr's.  If one is non-NULL, we return it.
8015       const ConditionalOperator *C = cast<ConditionalOperator>(E);
8016 
8017       // Handle the GNU extension for missing LHS.
8018       if (const Expr *LHSExpr = C->getLHS()) {
8019         // In C++, we can have a throw-expression, which has 'void' type.
8020         if (!LHSExpr->getType()->isVoidType())
8021           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8022             return LHS;
8023       }
8024 
8025       // In C++, we can have a throw-expression, which has 'void' type.
8026       if (C->getRHS()->getType()->isVoidType())
8027         return nullptr;
8028 
8029       return EvalVal(C->getRHS(), refVars, ParentDecl);
8030     }
8031 
8032     // Accesses to members are potential references to data on the stack.
8033     case Stmt::MemberExprClass: {
8034       const MemberExpr *M = cast<MemberExpr>(E);
8035 
8036       // Check for indirect access.  We only want direct field accesses.
8037       if (M->isArrow())
8038         return nullptr;
8039 
8040       // Check whether the member type is itself a reference, in which case
8041       // we're not going to refer to the member, but to what the member refers
8042       // to.
8043       if (M->getMemberDecl()->getType()->isReferenceType())
8044         return nullptr;
8045 
8046       return EvalVal(M->getBase(), refVars, ParentDecl);
8047     }
8048 
8049     case Stmt::MaterializeTemporaryExprClass:
8050       if (const Expr *Result =
8051               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8052                       refVars, ParentDecl))
8053         return Result;
8054       return E;
8055 
8056     default:
8057       // Check that we don't return or take the address of a reference to a
8058       // temporary. This is only useful in C++.
8059       if (!E->isTypeDependent() && E->isRValue())
8060         return E;
8061 
8062       // Everything else: we simply don't reason about them.
8063       return nullptr;
8064     }
8065   } while (true);
8066 }
8067 
8068 void
8069 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8070                          SourceLocation ReturnLoc,
8071                          bool isObjCMethod,
8072                          const AttrVec *Attrs,
8073                          const FunctionDecl *FD) {
8074   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8075 
8076   // Check if the return value is null but should not be.
8077   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8078        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8079       CheckNonNullExpr(*this, RetValExp))
8080     Diag(ReturnLoc, diag::warn_null_ret)
8081       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8082 
8083   // C++11 [basic.stc.dynamic.allocation]p4:
8084   //   If an allocation function declared with a non-throwing
8085   //   exception-specification fails to allocate storage, it shall return
8086   //   a null pointer. Any other allocation function that fails to allocate
8087   //   storage shall indicate failure only by throwing an exception [...]
8088   if (FD) {
8089     OverloadedOperatorKind Op = FD->getOverloadedOperator();
8090     if (Op == OO_New || Op == OO_Array_New) {
8091       const FunctionProtoType *Proto
8092         = FD->getType()->castAs<FunctionProtoType>();
8093       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8094           CheckNonNullExpr(*this, RetValExp))
8095         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8096           << FD << getLangOpts().CPlusPlus11;
8097     }
8098   }
8099 }
8100 
8101 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8102 
8103 /// Check for comparisons of floating point operands using != and ==.
8104 /// Issue a warning if these are no self-comparisons, as they are not likely
8105 /// to do what the programmer intended.
8106 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8107   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8108   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8109 
8110   // Special case: check for x == x (which is OK).
8111   // Do not emit warnings for such cases.
8112   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8113     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8114       if (DRL->getDecl() == DRR->getDecl())
8115         return;
8116 
8117   // Special case: check for comparisons against literals that can be exactly
8118   //  represented by APFloat.  In such cases, do not emit a warning.  This
8119   //  is a heuristic: often comparison against such literals are used to
8120   //  detect if a value in a variable has not changed.  This clearly can
8121   //  lead to false negatives.
8122   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8123     if (FLL->isExact())
8124       return;
8125   } else
8126     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8127       if (FLR->isExact())
8128         return;
8129 
8130   // Check for comparisons with builtin types.
8131   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8132     if (CL->getBuiltinCallee())
8133       return;
8134 
8135   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8136     if (CR->getBuiltinCallee())
8137       return;
8138 
8139   // Emit the diagnostic.
8140   Diag(Loc, diag::warn_floatingpoint_eq)
8141     << LHS->getSourceRange() << RHS->getSourceRange();
8142 }
8143 
8144 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8145 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8146 
8147 namespace {
8148 
8149 /// Structure recording the 'active' range of an integer-valued
8150 /// expression.
8151 struct IntRange {
8152   /// The number of bits active in the int.
8153   unsigned Width;
8154 
8155   /// True if the int is known not to have negative values.
8156   bool NonNegative;
8157 
8158   IntRange(unsigned Width, bool NonNegative)
8159     : Width(Width), NonNegative(NonNegative)
8160   {}
8161 
8162   /// Returns the range of the bool type.
8163   static IntRange forBoolType() {
8164     return IntRange(1, true);
8165   }
8166 
8167   /// Returns the range of an opaque value of the given integral type.
8168   static IntRange forValueOfType(ASTContext &C, QualType T) {
8169     return forValueOfCanonicalType(C,
8170                           T->getCanonicalTypeInternal().getTypePtr());
8171   }
8172 
8173   /// Returns the range of an opaque value of a canonical integral type.
8174   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8175     assert(T->isCanonicalUnqualified());
8176 
8177     if (const VectorType *VT = dyn_cast<VectorType>(T))
8178       T = VT->getElementType().getTypePtr();
8179     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8180       T = CT->getElementType().getTypePtr();
8181     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8182       T = AT->getValueType().getTypePtr();
8183 
8184     if (!C.getLangOpts().CPlusPlus) {
8185       // For enum types in C code, use the underlying datatype.
8186       if (const EnumType *ET = dyn_cast<EnumType>(T))
8187         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8188     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8189       // For enum types in C++, use the known bit width of the enumerators.
8190       EnumDecl *Enum = ET->getDecl();
8191       // In C++11, enums without definitions can have an explicitly specified
8192       // underlying type.  Use this type to compute the range.
8193       if (!Enum->isCompleteDefinition())
8194         return IntRange(C.getIntWidth(QualType(T, 0)),
8195                         !ET->isSignedIntegerOrEnumerationType());
8196 
8197       unsigned NumPositive = Enum->getNumPositiveBits();
8198       unsigned NumNegative = Enum->getNumNegativeBits();
8199 
8200       if (NumNegative == 0)
8201         return IntRange(NumPositive, true/*NonNegative*/);
8202       else
8203         return IntRange(std::max(NumPositive + 1, NumNegative),
8204                         false/*NonNegative*/);
8205     }
8206 
8207     const BuiltinType *BT = cast<BuiltinType>(T);
8208     assert(BT->isInteger());
8209 
8210     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8211   }
8212 
8213   /// Returns the "target" range of a canonical integral type, i.e.
8214   /// the range of values expressible in the type.
8215   ///
8216   /// This matches forValueOfCanonicalType except that enums have the
8217   /// full range of their type, not the range of their enumerators.
8218   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8219     assert(T->isCanonicalUnqualified());
8220 
8221     if (const VectorType *VT = dyn_cast<VectorType>(T))
8222       T = VT->getElementType().getTypePtr();
8223     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8224       T = CT->getElementType().getTypePtr();
8225     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8226       T = AT->getValueType().getTypePtr();
8227     if (const EnumType *ET = dyn_cast<EnumType>(T))
8228       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8229 
8230     const BuiltinType *BT = cast<BuiltinType>(T);
8231     assert(BT->isInteger());
8232 
8233     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8234   }
8235 
8236   /// Returns the supremum of two ranges: i.e. their conservative merge.
8237   static IntRange join(IntRange L, IntRange R) {
8238     return IntRange(std::max(L.Width, R.Width),
8239                     L.NonNegative && R.NonNegative);
8240   }
8241 
8242   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8243   static IntRange meet(IntRange L, IntRange R) {
8244     return IntRange(std::min(L.Width, R.Width),
8245                     L.NonNegative || R.NonNegative);
8246   }
8247 };
8248 
8249 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
8250   if (value.isSigned() && value.isNegative())
8251     return IntRange(value.getMinSignedBits(), false);
8252 
8253   if (value.getBitWidth() > MaxWidth)
8254     value = value.trunc(MaxWidth);
8255 
8256   // isNonNegative() just checks the sign bit without considering
8257   // signedness.
8258   return IntRange(value.getActiveBits(), true);
8259 }
8260 
8261 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8262                        unsigned MaxWidth) {
8263   if (result.isInt())
8264     return GetValueRange(C, result.getInt(), MaxWidth);
8265 
8266   if (result.isVector()) {
8267     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8268     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8269       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8270       R = IntRange::join(R, El);
8271     }
8272     return R;
8273   }
8274 
8275   if (result.isComplexInt()) {
8276     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8277     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8278     return IntRange::join(R, I);
8279   }
8280 
8281   // This can happen with lossless casts to intptr_t of "based" lvalues.
8282   // Assume it might use arbitrary bits.
8283   // FIXME: The only reason we need to pass the type in here is to get
8284   // the sign right on this one case.  It would be nice if APValue
8285   // preserved this.
8286   assert(result.isLValue() || result.isAddrLabelDiff());
8287   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8288 }
8289 
8290 QualType GetExprType(const Expr *E) {
8291   QualType Ty = E->getType();
8292   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8293     Ty = AtomicRHS->getValueType();
8294   return Ty;
8295 }
8296 
8297 /// Pseudo-evaluate the given integer expression, estimating the
8298 /// range of values it might take.
8299 ///
8300 /// \param MaxWidth - the width to which the value will be truncated
8301 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8302   E = E->IgnoreParens();
8303 
8304   // Try a full evaluation first.
8305   Expr::EvalResult result;
8306   if (E->EvaluateAsRValue(result, C))
8307     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8308 
8309   // I think we only want to look through implicit casts here; if the
8310   // user has an explicit widening cast, we should treat the value as
8311   // being of the new, wider type.
8312   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8313     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8314       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8315 
8316     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8317 
8318     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8319                          CE->getCastKind() == CK_BooleanToSignedIntegral;
8320 
8321     // Assume that non-integer casts can span the full range of the type.
8322     if (!isIntegerCast)
8323       return OutputTypeRange;
8324 
8325     IntRange SubRange
8326       = GetExprRange(C, CE->getSubExpr(),
8327                      std::min(MaxWidth, OutputTypeRange.Width));
8328 
8329     // Bail out if the subexpr's range is as wide as the cast type.
8330     if (SubRange.Width >= OutputTypeRange.Width)
8331       return OutputTypeRange;
8332 
8333     // Otherwise, we take the smaller width, and we're non-negative if
8334     // either the output type or the subexpr is.
8335     return IntRange(SubRange.Width,
8336                     SubRange.NonNegative || OutputTypeRange.NonNegative);
8337   }
8338 
8339   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8340     // If we can fold the condition, just take that operand.
8341     bool CondResult;
8342     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8343       return GetExprRange(C, CondResult ? CO->getTrueExpr()
8344                                         : CO->getFalseExpr(),
8345                           MaxWidth);
8346 
8347     // Otherwise, conservatively merge.
8348     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8349     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8350     return IntRange::join(L, R);
8351   }
8352 
8353   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8354     switch (BO->getOpcode()) {
8355 
8356     // Boolean-valued operations are single-bit and positive.
8357     case BO_LAnd:
8358     case BO_LOr:
8359     case BO_LT:
8360     case BO_GT:
8361     case BO_LE:
8362     case BO_GE:
8363     case BO_EQ:
8364     case BO_NE:
8365       return IntRange::forBoolType();
8366 
8367     // The type of the assignments is the type of the LHS, so the RHS
8368     // is not necessarily the same type.
8369     case BO_MulAssign:
8370     case BO_DivAssign:
8371     case BO_RemAssign:
8372     case BO_AddAssign:
8373     case BO_SubAssign:
8374     case BO_XorAssign:
8375     case BO_OrAssign:
8376       // TODO: bitfields?
8377       return IntRange::forValueOfType(C, GetExprType(E));
8378 
8379     // Simple assignments just pass through the RHS, which will have
8380     // been coerced to the LHS type.
8381     case BO_Assign:
8382       // TODO: bitfields?
8383       return GetExprRange(C, BO->getRHS(), MaxWidth);
8384 
8385     // Operations with opaque sources are black-listed.
8386     case BO_PtrMemD:
8387     case BO_PtrMemI:
8388       return IntRange::forValueOfType(C, GetExprType(E));
8389 
8390     // Bitwise-and uses the *infinum* of the two source ranges.
8391     case BO_And:
8392     case BO_AndAssign:
8393       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8394                             GetExprRange(C, BO->getRHS(), MaxWidth));
8395 
8396     // Left shift gets black-listed based on a judgement call.
8397     case BO_Shl:
8398       // ...except that we want to treat '1 << (blah)' as logically
8399       // positive.  It's an important idiom.
8400       if (IntegerLiteral *I
8401             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8402         if (I->getValue() == 1) {
8403           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8404           return IntRange(R.Width, /*NonNegative*/ true);
8405         }
8406       }
8407       // fallthrough
8408 
8409     case BO_ShlAssign:
8410       return IntRange::forValueOfType(C, GetExprType(E));
8411 
8412     // Right shift by a constant can narrow its left argument.
8413     case BO_Shr:
8414     case BO_ShrAssign: {
8415       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8416 
8417       // If the shift amount is a positive constant, drop the width by
8418       // that much.
8419       llvm::APSInt shift;
8420       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8421           shift.isNonNegative()) {
8422         unsigned zext = shift.getZExtValue();
8423         if (zext >= L.Width)
8424           L.Width = (L.NonNegative ? 0 : 1);
8425         else
8426           L.Width -= zext;
8427       }
8428 
8429       return L;
8430     }
8431 
8432     // Comma acts as its right operand.
8433     case BO_Comma:
8434       return GetExprRange(C, BO->getRHS(), MaxWidth);
8435 
8436     // Black-list pointer subtractions.
8437     case BO_Sub:
8438       if (BO->getLHS()->getType()->isPointerType())
8439         return IntRange::forValueOfType(C, GetExprType(E));
8440       break;
8441 
8442     // The width of a division result is mostly determined by the size
8443     // of the LHS.
8444     case BO_Div: {
8445       // Don't 'pre-truncate' the operands.
8446       unsigned opWidth = C.getIntWidth(GetExprType(E));
8447       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8448 
8449       // If the divisor is constant, use that.
8450       llvm::APSInt divisor;
8451       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8452         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8453         if (log2 >= L.Width)
8454           L.Width = (L.NonNegative ? 0 : 1);
8455         else
8456           L.Width = std::min(L.Width - log2, MaxWidth);
8457         return L;
8458       }
8459 
8460       // Otherwise, just use the LHS's width.
8461       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8462       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8463     }
8464 
8465     // The result of a remainder can't be larger than the result of
8466     // either side.
8467     case BO_Rem: {
8468       // Don't 'pre-truncate' the operands.
8469       unsigned opWidth = C.getIntWidth(GetExprType(E));
8470       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8471       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8472 
8473       IntRange meet = IntRange::meet(L, R);
8474       meet.Width = std::min(meet.Width, MaxWidth);
8475       return meet;
8476     }
8477 
8478     // The default behavior is okay for these.
8479     case BO_Mul:
8480     case BO_Add:
8481     case BO_Xor:
8482     case BO_Or:
8483       break;
8484     }
8485 
8486     // The default case is to treat the operation as if it were closed
8487     // on the narrowest type that encompasses both operands.
8488     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8489     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8490     return IntRange::join(L, R);
8491   }
8492 
8493   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8494     switch (UO->getOpcode()) {
8495     // Boolean-valued operations are white-listed.
8496     case UO_LNot:
8497       return IntRange::forBoolType();
8498 
8499     // Operations with opaque sources are black-listed.
8500     case UO_Deref:
8501     case UO_AddrOf: // should be impossible
8502       return IntRange::forValueOfType(C, GetExprType(E));
8503 
8504     default:
8505       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8506     }
8507   }
8508 
8509   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8510     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8511 
8512   if (const auto *BitField = E->getSourceBitField())
8513     return IntRange(BitField->getBitWidthValue(C),
8514                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8515 
8516   return IntRange::forValueOfType(C, GetExprType(E));
8517 }
8518 
8519 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8520   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8521 }
8522 
8523 /// Checks whether the given value, which currently has the given
8524 /// source semantics, has the same value when coerced through the
8525 /// target semantics.
8526 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8527                           const llvm::fltSemantics &Src,
8528                           const llvm::fltSemantics &Tgt) {
8529   llvm::APFloat truncated = value;
8530 
8531   bool ignored;
8532   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8533   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8534 
8535   return truncated.bitwiseIsEqual(value);
8536 }
8537 
8538 /// Checks whether the given value, which currently has the given
8539 /// source semantics, has the same value when coerced through the
8540 /// target semantics.
8541 ///
8542 /// The value might be a vector of floats (or a complex number).
8543 bool IsSameFloatAfterCast(const APValue &value,
8544                           const llvm::fltSemantics &Src,
8545                           const llvm::fltSemantics &Tgt) {
8546   if (value.isFloat())
8547     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8548 
8549   if (value.isVector()) {
8550     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8551       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8552         return false;
8553     return true;
8554   }
8555 
8556   assert(value.isComplexFloat());
8557   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8558           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8559 }
8560 
8561 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8562 
8563 bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
8564   // Suppress cases where we are comparing against an enum constant.
8565   if (const DeclRefExpr *DR =
8566       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8567     if (isa<EnumConstantDecl>(DR->getDecl()))
8568       return true;
8569 
8570   // Suppress cases where the '0' value is expanded from a macro.
8571   if (E->getLocStart().isMacroID())
8572     return true;
8573 
8574   return false;
8575 }
8576 
8577 bool isNonBooleanIntegerValue(Expr *E) {
8578   return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType();
8579 }
8580 
8581 bool isNonBooleanUnsignedValue(Expr *E) {
8582   // We are checking that the expression is not known to have boolean value,
8583   // is an integer type; and is either unsigned after implicit casts,
8584   // or was unsigned before implicit casts.
8585   return isNonBooleanIntegerValue(E) &&
8586          (!E->getType()->isSignedIntegerType() ||
8587           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8588 }
8589 
8590 enum class LimitType {
8591   Max = 1U << 0U,  // e.g. 32767 for short
8592   Min = 1U << 1U,  // e.g. -32768 for short
8593   Both = Max | Min // When the value is both the Min and the Max limit at the
8594                    // same time; e.g. in C++, A::a in enum A { a = 0 };
8595 };
8596 
8597 /// Checks whether Expr 'Constant' may be the
8598 /// std::numeric_limits<>::max() or std::numeric_limits<>::min()
8599 /// of the Expr 'Other'. If true, then returns the limit type (min or max).
8600 /// The Value is the evaluation of Constant
8601 llvm::Optional<LimitType> IsTypeLimit(Sema &S, Expr *Constant, Expr *Other,
8602                                       const llvm::APSInt &Value) {
8603   if (IsEnumConstOrFromMacro(S, Constant))
8604     return llvm::Optional<LimitType>();
8605 
8606   if (isNonBooleanUnsignedValue(Other) && Value == 0)
8607     return LimitType::Min;
8608 
8609   // TODO: Investigate using GetExprRange() to get tighter bounds
8610   // on the bit ranges.
8611   QualType OtherT = Other->IgnoreParenImpCasts()->getType();
8612   if (const auto *AT = OtherT->getAs<AtomicType>())
8613     OtherT = AT->getValueType();
8614 
8615   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8616 
8617   // Special-case for C++ for enum with one enumerator with value of 0.
8618   if (OtherRange.Width == 0)
8619     return Value == 0 ? LimitType::Both : llvm::Optional<LimitType>();
8620 
8621   if (llvm::APSInt::isSameValue(
8622           llvm::APSInt::getMaxValue(OtherRange.Width,
8623                                     OtherT->isUnsignedIntegerType()),
8624           Value))
8625     return LimitType::Max;
8626 
8627   if (llvm::APSInt::isSameValue(
8628           llvm::APSInt::getMinValue(OtherRange.Width,
8629                                     OtherT->isUnsignedIntegerType()),
8630           Value))
8631     return LimitType::Min;
8632 
8633   return llvm::None;
8634 }
8635 
8636 bool HasEnumType(Expr *E) {
8637   // Strip off implicit integral promotions.
8638   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8639     if (ICE->getCastKind() != CK_IntegralCast &&
8640         ICE->getCastKind() != CK_NoOp)
8641       break;
8642     E = ICE->getSubExpr();
8643   }
8644 
8645   return E->getType()->isEnumeralType();
8646 }
8647 
8648 bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8649                                  Expr *Other, const llvm::APSInt &Value,
8650                                  bool RhsConstant) {
8651   // Disable warning in template instantiations
8652   // and only analyze <, >, <= and >= operations.
8653   if (S.inTemplateInstantiation() || !E->isRelationalOp())
8654     return false;
8655 
8656   BinaryOperatorKind Op = E->getOpcode();
8657 
8658   QualType OType = Other->IgnoreParenImpCasts()->getType();
8659 
8660   llvm::Optional<LimitType> ValueType; // Which limit (min/max) is the constant?
8661 
8662   if (!(isNonBooleanIntegerValue(Other) &&
8663         (ValueType = IsTypeLimit(S, Constant, Other, Value))))
8664     return false;
8665 
8666   bool ConstIsLowerBound = (Op == BO_LT || Op == BO_LE) ^ RhsConstant;
8667   bool ResultWhenConstEqualsOther = (Op == BO_LE || Op == BO_GE);
8668   if (ValueType != LimitType::Both) {
8669     bool ResultWhenConstNeOther =
8670         ConstIsLowerBound ^ (ValueType == LimitType::Max);
8671     if (ResultWhenConstEqualsOther != ResultWhenConstNeOther)
8672       return false; // The comparison is not tautological.
8673   } else if (ResultWhenConstEqualsOther == ConstIsLowerBound)
8674     return false; // The comparison is not tautological.
8675 
8676   const bool Result = ResultWhenConstEqualsOther;
8677 
8678   unsigned Diag = (isNonBooleanUnsignedValue(Other) && Value == 0)
8679                       ? (HasEnumType(Other)
8680                              ? diag::warn_unsigned_enum_always_true_comparison
8681                              : diag::warn_unsigned_always_true_comparison)
8682                       : diag::warn_tautological_constant_compare;
8683 
8684   // Should be enough for uint128 (39 decimal digits)
8685   SmallString<64> PrettySourceValue;
8686   llvm::raw_svector_ostream OS(PrettySourceValue);
8687   OS << Value;
8688 
8689   S.Diag(E->getOperatorLoc(), Diag)
8690       << RhsConstant << OType << E->getOpcodeStr() << OS.str() << Result
8691       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8692 
8693   return true;
8694 }
8695 
8696 bool DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8697                                   Expr *Other, const llvm::APSInt &Value,
8698                                   bool RhsConstant) {
8699   // Disable warning in template instantiations.
8700   if (S.inTemplateInstantiation())
8701     return false;
8702 
8703   Constant = Constant->IgnoreParenImpCasts();
8704   Other = Other->IgnoreParenImpCasts();
8705 
8706   // TODO: Investigate using GetExprRange() to get tighter bounds
8707   // on the bit ranges.
8708   QualType OtherT = Other->getType();
8709   if (const auto *AT = OtherT->getAs<AtomicType>())
8710     OtherT = AT->getValueType();
8711   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8712   unsigned OtherWidth = OtherRange.Width;
8713 
8714   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8715 
8716   BinaryOperatorKind op = E->getOpcode();
8717   bool IsTrue = true;
8718 
8719   // Used for diagnostic printout.
8720   enum {
8721     LiteralConstant = 0,
8722     CXXBoolLiteralTrue,
8723     CXXBoolLiteralFalse
8724   } LiteralOrBoolConstant = LiteralConstant;
8725 
8726   if (!OtherIsBooleanType) {
8727     QualType ConstantT = Constant->getType();
8728     QualType CommonT = E->getLHS()->getType();
8729 
8730     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8731       return false;
8732     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8733            "comparison with non-integer type");
8734 
8735     bool ConstantSigned = ConstantT->isSignedIntegerType();
8736     bool CommonSigned = CommonT->isSignedIntegerType();
8737 
8738     bool EqualityOnly = false;
8739 
8740     if (CommonSigned) {
8741       // The common type is signed, therefore no signed to unsigned conversion.
8742       if (!OtherRange.NonNegative) {
8743         // Check that the constant is representable in type OtherT.
8744         if (ConstantSigned) {
8745           if (OtherWidth >= Value.getMinSignedBits())
8746             return false;
8747         } else { // !ConstantSigned
8748           if (OtherWidth >= Value.getActiveBits() + 1)
8749             return false;
8750         }
8751       } else { // !OtherSigned
8752                // Check that the constant is representable in type OtherT.
8753         // Negative values are out of range.
8754         if (ConstantSigned) {
8755           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8756             return false;
8757         } else { // !ConstantSigned
8758           if (OtherWidth >= Value.getActiveBits())
8759             return false;
8760         }
8761       }
8762     } else { // !CommonSigned
8763       if (OtherRange.NonNegative) {
8764         if (OtherWidth >= Value.getActiveBits())
8765           return false;
8766       } else { // OtherSigned
8767         assert(!ConstantSigned &&
8768                "Two signed types converted to unsigned types.");
8769         // Check to see if the constant is representable in OtherT.
8770         if (OtherWidth > Value.getActiveBits())
8771           return false;
8772         // Check to see if the constant is equivalent to a negative value
8773         // cast to CommonT.
8774         if (S.Context.getIntWidth(ConstantT) ==
8775                 S.Context.getIntWidth(CommonT) &&
8776             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8777           return false;
8778         // The constant value rests between values that OtherT can represent
8779         // after conversion.  Relational comparison still works, but equality
8780         // comparisons will be tautological.
8781         EqualityOnly = true;
8782       }
8783     }
8784 
8785     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8786 
8787     if (op == BO_EQ || op == BO_NE) {
8788       IsTrue = op == BO_NE;
8789     } else if (EqualityOnly) {
8790       return false;
8791     } else if (RhsConstant) {
8792       if (op == BO_GT || op == BO_GE)
8793         IsTrue = !PositiveConstant;
8794       else // op == BO_LT || op == BO_LE
8795         IsTrue = PositiveConstant;
8796     } else {
8797       if (op == BO_LT || op == BO_LE)
8798         IsTrue = !PositiveConstant;
8799       else // op == BO_GT || op == BO_GE
8800         IsTrue = PositiveConstant;
8801     }
8802   } else {
8803     // Other isKnownToHaveBooleanValue
8804     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8805     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8806     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8807 
8808     static const struct LinkedConditions {
8809       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8810       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8811       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8812       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8813       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8814       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8815 
8816     } TruthTable = {
8817         // Constant on LHS.              | Constant on RHS.              |
8818         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
8819         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8820         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8821         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8822         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8823         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8824         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8825       };
8826 
8827     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8828 
8829     enum ConstantValue ConstVal = Zero;
8830     if (Value.isUnsigned() || Value.isNonNegative()) {
8831       if (Value == 0) {
8832         LiteralOrBoolConstant =
8833             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8834         ConstVal = Zero;
8835       } else if (Value == 1) {
8836         LiteralOrBoolConstant =
8837             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8838         ConstVal = One;
8839       } else {
8840         LiteralOrBoolConstant = LiteralConstant;
8841         ConstVal = GT_One;
8842       }
8843     } else {
8844       ConstVal = LT_Zero;
8845     }
8846 
8847     CompareBoolWithConstantResult CmpRes;
8848 
8849     switch (op) {
8850     case BO_LT:
8851       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8852       break;
8853     case BO_GT:
8854       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8855       break;
8856     case BO_LE:
8857       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8858       break;
8859     case BO_GE:
8860       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8861       break;
8862     case BO_EQ:
8863       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8864       break;
8865     case BO_NE:
8866       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8867       break;
8868     default:
8869       CmpRes = Unkwn;
8870       break;
8871     }
8872 
8873     if (CmpRes == AFals) {
8874       IsTrue = false;
8875     } else if (CmpRes == ATrue) {
8876       IsTrue = true;
8877     } else {
8878       return false;
8879     }
8880   }
8881 
8882   // If this is a comparison to an enum constant, include that
8883   // constant in the diagnostic.
8884   const EnumConstantDecl *ED = nullptr;
8885   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8886     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8887 
8888   SmallString<64> PrettySourceValue;
8889   llvm::raw_svector_ostream OS(PrettySourceValue);
8890   if (ED)
8891     OS << '\'' << *ED << "' (" << Value << ")";
8892   else
8893     OS << Value;
8894 
8895   S.DiagRuntimeBehavior(
8896     E->getOperatorLoc(), E,
8897     S.PDiag(diag::warn_out_of_range_compare)
8898         << OS.str() << LiteralOrBoolConstant
8899         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8900         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8901 
8902    return true;
8903 }
8904 
8905 /// Analyze the operands of the given comparison.  Implements the
8906 /// fallback case from AnalyzeComparison.
8907 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8908   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8909   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8910 }
8911 
8912 /// \brief Implements -Wsign-compare.
8913 ///
8914 /// \param E the binary operator to check for warnings
8915 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8916   // The type the comparison is being performed in.
8917   QualType T = E->getLHS()->getType();
8918 
8919   // Only analyze comparison operators where both sides have been converted to
8920   // the same type.
8921   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8922     return AnalyzeImpConvsInComparison(S, E);
8923 
8924   // Don't analyze value-dependent comparisons directly.
8925   if (E->isValueDependent())
8926     return AnalyzeImpConvsInComparison(S, E);
8927 
8928   Expr *LHS = E->getLHS();
8929   Expr *RHS = E->getRHS();
8930 
8931   if (T->isIntegralType(S.Context)) {
8932     llvm::APSInt RHSValue;
8933     llvm::APSInt LHSValue;
8934 
8935     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8936     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
8937 
8938     // We don't care about expressions whose result is a constant.
8939     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8940       return AnalyzeImpConvsInComparison(S, E);
8941 
8942     // We only care about expressions where just one side is literal
8943     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8944       // Is the constant on the RHS or LHS?
8945       const bool RhsConstant = IsRHSIntegralLiteral;
8946       Expr *Const = RhsConstant ? RHS : LHS;
8947       Expr *Other = RhsConstant ? LHS : RHS;
8948       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8949 
8950       // Check whether an integer constant comparison results in a value
8951       // of 'true' or 'false'.
8952 
8953       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8954         return AnalyzeImpConvsInComparison(S, E);
8955 
8956       if (DiagnoseOutOfRangeComparison(S, E, Const, Other, Value, RhsConstant))
8957         return AnalyzeImpConvsInComparison(S, E);
8958     }
8959   }
8960 
8961   if (!T->hasUnsignedIntegerRepresentation()) {
8962     // We don't do anything special if this isn't an unsigned integral
8963     // comparison:  we're only interested in integral comparisons, and
8964     // signed comparisons only happen in cases we don't care to warn about.
8965     return AnalyzeImpConvsInComparison(S, E);
8966   }
8967 
8968   LHS = LHS->IgnoreParenImpCasts();
8969   RHS = RHS->IgnoreParenImpCasts();
8970 
8971   // Check to see if one of the (unmodified) operands is of different
8972   // signedness.
8973   Expr *signedOperand, *unsignedOperand;
8974   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8975     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8976            "unsigned comparison between two signed integer expressions?");
8977     signedOperand = LHS;
8978     unsignedOperand = RHS;
8979   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8980     signedOperand = RHS;
8981     unsignedOperand = LHS;
8982   } else {
8983     return AnalyzeImpConvsInComparison(S, E);
8984   }
8985 
8986   // Otherwise, calculate the effective range of the signed operand.
8987   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8988 
8989   // Go ahead and analyze implicit conversions in the operands.  Note
8990   // that we skip the implicit conversions on both sides.
8991   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8992   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8993 
8994   // If the signed range is non-negative, -Wsign-compare won't fire.
8995   if (signedRange.NonNegative)
8996     return;
8997 
8998   // For (in)equality comparisons, if the unsigned operand is a
8999   // constant which cannot collide with a overflowed signed operand,
9000   // then reinterpreting the signed operand as unsigned will not
9001   // change the result of the comparison.
9002   if (E->isEqualityOp()) {
9003     unsigned comparisonWidth = S.Context.getIntWidth(T);
9004     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
9005 
9006     // We should never be unable to prove that the unsigned operand is
9007     // non-negative.
9008     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9009 
9010     if (unsignedRange.Width < comparisonWidth)
9011       return;
9012   }
9013 
9014   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9015     S.PDiag(diag::warn_mixed_sign_comparison)
9016       << LHS->getType() << RHS->getType()
9017       << LHS->getSourceRange() << RHS->getSourceRange());
9018 }
9019 
9020 /// Analyzes an attempt to assign the given value to a bitfield.
9021 ///
9022 /// Returns true if there was something fishy about the attempt.
9023 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9024                                SourceLocation InitLoc) {
9025   assert(Bitfield->isBitField());
9026   if (Bitfield->isInvalidDecl())
9027     return false;
9028 
9029   // White-list bool bitfields.
9030   QualType BitfieldType = Bitfield->getType();
9031   if (BitfieldType->isBooleanType())
9032      return false;
9033 
9034   if (BitfieldType->isEnumeralType()) {
9035     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9036     // If the underlying enum type was not explicitly specified as an unsigned
9037     // type and the enum contain only positive values, MSVC++ will cause an
9038     // inconsistency by storing this as a signed type.
9039     if (S.getLangOpts().CPlusPlus11 &&
9040         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9041         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9042         BitfieldEnumDecl->getNumNegativeBits() == 0) {
9043       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9044         << BitfieldEnumDecl->getNameAsString();
9045     }
9046   }
9047 
9048   if (Bitfield->getType()->isBooleanType())
9049     return false;
9050 
9051   // Ignore value- or type-dependent expressions.
9052   if (Bitfield->getBitWidth()->isValueDependent() ||
9053       Bitfield->getBitWidth()->isTypeDependent() ||
9054       Init->isValueDependent() ||
9055       Init->isTypeDependent())
9056     return false;
9057 
9058   Expr *OriginalInit = Init->IgnoreParenImpCasts();
9059   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
9060 
9061   llvm::APSInt Value;
9062   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9063                                    Expr::SE_AllowSideEffects)) {
9064     // The RHS is not constant.  If the RHS has an enum type, make sure the
9065     // bitfield is wide enough to hold all the values of the enum without
9066     // truncation.
9067     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9068       EnumDecl *ED = EnumTy->getDecl();
9069       bool SignedBitfield = BitfieldType->isSignedIntegerType();
9070 
9071       // Enum types are implicitly signed on Windows, so check if there are any
9072       // negative enumerators to see if the enum was intended to be signed or
9073       // not.
9074       bool SignedEnum = ED->getNumNegativeBits() > 0;
9075 
9076       // Check for surprising sign changes when assigning enum values to a
9077       // bitfield of different signedness.  If the bitfield is signed and we
9078       // have exactly the right number of bits to store this unsigned enum,
9079       // suggest changing the enum to an unsigned type. This typically happens
9080       // on Windows where unfixed enums always use an underlying type of 'int'.
9081       unsigned DiagID = 0;
9082       if (SignedEnum && !SignedBitfield) {
9083         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9084       } else if (SignedBitfield && !SignedEnum &&
9085                  ED->getNumPositiveBits() == FieldWidth) {
9086         DiagID = diag::warn_signed_bitfield_enum_conversion;
9087       }
9088 
9089       if (DiagID) {
9090         S.Diag(InitLoc, DiagID) << Bitfield << ED;
9091         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9092         SourceRange TypeRange =
9093             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9094         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9095             << SignedEnum << TypeRange;
9096       }
9097 
9098       // Compute the required bitwidth. If the enum has negative values, we need
9099       // one more bit than the normal number of positive bits to represent the
9100       // sign bit.
9101       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9102                                                   ED->getNumNegativeBits())
9103                                        : ED->getNumPositiveBits();
9104 
9105       // Check the bitwidth.
9106       if (BitsNeeded > FieldWidth) {
9107         Expr *WidthExpr = Bitfield->getBitWidth();
9108         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9109             << Bitfield << ED;
9110         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9111             << BitsNeeded << ED << WidthExpr->getSourceRange();
9112       }
9113     }
9114 
9115     return false;
9116   }
9117 
9118   unsigned OriginalWidth = Value.getBitWidth();
9119 
9120   if (!Value.isSigned() || Value.isNegative())
9121     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9122       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9123         OriginalWidth = Value.getMinSignedBits();
9124 
9125   if (OriginalWidth <= FieldWidth)
9126     return false;
9127 
9128   // Compute the value which the bitfield will contain.
9129   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9130   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9131 
9132   // Check whether the stored value is equal to the original value.
9133   TruncatedValue = TruncatedValue.extend(OriginalWidth);
9134   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9135     return false;
9136 
9137   // Special-case bitfields of width 1: booleans are naturally 0/1, and
9138   // therefore don't strictly fit into a signed bitfield of width 1.
9139   if (FieldWidth == 1 && Value == 1)
9140     return false;
9141 
9142   std::string PrettyValue = Value.toString(10);
9143   std::string PrettyTrunc = TruncatedValue.toString(10);
9144 
9145   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9146     << PrettyValue << PrettyTrunc << OriginalInit->getType()
9147     << Init->getSourceRange();
9148 
9149   return true;
9150 }
9151 
9152 /// Analyze the given simple or compound assignment for warning-worthy
9153 /// operations.
9154 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9155   // Just recurse on the LHS.
9156   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9157 
9158   // We want to recurse on the RHS as normal unless we're assigning to
9159   // a bitfield.
9160   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9161     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9162                                   E->getOperatorLoc())) {
9163       // Recurse, ignoring any implicit conversions on the RHS.
9164       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9165                                         E->getOperatorLoc());
9166     }
9167   }
9168 
9169   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9170 }
9171 
9172 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9173 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9174                      SourceLocation CContext, unsigned diag,
9175                      bool pruneControlFlow = false) {
9176   if (pruneControlFlow) {
9177     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9178                           S.PDiag(diag)
9179                             << SourceType << T << E->getSourceRange()
9180                             << SourceRange(CContext));
9181     return;
9182   }
9183   S.Diag(E->getExprLoc(), diag)
9184     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9185 }
9186 
9187 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9188 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
9189                      unsigned diag, bool pruneControlFlow = false) {
9190   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9191 }
9192 
9193 
9194 /// Diagnose an implicit cast from a floating point value to an integer value.
9195 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9196 
9197                              SourceLocation CContext) {
9198   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9199   const bool PruneWarnings = S.inTemplateInstantiation();
9200 
9201   Expr *InnerE = E->IgnoreParenImpCasts();
9202   // We also want to warn on, e.g., "int i = -1.234"
9203   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9204     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9205       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9206 
9207   const bool IsLiteral =
9208       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9209 
9210   llvm::APFloat Value(0.0);
9211   bool IsConstant =
9212     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9213   if (!IsConstant) {
9214     return DiagnoseImpCast(S, E, T, CContext,
9215                            diag::warn_impcast_float_integer, PruneWarnings);
9216   }
9217 
9218   bool isExact = false;
9219 
9220   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9221                             T->hasUnsignedIntegerRepresentation());
9222   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9223                              &isExact) == llvm::APFloat::opOK &&
9224       isExact) {
9225     if (IsLiteral) return;
9226     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9227                            PruneWarnings);
9228   }
9229 
9230   unsigned DiagID = 0;
9231   if (IsLiteral) {
9232     // Warn on floating point literal to integer.
9233     DiagID = diag::warn_impcast_literal_float_to_integer;
9234   } else if (IntegerValue == 0) {
9235     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
9236       return DiagnoseImpCast(S, E, T, CContext,
9237                              diag::warn_impcast_float_integer, PruneWarnings);
9238     }
9239     // Warn on non-zero to zero conversion.
9240     DiagID = diag::warn_impcast_float_to_integer_zero;
9241   } else {
9242     if (IntegerValue.isUnsigned()) {
9243       if (!IntegerValue.isMaxValue()) {
9244         return DiagnoseImpCast(S, E, T, CContext,
9245                                diag::warn_impcast_float_integer, PruneWarnings);
9246       }
9247     } else {  // IntegerValue.isSigned()
9248       if (!IntegerValue.isMaxSignedValue() &&
9249           !IntegerValue.isMinSignedValue()) {
9250         return DiagnoseImpCast(S, E, T, CContext,
9251                                diag::warn_impcast_float_integer, PruneWarnings);
9252       }
9253     }
9254     // Warn on evaluatable floating point expression to integer conversion.
9255     DiagID = diag::warn_impcast_float_to_integer;
9256   }
9257 
9258   // FIXME: Force the precision of the source value down so we don't print
9259   // digits which are usually useless (we don't really care here if we
9260   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9261   // would automatically print the shortest representation, but it's a bit
9262   // tricky to implement.
9263   SmallString<16> PrettySourceValue;
9264   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9265   precision = (precision * 59 + 195) / 196;
9266   Value.toString(PrettySourceValue, precision);
9267 
9268   SmallString<16> PrettyTargetValue;
9269   if (IsBool)
9270     PrettyTargetValue = Value.isZero() ? "false" : "true";
9271   else
9272     IntegerValue.toString(PrettyTargetValue);
9273 
9274   if (PruneWarnings) {
9275     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9276                           S.PDiag(DiagID)
9277                               << E->getType() << T.getUnqualifiedType()
9278                               << PrettySourceValue << PrettyTargetValue
9279                               << E->getSourceRange() << SourceRange(CContext));
9280   } else {
9281     S.Diag(E->getExprLoc(), DiagID)
9282         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9283         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9284   }
9285 }
9286 
9287 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9288   if (!Range.Width) return "0";
9289 
9290   llvm::APSInt ValueInRange = Value;
9291   ValueInRange.setIsSigned(!Range.NonNegative);
9292   ValueInRange = ValueInRange.trunc(Range.Width);
9293   return ValueInRange.toString(10);
9294 }
9295 
9296 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9297   if (!isa<ImplicitCastExpr>(Ex))
9298     return false;
9299 
9300   Expr *InnerE = Ex->IgnoreParenImpCasts();
9301   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9302   const Type *Source =
9303     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9304   if (Target->isDependentType())
9305     return false;
9306 
9307   const BuiltinType *FloatCandidateBT =
9308     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9309   const Type *BoolCandidateType = ToBool ? Target : Source;
9310 
9311   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9312           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9313 }
9314 
9315 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9316                                       SourceLocation CC) {
9317   unsigned NumArgs = TheCall->getNumArgs();
9318   for (unsigned i = 0; i < NumArgs; ++i) {
9319     Expr *CurrA = TheCall->getArg(i);
9320     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9321       continue;
9322 
9323     bool IsSwapped = ((i > 0) &&
9324         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9325     IsSwapped |= ((i < (NumArgs - 1)) &&
9326         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9327     if (IsSwapped) {
9328       // Warn on this floating-point to bool conversion.
9329       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9330                       CurrA->getType(), CC,
9331                       diag::warn_impcast_floating_point_to_bool);
9332     }
9333   }
9334 }
9335 
9336 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
9337   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9338                         E->getExprLoc()))
9339     return;
9340 
9341   // Don't warn on functions which have return type nullptr_t.
9342   if (isa<CallExpr>(E))
9343     return;
9344 
9345   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9346   const Expr::NullPointerConstantKind NullKind =
9347       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9348   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9349     return;
9350 
9351   // Return if target type is a safe conversion.
9352   if (T->isAnyPointerType() || T->isBlockPointerType() ||
9353       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9354     return;
9355 
9356   SourceLocation Loc = E->getSourceRange().getBegin();
9357 
9358   // Venture through the macro stacks to get to the source of macro arguments.
9359   // The new location is a better location than the complete location that was
9360   // passed in.
9361   while (S.SourceMgr.isMacroArgExpansion(Loc))
9362     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9363 
9364   while (S.SourceMgr.isMacroArgExpansion(CC))
9365     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9366 
9367   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
9368   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9369     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9370         Loc, S.SourceMgr, S.getLangOpts());
9371     if (MacroName == "NULL")
9372       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9373   }
9374 
9375   // Only warn if the null and context location are in the same macro expansion.
9376   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9377     return;
9378 
9379   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9380       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9381       << FixItHint::CreateReplacement(Loc,
9382                                       S.getFixItZeroLiteralForType(T, Loc));
9383 }
9384 
9385 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9386                            ObjCArrayLiteral *ArrayLiteral);
9387 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9388                                 ObjCDictionaryLiteral *DictionaryLiteral);
9389 
9390 /// Check a single element within a collection literal against the
9391 /// target element type.
9392 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9393                                        Expr *Element, unsigned ElementKind) {
9394   // Skip a bitcast to 'id' or qualified 'id'.
9395   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9396     if (ICE->getCastKind() == CK_BitCast &&
9397         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9398       Element = ICE->getSubExpr();
9399   }
9400 
9401   QualType ElementType = Element->getType();
9402   ExprResult ElementResult(Element);
9403   if (ElementType->getAs<ObjCObjectPointerType>() &&
9404       S.CheckSingleAssignmentConstraints(TargetElementType,
9405                                          ElementResult,
9406                                          false, false)
9407         != Sema::Compatible) {
9408     S.Diag(Element->getLocStart(),
9409            diag::warn_objc_collection_literal_element)
9410       << ElementType << ElementKind << TargetElementType
9411       << Element->getSourceRange();
9412   }
9413 
9414   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9415     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9416   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9417     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9418 }
9419 
9420 /// Check an Objective-C array literal being converted to the given
9421 /// target type.
9422 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9423                            ObjCArrayLiteral *ArrayLiteral) {
9424   if (!S.NSArrayDecl)
9425     return;
9426 
9427   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9428   if (!TargetObjCPtr)
9429     return;
9430 
9431   if (TargetObjCPtr->isUnspecialized() ||
9432       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9433         != S.NSArrayDecl->getCanonicalDecl())
9434     return;
9435 
9436   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9437   if (TypeArgs.size() != 1)
9438     return;
9439 
9440   QualType TargetElementType = TypeArgs[0];
9441   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9442     checkObjCCollectionLiteralElement(S, TargetElementType,
9443                                       ArrayLiteral->getElement(I),
9444                                       0);
9445   }
9446 }
9447 
9448 /// Check an Objective-C dictionary literal being converted to the given
9449 /// target type.
9450 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9451                                 ObjCDictionaryLiteral *DictionaryLiteral) {
9452   if (!S.NSDictionaryDecl)
9453     return;
9454 
9455   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9456   if (!TargetObjCPtr)
9457     return;
9458 
9459   if (TargetObjCPtr->isUnspecialized() ||
9460       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9461         != S.NSDictionaryDecl->getCanonicalDecl())
9462     return;
9463 
9464   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9465   if (TypeArgs.size() != 2)
9466     return;
9467 
9468   QualType TargetKeyType = TypeArgs[0];
9469   QualType TargetObjectType = TypeArgs[1];
9470   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9471     auto Element = DictionaryLiteral->getKeyValueElement(I);
9472     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9473     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9474   }
9475 }
9476 
9477 // Helper function to filter out cases for constant width constant conversion.
9478 // Don't warn on char array initialization or for non-decimal values.
9479 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9480                                    SourceLocation CC) {
9481   // If initializing from a constant, and the constant starts with '0',
9482   // then it is a binary, octal, or hexadecimal.  Allow these constants
9483   // to fill all the bits, even if there is a sign change.
9484   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9485     const char FirstLiteralCharacter =
9486         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9487     if (FirstLiteralCharacter == '0')
9488       return false;
9489   }
9490 
9491   // If the CC location points to a '{', and the type is char, then assume
9492   // assume it is an array initialization.
9493   if (CC.isValid() && T->isCharType()) {
9494     const char FirstContextCharacter =
9495         S.getSourceManager().getCharacterData(CC)[0];
9496     if (FirstContextCharacter == '{')
9497       return false;
9498   }
9499 
9500   return true;
9501 }
9502 
9503 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
9504                              SourceLocation CC, bool *ICContext = nullptr) {
9505   if (E->isTypeDependent() || E->isValueDependent()) return;
9506 
9507   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9508   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9509   if (Source == Target) return;
9510   if (Target->isDependentType()) return;
9511 
9512   // If the conversion context location is invalid don't complain. We also
9513   // don't want to emit a warning if the issue occurs from the expansion of
9514   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9515   // delay this check as long as possible. Once we detect we are in that
9516   // scenario, we just return.
9517   if (CC.isInvalid())
9518     return;
9519 
9520   // Diagnose implicit casts to bool.
9521   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9522     if (isa<StringLiteral>(E))
9523       // Warn on string literal to bool.  Checks for string literals in logical
9524       // and expressions, for instance, assert(0 && "error here"), are
9525       // prevented by a check in AnalyzeImplicitConversions().
9526       return DiagnoseImpCast(S, E, T, CC,
9527                              diag::warn_impcast_string_literal_to_bool);
9528     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9529         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9530       // This covers the literal expressions that evaluate to Objective-C
9531       // objects.
9532       return DiagnoseImpCast(S, E, T, CC,
9533                              diag::warn_impcast_objective_c_literal_to_bool);
9534     }
9535     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9536       // Warn on pointer to bool conversion that is always true.
9537       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9538                                      SourceRange(CC));
9539     }
9540   }
9541 
9542   // Check implicit casts from Objective-C collection literals to specialized
9543   // collection types, e.g., NSArray<NSString *> *.
9544   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9545     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9546   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9547     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9548 
9549   // Strip vector types.
9550   if (isa<VectorType>(Source)) {
9551     if (!isa<VectorType>(Target)) {
9552       if (S.SourceMgr.isInSystemMacro(CC))
9553         return;
9554       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9555     }
9556 
9557     // If the vector cast is cast between two vectors of the same size, it is
9558     // a bitcast, not a conversion.
9559     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9560       return;
9561 
9562     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9563     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9564   }
9565   if (auto VecTy = dyn_cast<VectorType>(Target))
9566     Target = VecTy->getElementType().getTypePtr();
9567 
9568   // Strip complex types.
9569   if (isa<ComplexType>(Source)) {
9570     if (!isa<ComplexType>(Target)) {
9571       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
9572         return;
9573 
9574       return DiagnoseImpCast(S, E, T, CC,
9575                              S.getLangOpts().CPlusPlus
9576                                  ? diag::err_impcast_complex_scalar
9577                                  : diag::warn_impcast_complex_scalar);
9578     }
9579 
9580     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9581     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9582   }
9583 
9584   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9585   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9586 
9587   // If the source is floating point...
9588   if (SourceBT && SourceBT->isFloatingPoint()) {
9589     // ...and the target is floating point...
9590     if (TargetBT && TargetBT->isFloatingPoint()) {
9591       // ...then warn if we're dropping FP rank.
9592 
9593       // Builtin FP kinds are ordered by increasing FP rank.
9594       if (SourceBT->getKind() > TargetBT->getKind()) {
9595         // Don't warn about float constants that are precisely
9596         // representable in the target type.
9597         Expr::EvalResult result;
9598         if (E->EvaluateAsRValue(result, S.Context)) {
9599           // Value might be a float, a float vector, or a float complex.
9600           if (IsSameFloatAfterCast(result.Val,
9601                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9602                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9603             return;
9604         }
9605 
9606         if (S.SourceMgr.isInSystemMacro(CC))
9607           return;
9608 
9609         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9610       }
9611       // ... or possibly if we're increasing rank, too
9612       else if (TargetBT->getKind() > SourceBT->getKind()) {
9613         if (S.SourceMgr.isInSystemMacro(CC))
9614           return;
9615 
9616         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9617       }
9618       return;
9619     }
9620 
9621     // If the target is integral, always warn.
9622     if (TargetBT && TargetBT->isInteger()) {
9623       if (S.SourceMgr.isInSystemMacro(CC))
9624         return;
9625 
9626       DiagnoseFloatingImpCast(S, E, T, CC);
9627     }
9628 
9629     // Detect the case where a call result is converted from floating-point to
9630     // to bool, and the final argument to the call is converted from bool, to
9631     // discover this typo:
9632     //
9633     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9634     //
9635     // FIXME: This is an incredibly special case; is there some more general
9636     // way to detect this class of misplaced-parentheses bug?
9637     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9638       // Check last argument of function call to see if it is an
9639       // implicit cast from a type matching the type the result
9640       // is being cast to.
9641       CallExpr *CEx = cast<CallExpr>(E);
9642       if (unsigned NumArgs = CEx->getNumArgs()) {
9643         Expr *LastA = CEx->getArg(NumArgs - 1);
9644         Expr *InnerE = LastA->IgnoreParenImpCasts();
9645         if (isa<ImplicitCastExpr>(LastA) &&
9646             InnerE->getType()->isBooleanType()) {
9647           // Warn on this floating-point to bool conversion
9648           DiagnoseImpCast(S, E, T, CC,
9649                           diag::warn_impcast_floating_point_to_bool);
9650         }
9651       }
9652     }
9653     return;
9654   }
9655 
9656   DiagnoseNullConversion(S, E, T, CC);
9657 
9658   S.DiscardMisalignedMemberAddress(Target, E);
9659 
9660   if (!Source->isIntegerType() || !Target->isIntegerType())
9661     return;
9662 
9663   // TODO: remove this early return once the false positives for constant->bool
9664   // in templates, macros, etc, are reduced or removed.
9665   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9666     return;
9667 
9668   IntRange SourceRange = GetExprRange(S.Context, E);
9669   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9670 
9671   if (SourceRange.Width > TargetRange.Width) {
9672     // If the source is a constant, use a default-on diagnostic.
9673     // TODO: this should happen for bitfield stores, too.
9674     llvm::APSInt Value(32);
9675     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9676       if (S.SourceMgr.isInSystemMacro(CC))
9677         return;
9678 
9679       std::string PrettySourceValue = Value.toString(10);
9680       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9681 
9682       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9683         S.PDiag(diag::warn_impcast_integer_precision_constant)
9684             << PrettySourceValue << PrettyTargetValue
9685             << E->getType() << T << E->getSourceRange()
9686             << clang::SourceRange(CC));
9687       return;
9688     }
9689 
9690     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9691     if (S.SourceMgr.isInSystemMacro(CC))
9692       return;
9693 
9694     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9695       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9696                              /* pruneControlFlow */ true);
9697     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9698   }
9699 
9700   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9701       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9702     // Warn when doing a signed to signed conversion, warn if the positive
9703     // source value is exactly the width of the target type, which will
9704     // cause a negative value to be stored.
9705 
9706     llvm::APSInt Value;
9707     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9708         !S.SourceMgr.isInSystemMacro(CC)) {
9709       if (isSameWidthConstantConversion(S, E, T, CC)) {
9710         std::string PrettySourceValue = Value.toString(10);
9711         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9712 
9713         S.DiagRuntimeBehavior(
9714             E->getExprLoc(), E,
9715             S.PDiag(diag::warn_impcast_integer_precision_constant)
9716                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9717                 << E->getSourceRange() << clang::SourceRange(CC));
9718         return;
9719       }
9720     }
9721 
9722     // Fall through for non-constants to give a sign conversion warning.
9723   }
9724 
9725   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9726       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9727        SourceRange.Width == TargetRange.Width)) {
9728     if (S.SourceMgr.isInSystemMacro(CC))
9729       return;
9730 
9731     unsigned DiagID = diag::warn_impcast_integer_sign;
9732 
9733     // Traditionally, gcc has warned about this under -Wsign-compare.
9734     // We also want to warn about it in -Wconversion.
9735     // So if -Wconversion is off, use a completely identical diagnostic
9736     // in the sign-compare group.
9737     // The conditional-checking code will
9738     if (ICContext) {
9739       DiagID = diag::warn_impcast_integer_sign_conditional;
9740       *ICContext = true;
9741     }
9742 
9743     return DiagnoseImpCast(S, E, T, CC, DiagID);
9744   }
9745 
9746   // Diagnose conversions between different enumeration types.
9747   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9748   // type, to give us better diagnostics.
9749   QualType SourceType = E->getType();
9750   if (!S.getLangOpts().CPlusPlus) {
9751     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9752       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9753         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9754         SourceType = S.Context.getTypeDeclType(Enum);
9755         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9756       }
9757   }
9758 
9759   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9760     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9761       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9762           TargetEnum->getDecl()->hasNameForLinkage() &&
9763           SourceEnum != TargetEnum) {
9764         if (S.SourceMgr.isInSystemMacro(CC))
9765           return;
9766 
9767         return DiagnoseImpCast(S, E, SourceType, T, CC,
9768                                diag::warn_impcast_different_enum_types);
9769       }
9770 }
9771 
9772 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9773                               SourceLocation CC, QualType T);
9774 
9775 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9776                              SourceLocation CC, bool &ICContext) {
9777   E = E->IgnoreParenImpCasts();
9778 
9779   if (isa<ConditionalOperator>(E))
9780     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9781 
9782   AnalyzeImplicitConversions(S, E, CC);
9783   if (E->getType() != T)
9784     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9785 }
9786 
9787 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9788                               SourceLocation CC, QualType T) {
9789   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9790 
9791   bool Suspicious = false;
9792   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9793   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9794 
9795   // If -Wconversion would have warned about either of the candidates
9796   // for a signedness conversion to the context type...
9797   if (!Suspicious) return;
9798 
9799   // ...but it's currently ignored...
9800   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9801     return;
9802 
9803   // ...then check whether it would have warned about either of the
9804   // candidates for a signedness conversion to the condition type.
9805   if (E->getType() == T) return;
9806 
9807   Suspicious = false;
9808   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9809                           E->getType(), CC, &Suspicious);
9810   if (!Suspicious)
9811     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9812                             E->getType(), CC, &Suspicious);
9813 }
9814 
9815 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9816 /// Input argument E is a logical expression.
9817 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9818   if (S.getLangOpts().Bool)
9819     return;
9820   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9821 }
9822 
9823 /// AnalyzeImplicitConversions - Find and report any interesting
9824 /// implicit conversions in the given expression.  There are a couple
9825 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9826 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9827   QualType T = OrigE->getType();
9828   Expr *E = OrigE->IgnoreParenImpCasts();
9829 
9830   if (E->isTypeDependent() || E->isValueDependent())
9831     return;
9832 
9833   // For conditional operators, we analyze the arguments as if they
9834   // were being fed directly into the output.
9835   if (isa<ConditionalOperator>(E)) {
9836     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9837     CheckConditionalOperator(S, CO, CC, T);
9838     return;
9839   }
9840 
9841   // Check implicit argument conversions for function calls.
9842   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9843     CheckImplicitArgumentConversions(S, Call, CC);
9844 
9845   // Go ahead and check any implicit conversions we might have skipped.
9846   // The non-canonical typecheck is just an optimization;
9847   // CheckImplicitConversion will filter out dead implicit conversions.
9848   if (E->getType() != T)
9849     CheckImplicitConversion(S, E, T, CC);
9850 
9851   // Now continue drilling into this expression.
9852 
9853   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9854     // The bound subexpressions in a PseudoObjectExpr are not reachable
9855     // as transitive children.
9856     // FIXME: Use a more uniform representation for this.
9857     for (auto *SE : POE->semantics())
9858       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9859         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9860   }
9861 
9862   // Skip past explicit casts.
9863   if (isa<ExplicitCastExpr>(E)) {
9864     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9865     return AnalyzeImplicitConversions(S, E, CC);
9866   }
9867 
9868   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9869     // Do a somewhat different check with comparison operators.
9870     if (BO->isComparisonOp())
9871       return AnalyzeComparison(S, BO);
9872 
9873     // And with simple assignments.
9874     if (BO->getOpcode() == BO_Assign)
9875       return AnalyzeAssignment(S, BO);
9876   }
9877 
9878   // These break the otherwise-useful invariant below.  Fortunately,
9879   // we don't really need to recurse into them, because any internal
9880   // expressions should have been analyzed already when they were
9881   // built into statements.
9882   if (isa<StmtExpr>(E)) return;
9883 
9884   // Don't descend into unevaluated contexts.
9885   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9886 
9887   // Now just recurse over the expression's children.
9888   CC = E->getExprLoc();
9889   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9890   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9891   for (Stmt *SubStmt : E->children()) {
9892     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9893     if (!ChildExpr)
9894       continue;
9895 
9896     if (IsLogicalAndOperator &&
9897         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9898       // Ignore checking string literals that are in logical and operators.
9899       // This is a common pattern for asserts.
9900       continue;
9901     AnalyzeImplicitConversions(S, ChildExpr, CC);
9902   }
9903 
9904   if (BO && BO->isLogicalOp()) {
9905     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9906     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9907       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9908 
9909     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9910     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9911       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9912   }
9913 
9914   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9915     if (U->getOpcode() == UO_LNot)
9916       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9917 }
9918 
9919 } // end anonymous namespace
9920 
9921 /// Diagnose integer type and any valid implicit convertion to it.
9922 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9923   // Taking into account implicit conversions,
9924   // allow any integer.
9925   if (!E->getType()->isIntegerType()) {
9926     S.Diag(E->getLocStart(),
9927            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9928     return true;
9929   }
9930   // Potentially emit standard warnings for implicit conversions if enabled
9931   // using -Wconversion.
9932   CheckImplicitConversion(S, E, IntT, E->getLocStart());
9933   return false;
9934 }
9935 
9936 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9937 // Returns true when emitting a warning about taking the address of a reference.
9938 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9939                               const PartialDiagnostic &PD) {
9940   E = E->IgnoreParenImpCasts();
9941 
9942   const FunctionDecl *FD = nullptr;
9943 
9944   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9945     if (!DRE->getDecl()->getType()->isReferenceType())
9946       return false;
9947   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9948     if (!M->getMemberDecl()->getType()->isReferenceType())
9949       return false;
9950   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9951     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9952       return false;
9953     FD = Call->getDirectCallee();
9954   } else {
9955     return false;
9956   }
9957 
9958   SemaRef.Diag(E->getExprLoc(), PD);
9959 
9960   // If possible, point to location of function.
9961   if (FD) {
9962     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9963   }
9964 
9965   return true;
9966 }
9967 
9968 // Returns true if the SourceLocation is expanded from any macro body.
9969 // Returns false if the SourceLocation is invalid, is from not in a macro
9970 // expansion, or is from expanded from a top-level macro argument.
9971 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9972   if (Loc.isInvalid())
9973     return false;
9974 
9975   while (Loc.isMacroID()) {
9976     if (SM.isMacroBodyExpansion(Loc))
9977       return true;
9978     Loc = SM.getImmediateMacroCallerLoc(Loc);
9979   }
9980 
9981   return false;
9982 }
9983 
9984 /// \brief Diagnose pointers that are always non-null.
9985 /// \param E the expression containing the pointer
9986 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9987 /// compared to a null pointer
9988 /// \param IsEqual True when the comparison is equal to a null pointer
9989 /// \param Range Extra SourceRange to highlight in the diagnostic
9990 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9991                                         Expr::NullPointerConstantKind NullKind,
9992                                         bool IsEqual, SourceRange Range) {
9993   if (!E)
9994     return;
9995 
9996   // Don't warn inside macros.
9997   if (E->getExprLoc().isMacroID()) {
9998     const SourceManager &SM = getSourceManager();
9999     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10000         IsInAnyMacroBody(SM, Range.getBegin()))
10001       return;
10002   }
10003   E = E->IgnoreImpCasts();
10004 
10005   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10006 
10007   if (isa<CXXThisExpr>(E)) {
10008     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10009                                 : diag::warn_this_bool_conversion;
10010     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10011     return;
10012   }
10013 
10014   bool IsAddressOf = false;
10015 
10016   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10017     if (UO->getOpcode() != UO_AddrOf)
10018       return;
10019     IsAddressOf = true;
10020     E = UO->getSubExpr();
10021   }
10022 
10023   if (IsAddressOf) {
10024     unsigned DiagID = IsCompare
10025                           ? diag::warn_address_of_reference_null_compare
10026                           : diag::warn_address_of_reference_bool_conversion;
10027     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10028                                          << IsEqual;
10029     if (CheckForReference(*this, E, PD)) {
10030       return;
10031     }
10032   }
10033 
10034   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10035     bool IsParam = isa<NonNullAttr>(NonnullAttr);
10036     std::string Str;
10037     llvm::raw_string_ostream S(Str);
10038     E->printPretty(S, nullptr, getPrintingPolicy());
10039     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10040                                 : diag::warn_cast_nonnull_to_bool;
10041     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10042       << E->getSourceRange() << Range << IsEqual;
10043     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10044   };
10045 
10046   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10047   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10048     if (auto *Callee = Call->getDirectCallee()) {
10049       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10050         ComplainAboutNonnullParamOrCall(A);
10051         return;
10052       }
10053     }
10054   }
10055 
10056   // Expect to find a single Decl.  Skip anything more complicated.
10057   ValueDecl *D = nullptr;
10058   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10059     D = R->getDecl();
10060   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10061     D = M->getMemberDecl();
10062   }
10063 
10064   // Weak Decls can be null.
10065   if (!D || D->isWeak())
10066     return;
10067 
10068   // Check for parameter decl with nonnull attribute
10069   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10070     if (getCurFunction() &&
10071         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10072       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10073         ComplainAboutNonnullParamOrCall(A);
10074         return;
10075       }
10076 
10077       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10078         auto ParamIter = llvm::find(FD->parameters(), PV);
10079         assert(ParamIter != FD->param_end());
10080         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10081 
10082         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10083           if (!NonNull->args_size()) {
10084               ComplainAboutNonnullParamOrCall(NonNull);
10085               return;
10086           }
10087 
10088           for (unsigned ArgNo : NonNull->args()) {
10089             if (ArgNo == ParamNo) {
10090               ComplainAboutNonnullParamOrCall(NonNull);
10091               return;
10092             }
10093           }
10094         }
10095       }
10096     }
10097   }
10098 
10099   QualType T = D->getType();
10100   const bool IsArray = T->isArrayType();
10101   const bool IsFunction = T->isFunctionType();
10102 
10103   // Address of function is used to silence the function warning.
10104   if (IsAddressOf && IsFunction) {
10105     return;
10106   }
10107 
10108   // Found nothing.
10109   if (!IsAddressOf && !IsFunction && !IsArray)
10110     return;
10111 
10112   // Pretty print the expression for the diagnostic.
10113   std::string Str;
10114   llvm::raw_string_ostream S(Str);
10115   E->printPretty(S, nullptr, getPrintingPolicy());
10116 
10117   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10118                               : diag::warn_impcast_pointer_to_bool;
10119   enum {
10120     AddressOf,
10121     FunctionPointer,
10122     ArrayPointer
10123   } DiagType;
10124   if (IsAddressOf)
10125     DiagType = AddressOf;
10126   else if (IsFunction)
10127     DiagType = FunctionPointer;
10128   else if (IsArray)
10129     DiagType = ArrayPointer;
10130   else
10131     llvm_unreachable("Could not determine diagnostic.");
10132   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10133                                 << Range << IsEqual;
10134 
10135   if (!IsFunction)
10136     return;
10137 
10138   // Suggest '&' to silence the function warning.
10139   Diag(E->getExprLoc(), diag::note_function_warning_silence)
10140       << FixItHint::CreateInsertion(E->getLocStart(), "&");
10141 
10142   // Check to see if '()' fixit should be emitted.
10143   QualType ReturnType;
10144   UnresolvedSet<4> NonTemplateOverloads;
10145   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10146   if (ReturnType.isNull())
10147     return;
10148 
10149   if (IsCompare) {
10150     // There are two cases here.  If there is null constant, the only suggest
10151     // for a pointer return type.  If the null is 0, then suggest if the return
10152     // type is a pointer or an integer type.
10153     if (!ReturnType->isPointerType()) {
10154       if (NullKind == Expr::NPCK_ZeroExpression ||
10155           NullKind == Expr::NPCK_ZeroLiteral) {
10156         if (!ReturnType->isIntegerType())
10157           return;
10158       } else {
10159         return;
10160       }
10161     }
10162   } else { // !IsCompare
10163     // For function to bool, only suggest if the function pointer has bool
10164     // return type.
10165     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10166       return;
10167   }
10168   Diag(E->getExprLoc(), diag::note_function_to_function_call)
10169       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10170 }
10171 
10172 /// Diagnoses "dangerous" implicit conversions within the given
10173 /// expression (which is a full expression).  Implements -Wconversion
10174 /// and -Wsign-compare.
10175 ///
10176 /// \param CC the "context" location of the implicit conversion, i.e.
10177 ///   the most location of the syntactic entity requiring the implicit
10178 ///   conversion
10179 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10180   // Don't diagnose in unevaluated contexts.
10181   if (isUnevaluatedContext())
10182     return;
10183 
10184   // Don't diagnose for value- or type-dependent expressions.
10185   if (E->isTypeDependent() || E->isValueDependent())
10186     return;
10187 
10188   // Check for array bounds violations in cases where the check isn't triggered
10189   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10190   // ArraySubscriptExpr is on the RHS of a variable initialization.
10191   CheckArrayAccess(E);
10192 
10193   // This is not the right CC for (e.g.) a variable initialization.
10194   AnalyzeImplicitConversions(*this, E, CC);
10195 }
10196 
10197 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10198 /// Input argument E is a logical expression.
10199 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10200   ::CheckBoolLikeConversion(*this, E, CC);
10201 }
10202 
10203 /// Diagnose when expression is an integer constant expression and its evaluation
10204 /// results in integer overflow
10205 void Sema::CheckForIntOverflow (Expr *E) {
10206   // Use a work list to deal with nested struct initializers.
10207   SmallVector<Expr *, 2> Exprs(1, E);
10208 
10209   do {
10210     Expr *E = Exprs.pop_back_val();
10211 
10212     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10213       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10214       continue;
10215     }
10216 
10217     if (auto InitList = dyn_cast<InitListExpr>(E))
10218       Exprs.append(InitList->inits().begin(), InitList->inits().end());
10219 
10220     if (isa<ObjCBoxedExpr>(E))
10221       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10222   } while (!Exprs.empty());
10223 }
10224 
10225 namespace {
10226 /// \brief Visitor for expressions which looks for unsequenced operations on the
10227 /// same object.
10228 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10229   typedef EvaluatedExprVisitor<SequenceChecker> Base;
10230 
10231   /// \brief A tree of sequenced regions within an expression. Two regions are
10232   /// unsequenced if one is an ancestor or a descendent of the other. When we
10233   /// finish processing an expression with sequencing, such as a comma
10234   /// expression, we fold its tree nodes into its parent, since they are
10235   /// unsequenced with respect to nodes we will visit later.
10236   class SequenceTree {
10237     struct Value {
10238       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10239       unsigned Parent : 31;
10240       unsigned Merged : 1;
10241     };
10242     SmallVector<Value, 8> Values;
10243 
10244   public:
10245     /// \brief A region within an expression which may be sequenced with respect
10246     /// to some other region.
10247     class Seq {
10248       explicit Seq(unsigned N) : Index(N) {}
10249       unsigned Index;
10250       friend class SequenceTree;
10251     public:
10252       Seq() : Index(0) {}
10253     };
10254 
10255     SequenceTree() { Values.push_back(Value(0)); }
10256     Seq root() const { return Seq(0); }
10257 
10258     /// \brief Create a new sequence of operations, which is an unsequenced
10259     /// subset of \p Parent. This sequence of operations is sequenced with
10260     /// respect to other children of \p Parent.
10261     Seq allocate(Seq Parent) {
10262       Values.push_back(Value(Parent.Index));
10263       return Seq(Values.size() - 1);
10264     }
10265 
10266     /// \brief Merge a sequence of operations into its parent.
10267     void merge(Seq S) {
10268       Values[S.Index].Merged = true;
10269     }
10270 
10271     /// \brief Determine whether two operations are unsequenced. This operation
10272     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10273     /// should have been merged into its parent as appropriate.
10274     bool isUnsequenced(Seq Cur, Seq Old) {
10275       unsigned C = representative(Cur.Index);
10276       unsigned Target = representative(Old.Index);
10277       while (C >= Target) {
10278         if (C == Target)
10279           return true;
10280         C = Values[C].Parent;
10281       }
10282       return false;
10283     }
10284 
10285   private:
10286     /// \brief Pick a representative for a sequence.
10287     unsigned representative(unsigned K) {
10288       if (Values[K].Merged)
10289         // Perform path compression as we go.
10290         return Values[K].Parent = representative(Values[K].Parent);
10291       return K;
10292     }
10293   };
10294 
10295   /// An object for which we can track unsequenced uses.
10296   typedef NamedDecl *Object;
10297 
10298   /// Different flavors of object usage which we track. We only track the
10299   /// least-sequenced usage of each kind.
10300   enum UsageKind {
10301     /// A read of an object. Multiple unsequenced reads are OK.
10302     UK_Use,
10303     /// A modification of an object which is sequenced before the value
10304     /// computation of the expression, such as ++n in C++.
10305     UK_ModAsValue,
10306     /// A modification of an object which is not sequenced before the value
10307     /// computation of the expression, such as n++.
10308     UK_ModAsSideEffect,
10309 
10310     UK_Count = UK_ModAsSideEffect + 1
10311   };
10312 
10313   struct Usage {
10314     Usage() : Use(nullptr), Seq() {}
10315     Expr *Use;
10316     SequenceTree::Seq Seq;
10317   };
10318 
10319   struct UsageInfo {
10320     UsageInfo() : Diagnosed(false) {}
10321     Usage Uses[UK_Count];
10322     /// Have we issued a diagnostic for this variable already?
10323     bool Diagnosed;
10324   };
10325   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10326 
10327   Sema &SemaRef;
10328   /// Sequenced regions within the expression.
10329   SequenceTree Tree;
10330   /// Declaration modifications and references which we have seen.
10331   UsageInfoMap UsageMap;
10332   /// The region we are currently within.
10333   SequenceTree::Seq Region;
10334   /// Filled in with declarations which were modified as a side-effect
10335   /// (that is, post-increment operations).
10336   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
10337   /// Expressions to check later. We defer checking these to reduce
10338   /// stack usage.
10339   SmallVectorImpl<Expr *> &WorkList;
10340 
10341   /// RAII object wrapping the visitation of a sequenced subexpression of an
10342   /// expression. At the end of this process, the side-effects of the evaluation
10343   /// become sequenced with respect to the value computation of the result, so
10344   /// we downgrade any UK_ModAsSideEffect within the evaluation to
10345   /// UK_ModAsValue.
10346   struct SequencedSubexpression {
10347     SequencedSubexpression(SequenceChecker &Self)
10348       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10349       Self.ModAsSideEffect = &ModAsSideEffect;
10350     }
10351     ~SequencedSubexpression() {
10352       for (auto &M : llvm::reverse(ModAsSideEffect)) {
10353         UsageInfo &U = Self.UsageMap[M.first];
10354         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10355         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10356         SideEffectUsage = M.second;
10357       }
10358       Self.ModAsSideEffect = OldModAsSideEffect;
10359     }
10360 
10361     SequenceChecker &Self;
10362     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10363     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
10364   };
10365 
10366   /// RAII object wrapping the visitation of a subexpression which we might
10367   /// choose to evaluate as a constant. If any subexpression is evaluated and
10368   /// found to be non-constant, this allows us to suppress the evaluation of
10369   /// the outer expression.
10370   class EvaluationTracker {
10371   public:
10372     EvaluationTracker(SequenceChecker &Self)
10373         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10374       Self.EvalTracker = this;
10375     }
10376     ~EvaluationTracker() {
10377       Self.EvalTracker = Prev;
10378       if (Prev)
10379         Prev->EvalOK &= EvalOK;
10380     }
10381 
10382     bool evaluate(const Expr *E, bool &Result) {
10383       if (!EvalOK || E->isValueDependent())
10384         return false;
10385       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10386       return EvalOK;
10387     }
10388 
10389   private:
10390     SequenceChecker &Self;
10391     EvaluationTracker *Prev;
10392     bool EvalOK;
10393   } *EvalTracker;
10394 
10395   /// \brief Find the object which is produced by the specified expression,
10396   /// if any.
10397   Object getObject(Expr *E, bool Mod) const {
10398     E = E->IgnoreParenCasts();
10399     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10400       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10401         return getObject(UO->getSubExpr(), Mod);
10402     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10403       if (BO->getOpcode() == BO_Comma)
10404         return getObject(BO->getRHS(), Mod);
10405       if (Mod && BO->isAssignmentOp())
10406         return getObject(BO->getLHS(), Mod);
10407     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10408       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10409       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10410         return ME->getMemberDecl();
10411     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10412       // FIXME: If this is a reference, map through to its value.
10413       return DRE->getDecl();
10414     return nullptr;
10415   }
10416 
10417   /// \brief Note that an object was modified or used by an expression.
10418   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10419     Usage &U = UI.Uses[UK];
10420     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10421       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10422         ModAsSideEffect->push_back(std::make_pair(O, U));
10423       U.Use = Ref;
10424       U.Seq = Region;
10425     }
10426   }
10427   /// \brief Check whether a modification or use conflicts with a prior usage.
10428   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10429                   bool IsModMod) {
10430     if (UI.Diagnosed)
10431       return;
10432 
10433     const Usage &U = UI.Uses[OtherKind];
10434     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10435       return;
10436 
10437     Expr *Mod = U.Use;
10438     Expr *ModOrUse = Ref;
10439     if (OtherKind == UK_Use)
10440       std::swap(Mod, ModOrUse);
10441 
10442     SemaRef.Diag(Mod->getExprLoc(),
10443                  IsModMod ? diag::warn_unsequenced_mod_mod
10444                           : diag::warn_unsequenced_mod_use)
10445       << O << SourceRange(ModOrUse->getExprLoc());
10446     UI.Diagnosed = true;
10447   }
10448 
10449   void notePreUse(Object O, Expr *Use) {
10450     UsageInfo &U = UsageMap[O];
10451     // Uses conflict with other modifications.
10452     checkUsage(O, U, Use, UK_ModAsValue, false);
10453   }
10454   void notePostUse(Object O, Expr *Use) {
10455     UsageInfo &U = UsageMap[O];
10456     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10457     addUsage(U, O, Use, UK_Use);
10458   }
10459 
10460   void notePreMod(Object O, Expr *Mod) {
10461     UsageInfo &U = UsageMap[O];
10462     // Modifications conflict with other modifications and with uses.
10463     checkUsage(O, U, Mod, UK_ModAsValue, true);
10464     checkUsage(O, U, Mod, UK_Use, false);
10465   }
10466   void notePostMod(Object O, Expr *Use, UsageKind UK) {
10467     UsageInfo &U = UsageMap[O];
10468     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10469     addUsage(U, O, Use, UK);
10470   }
10471 
10472 public:
10473   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10474       : Base(S.Context), SemaRef(S), Region(Tree.root()),
10475         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
10476     Visit(E);
10477   }
10478 
10479   void VisitStmt(Stmt *S) {
10480     // Skip all statements which aren't expressions for now.
10481   }
10482 
10483   void VisitExpr(Expr *E) {
10484     // By default, just recurse to evaluated subexpressions.
10485     Base::VisitStmt(E);
10486   }
10487 
10488   void VisitCastExpr(CastExpr *E) {
10489     Object O = Object();
10490     if (E->getCastKind() == CK_LValueToRValue)
10491       O = getObject(E->getSubExpr(), false);
10492 
10493     if (O)
10494       notePreUse(O, E);
10495     VisitExpr(E);
10496     if (O)
10497       notePostUse(O, E);
10498   }
10499 
10500   void VisitBinComma(BinaryOperator *BO) {
10501     // C++11 [expr.comma]p1:
10502     //   Every value computation and side effect associated with the left
10503     //   expression is sequenced before every value computation and side
10504     //   effect associated with the right expression.
10505     SequenceTree::Seq LHS = Tree.allocate(Region);
10506     SequenceTree::Seq RHS = Tree.allocate(Region);
10507     SequenceTree::Seq OldRegion = Region;
10508 
10509     {
10510       SequencedSubexpression SeqLHS(*this);
10511       Region = LHS;
10512       Visit(BO->getLHS());
10513     }
10514 
10515     Region = RHS;
10516     Visit(BO->getRHS());
10517 
10518     Region = OldRegion;
10519 
10520     // Forget that LHS and RHS are sequenced. They are both unsequenced
10521     // with respect to other stuff.
10522     Tree.merge(LHS);
10523     Tree.merge(RHS);
10524   }
10525 
10526   void VisitBinAssign(BinaryOperator *BO) {
10527     // The modification is sequenced after the value computation of the LHS
10528     // and RHS, so check it before inspecting the operands and update the
10529     // map afterwards.
10530     Object O = getObject(BO->getLHS(), true);
10531     if (!O)
10532       return VisitExpr(BO);
10533 
10534     notePreMod(O, BO);
10535 
10536     // C++11 [expr.ass]p7:
10537     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10538     //   only once.
10539     //
10540     // Therefore, for a compound assignment operator, O is considered used
10541     // everywhere except within the evaluation of E1 itself.
10542     if (isa<CompoundAssignOperator>(BO))
10543       notePreUse(O, BO);
10544 
10545     Visit(BO->getLHS());
10546 
10547     if (isa<CompoundAssignOperator>(BO))
10548       notePostUse(O, BO);
10549 
10550     Visit(BO->getRHS());
10551 
10552     // C++11 [expr.ass]p1:
10553     //   the assignment is sequenced [...] before the value computation of the
10554     //   assignment expression.
10555     // C11 6.5.16/3 has no such rule.
10556     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10557                                                        : UK_ModAsSideEffect);
10558   }
10559 
10560   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10561     VisitBinAssign(CAO);
10562   }
10563 
10564   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10565   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10566   void VisitUnaryPreIncDec(UnaryOperator *UO) {
10567     Object O = getObject(UO->getSubExpr(), true);
10568     if (!O)
10569       return VisitExpr(UO);
10570 
10571     notePreMod(O, UO);
10572     Visit(UO->getSubExpr());
10573     // C++11 [expr.pre.incr]p1:
10574     //   the expression ++x is equivalent to x+=1
10575     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10576                                                        : UK_ModAsSideEffect);
10577   }
10578 
10579   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10580   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10581   void VisitUnaryPostIncDec(UnaryOperator *UO) {
10582     Object O = getObject(UO->getSubExpr(), true);
10583     if (!O)
10584       return VisitExpr(UO);
10585 
10586     notePreMod(O, UO);
10587     Visit(UO->getSubExpr());
10588     notePostMod(O, UO, UK_ModAsSideEffect);
10589   }
10590 
10591   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10592   void VisitBinLOr(BinaryOperator *BO) {
10593     // The side-effects of the LHS of an '&&' are sequenced before the
10594     // value computation of the RHS, and hence before the value computation
10595     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10596     // as if they were unconditionally sequenced.
10597     EvaluationTracker Eval(*this);
10598     {
10599       SequencedSubexpression Sequenced(*this);
10600       Visit(BO->getLHS());
10601     }
10602 
10603     bool Result;
10604     if (Eval.evaluate(BO->getLHS(), Result)) {
10605       if (!Result)
10606         Visit(BO->getRHS());
10607     } else {
10608       // Check for unsequenced operations in the RHS, treating it as an
10609       // entirely separate evaluation.
10610       //
10611       // FIXME: If there are operations in the RHS which are unsequenced
10612       // with respect to operations outside the RHS, and those operations
10613       // are unconditionally evaluated, diagnose them.
10614       WorkList.push_back(BO->getRHS());
10615     }
10616   }
10617   void VisitBinLAnd(BinaryOperator *BO) {
10618     EvaluationTracker Eval(*this);
10619     {
10620       SequencedSubexpression Sequenced(*this);
10621       Visit(BO->getLHS());
10622     }
10623 
10624     bool Result;
10625     if (Eval.evaluate(BO->getLHS(), Result)) {
10626       if (Result)
10627         Visit(BO->getRHS());
10628     } else {
10629       WorkList.push_back(BO->getRHS());
10630     }
10631   }
10632 
10633   // Only visit the condition, unless we can be sure which subexpression will
10634   // be chosen.
10635   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10636     EvaluationTracker Eval(*this);
10637     {
10638       SequencedSubexpression Sequenced(*this);
10639       Visit(CO->getCond());
10640     }
10641 
10642     bool Result;
10643     if (Eval.evaluate(CO->getCond(), Result))
10644       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10645     else {
10646       WorkList.push_back(CO->getTrueExpr());
10647       WorkList.push_back(CO->getFalseExpr());
10648     }
10649   }
10650 
10651   void VisitCallExpr(CallExpr *CE) {
10652     // C++11 [intro.execution]p15:
10653     //   When calling a function [...], every value computation and side effect
10654     //   associated with any argument expression, or with the postfix expression
10655     //   designating the called function, is sequenced before execution of every
10656     //   expression or statement in the body of the function [and thus before
10657     //   the value computation of its result].
10658     SequencedSubexpression Sequenced(*this);
10659     Base::VisitCallExpr(CE);
10660 
10661     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10662   }
10663 
10664   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10665     // This is a call, so all subexpressions are sequenced before the result.
10666     SequencedSubexpression Sequenced(*this);
10667 
10668     if (!CCE->isListInitialization())
10669       return VisitExpr(CCE);
10670 
10671     // In C++11, list initializations are sequenced.
10672     SmallVector<SequenceTree::Seq, 32> Elts;
10673     SequenceTree::Seq Parent = Region;
10674     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10675                                         E = CCE->arg_end();
10676          I != E; ++I) {
10677       Region = Tree.allocate(Parent);
10678       Elts.push_back(Region);
10679       Visit(*I);
10680     }
10681 
10682     // Forget that the initializers are sequenced.
10683     Region = Parent;
10684     for (unsigned I = 0; I < Elts.size(); ++I)
10685       Tree.merge(Elts[I]);
10686   }
10687 
10688   void VisitInitListExpr(InitListExpr *ILE) {
10689     if (!SemaRef.getLangOpts().CPlusPlus11)
10690       return VisitExpr(ILE);
10691 
10692     // In C++11, list initializations are sequenced.
10693     SmallVector<SequenceTree::Seq, 32> Elts;
10694     SequenceTree::Seq Parent = Region;
10695     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10696       Expr *E = ILE->getInit(I);
10697       if (!E) continue;
10698       Region = Tree.allocate(Parent);
10699       Elts.push_back(Region);
10700       Visit(E);
10701     }
10702 
10703     // Forget that the initializers are sequenced.
10704     Region = Parent;
10705     for (unsigned I = 0; I < Elts.size(); ++I)
10706       Tree.merge(Elts[I]);
10707   }
10708 };
10709 } // end anonymous namespace
10710 
10711 void Sema::CheckUnsequencedOperations(Expr *E) {
10712   SmallVector<Expr *, 8> WorkList;
10713   WorkList.push_back(E);
10714   while (!WorkList.empty()) {
10715     Expr *Item = WorkList.pop_back_val();
10716     SequenceChecker(*this, Item, WorkList);
10717   }
10718 }
10719 
10720 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10721                               bool IsConstexpr) {
10722   CheckImplicitConversions(E, CheckLoc);
10723   if (!E->isInstantiationDependent())
10724     CheckUnsequencedOperations(E);
10725   if (!IsConstexpr && !E->isValueDependent())
10726     CheckForIntOverflow(E);
10727   DiagnoseMisalignedMembers();
10728 }
10729 
10730 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10731                                        FieldDecl *BitField,
10732                                        Expr *Init) {
10733   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10734 }
10735 
10736 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10737                                          SourceLocation Loc) {
10738   if (!PType->isVariablyModifiedType())
10739     return;
10740   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10741     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10742     return;
10743   }
10744   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10745     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10746     return;
10747   }
10748   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10749     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10750     return;
10751   }
10752 
10753   const ArrayType *AT = S.Context.getAsArrayType(PType);
10754   if (!AT)
10755     return;
10756 
10757   if (AT->getSizeModifier() != ArrayType::Star) {
10758     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10759     return;
10760   }
10761 
10762   S.Diag(Loc, diag::err_array_star_in_function_definition);
10763 }
10764 
10765 /// CheckParmsForFunctionDef - Check that the parameters of the given
10766 /// function are appropriate for the definition of a function. This
10767 /// takes care of any checks that cannot be performed on the
10768 /// declaration itself, e.g., that the types of each of the function
10769 /// parameters are complete.
10770 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10771                                     bool CheckParameterNames) {
10772   bool HasInvalidParm = false;
10773   for (ParmVarDecl *Param : Parameters) {
10774     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10775     // function declarator that is part of a function definition of
10776     // that function shall not have incomplete type.
10777     //
10778     // This is also C++ [dcl.fct]p6.
10779     if (!Param->isInvalidDecl() &&
10780         RequireCompleteType(Param->getLocation(), Param->getType(),
10781                             diag::err_typecheck_decl_incomplete_type)) {
10782       Param->setInvalidDecl();
10783       HasInvalidParm = true;
10784     }
10785 
10786     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10787     // declaration of each parameter shall include an identifier.
10788     if (CheckParameterNames &&
10789         Param->getIdentifier() == nullptr &&
10790         !Param->isImplicit() &&
10791         !getLangOpts().CPlusPlus)
10792       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10793 
10794     // C99 6.7.5.3p12:
10795     //   If the function declarator is not part of a definition of that
10796     //   function, parameters may have incomplete type and may use the [*]
10797     //   notation in their sequences of declarator specifiers to specify
10798     //   variable length array types.
10799     QualType PType = Param->getOriginalType();
10800     // FIXME: This diagnostic should point the '[*]' if source-location
10801     // information is added for it.
10802     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10803 
10804     // MSVC destroys objects passed by value in the callee.  Therefore a
10805     // function definition which takes such a parameter must be able to call the
10806     // object's destructor.  However, we don't perform any direct access check
10807     // on the dtor.
10808     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10809                                        .getCXXABI()
10810                                        .areArgsDestroyedLeftToRightInCallee()) {
10811       if (!Param->isInvalidDecl()) {
10812         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10813           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10814           if (!ClassDecl->isInvalidDecl() &&
10815               !ClassDecl->hasIrrelevantDestructor() &&
10816               !ClassDecl->isDependentContext()) {
10817             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10818             MarkFunctionReferenced(Param->getLocation(), Destructor);
10819             DiagnoseUseOfDecl(Destructor, Param->getLocation());
10820           }
10821         }
10822       }
10823     }
10824 
10825     // Parameters with the pass_object_size attribute only need to be marked
10826     // constant at function definitions. Because we lack information about
10827     // whether we're on a declaration or definition when we're instantiating the
10828     // attribute, we need to check for constness here.
10829     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10830       if (!Param->getType().isConstQualified())
10831         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10832             << Attr->getSpelling() << 1;
10833   }
10834 
10835   return HasInvalidParm;
10836 }
10837 
10838 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10839 /// or MemberExpr.
10840 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10841                               ASTContext &Context) {
10842   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10843     return Context.getDeclAlign(DRE->getDecl());
10844 
10845   if (const auto *ME = dyn_cast<MemberExpr>(E))
10846     return Context.getDeclAlign(ME->getMemberDecl());
10847 
10848   return TypeAlign;
10849 }
10850 
10851 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10852 /// pointer cast increases the alignment requirements.
10853 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10854   // This is actually a lot of work to potentially be doing on every
10855   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10856   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10857     return;
10858 
10859   // Ignore dependent types.
10860   if (T->isDependentType() || Op->getType()->isDependentType())
10861     return;
10862 
10863   // Require that the destination be a pointer type.
10864   const PointerType *DestPtr = T->getAs<PointerType>();
10865   if (!DestPtr) return;
10866 
10867   // If the destination has alignment 1, we're done.
10868   QualType DestPointee = DestPtr->getPointeeType();
10869   if (DestPointee->isIncompleteType()) return;
10870   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10871   if (DestAlign.isOne()) return;
10872 
10873   // Require that the source be a pointer type.
10874   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10875   if (!SrcPtr) return;
10876   QualType SrcPointee = SrcPtr->getPointeeType();
10877 
10878   // Whitelist casts from cv void*.  We already implicitly
10879   // whitelisted casts to cv void*, since they have alignment 1.
10880   // Also whitelist casts involving incomplete types, which implicitly
10881   // includes 'void'.
10882   if (SrcPointee->isIncompleteType()) return;
10883 
10884   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10885 
10886   if (auto *CE = dyn_cast<CastExpr>(Op)) {
10887     if (CE->getCastKind() == CK_ArrayToPointerDecay)
10888       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10889   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10890     if (UO->getOpcode() == UO_AddrOf)
10891       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10892   }
10893 
10894   if (SrcAlign >= DestAlign) return;
10895 
10896   Diag(TRange.getBegin(), diag::warn_cast_align)
10897     << Op->getType() << T
10898     << static_cast<unsigned>(SrcAlign.getQuantity())
10899     << static_cast<unsigned>(DestAlign.getQuantity())
10900     << TRange << Op->getSourceRange();
10901 }
10902 
10903 /// \brief Check whether this array fits the idiom of a size-one tail padded
10904 /// array member of a struct.
10905 ///
10906 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10907 /// commonly used to emulate flexible arrays in C89 code.
10908 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10909                                     const NamedDecl *ND) {
10910   if (Size != 1 || !ND) return false;
10911 
10912   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10913   if (!FD) return false;
10914 
10915   // Don't consider sizes resulting from macro expansions or template argument
10916   // substitution to form C89 tail-padded arrays.
10917 
10918   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10919   while (TInfo) {
10920     TypeLoc TL = TInfo->getTypeLoc();
10921     // Look through typedefs.
10922     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10923       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10924       TInfo = TDL->getTypeSourceInfo();
10925       continue;
10926     }
10927     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10928       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10929       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10930         return false;
10931     }
10932     break;
10933   }
10934 
10935   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10936   if (!RD) return false;
10937   if (RD->isUnion()) return false;
10938   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10939     if (!CRD->isStandardLayout()) return false;
10940   }
10941 
10942   // See if this is the last field decl in the record.
10943   const Decl *D = FD;
10944   while ((D = D->getNextDeclInContext()))
10945     if (isa<FieldDecl>(D))
10946       return false;
10947   return true;
10948 }
10949 
10950 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10951                             const ArraySubscriptExpr *ASE,
10952                             bool AllowOnePastEnd, bool IndexNegated) {
10953   IndexExpr = IndexExpr->IgnoreParenImpCasts();
10954   if (IndexExpr->isValueDependent())
10955     return;
10956 
10957   const Type *EffectiveType =
10958       BaseExpr->getType()->getPointeeOrArrayElementType();
10959   BaseExpr = BaseExpr->IgnoreParenCasts();
10960   const ConstantArrayType *ArrayTy =
10961     Context.getAsConstantArrayType(BaseExpr->getType());
10962   if (!ArrayTy)
10963     return;
10964 
10965   llvm::APSInt index;
10966   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10967     return;
10968   if (IndexNegated)
10969     index = -index;
10970 
10971   const NamedDecl *ND = nullptr;
10972   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10973     ND = dyn_cast<NamedDecl>(DRE->getDecl());
10974   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10975     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10976 
10977   if (index.isUnsigned() || !index.isNegative()) {
10978     llvm::APInt size = ArrayTy->getSize();
10979     if (!size.isStrictlyPositive())
10980       return;
10981 
10982     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10983     if (BaseType != EffectiveType) {
10984       // Make sure we're comparing apples to apples when comparing index to size
10985       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10986       uint64_t array_typesize = Context.getTypeSize(BaseType);
10987       // Handle ptrarith_typesize being zero, such as when casting to void*
10988       if (!ptrarith_typesize) ptrarith_typesize = 1;
10989       if (ptrarith_typesize != array_typesize) {
10990         // There's a cast to a different size type involved
10991         uint64_t ratio = array_typesize / ptrarith_typesize;
10992         // TODO: Be smarter about handling cases where array_typesize is not a
10993         // multiple of ptrarith_typesize
10994         if (ptrarith_typesize * ratio == array_typesize)
10995           size *= llvm::APInt(size.getBitWidth(), ratio);
10996       }
10997     }
10998 
10999     if (size.getBitWidth() > index.getBitWidth())
11000       index = index.zext(size.getBitWidth());
11001     else if (size.getBitWidth() < index.getBitWidth())
11002       size = size.zext(index.getBitWidth());
11003 
11004     // For array subscripting the index must be less than size, but for pointer
11005     // arithmetic also allow the index (offset) to be equal to size since
11006     // computing the next address after the end of the array is legal and
11007     // commonly done e.g. in C++ iterators and range-based for loops.
11008     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11009       return;
11010 
11011     // Also don't warn for arrays of size 1 which are members of some
11012     // structure. These are often used to approximate flexible arrays in C89
11013     // code.
11014     if (IsTailPaddedMemberArray(*this, size, ND))
11015       return;
11016 
11017     // Suppress the warning if the subscript expression (as identified by the
11018     // ']' location) and the index expression are both from macro expansions
11019     // within a system header.
11020     if (ASE) {
11021       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11022           ASE->getRBracketLoc());
11023       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11024         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11025             IndexExpr->getLocStart());
11026         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11027           return;
11028       }
11029     }
11030 
11031     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11032     if (ASE)
11033       DiagID = diag::warn_array_index_exceeds_bounds;
11034 
11035     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11036                         PDiag(DiagID) << index.toString(10, true)
11037                           << size.toString(10, true)
11038                           << (unsigned)size.getLimitedValue(~0U)
11039                           << IndexExpr->getSourceRange());
11040   } else {
11041     unsigned DiagID = diag::warn_array_index_precedes_bounds;
11042     if (!ASE) {
11043       DiagID = diag::warn_ptr_arith_precedes_bounds;
11044       if (index.isNegative()) index = -index;
11045     }
11046 
11047     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11048                         PDiag(DiagID) << index.toString(10, true)
11049                           << IndexExpr->getSourceRange());
11050   }
11051 
11052   if (!ND) {
11053     // Try harder to find a NamedDecl to point at in the note.
11054     while (const ArraySubscriptExpr *ASE =
11055            dyn_cast<ArraySubscriptExpr>(BaseExpr))
11056       BaseExpr = ASE->getBase()->IgnoreParenCasts();
11057     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11058       ND = dyn_cast<NamedDecl>(DRE->getDecl());
11059     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11060       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11061   }
11062 
11063   if (ND)
11064     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11065                         PDiag(diag::note_array_index_out_of_bounds)
11066                           << ND->getDeclName());
11067 }
11068 
11069 void Sema::CheckArrayAccess(const Expr *expr) {
11070   int AllowOnePastEnd = 0;
11071   while (expr) {
11072     expr = expr->IgnoreParenImpCasts();
11073     switch (expr->getStmtClass()) {
11074       case Stmt::ArraySubscriptExprClass: {
11075         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11076         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11077                          AllowOnePastEnd > 0);
11078         return;
11079       }
11080       case Stmt::OMPArraySectionExprClass: {
11081         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11082         if (ASE->getLowerBound())
11083           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11084                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
11085         return;
11086       }
11087       case Stmt::UnaryOperatorClass: {
11088         // Only unwrap the * and & unary operators
11089         const UnaryOperator *UO = cast<UnaryOperator>(expr);
11090         expr = UO->getSubExpr();
11091         switch (UO->getOpcode()) {
11092           case UO_AddrOf:
11093             AllowOnePastEnd++;
11094             break;
11095           case UO_Deref:
11096             AllowOnePastEnd--;
11097             break;
11098           default:
11099             return;
11100         }
11101         break;
11102       }
11103       case Stmt::ConditionalOperatorClass: {
11104         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11105         if (const Expr *lhs = cond->getLHS())
11106           CheckArrayAccess(lhs);
11107         if (const Expr *rhs = cond->getRHS())
11108           CheckArrayAccess(rhs);
11109         return;
11110       }
11111       case Stmt::CXXOperatorCallExprClass: {
11112         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11113         for (const auto *Arg : OCE->arguments())
11114           CheckArrayAccess(Arg);
11115         return;
11116       }
11117       default:
11118         return;
11119     }
11120   }
11121 }
11122 
11123 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11124 
11125 namespace {
11126   struct RetainCycleOwner {
11127     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
11128     VarDecl *Variable;
11129     SourceRange Range;
11130     SourceLocation Loc;
11131     bool Indirect;
11132 
11133     void setLocsFrom(Expr *e) {
11134       Loc = e->getExprLoc();
11135       Range = e->getSourceRange();
11136     }
11137   };
11138 } // end anonymous namespace
11139 
11140 /// Consider whether capturing the given variable can possibly lead to
11141 /// a retain cycle.
11142 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11143   // In ARC, it's captured strongly iff the variable has __strong
11144   // lifetime.  In MRR, it's captured strongly if the variable is
11145   // __block and has an appropriate type.
11146   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11147     return false;
11148 
11149   owner.Variable = var;
11150   if (ref)
11151     owner.setLocsFrom(ref);
11152   return true;
11153 }
11154 
11155 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11156   while (true) {
11157     e = e->IgnoreParens();
11158     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11159       switch (cast->getCastKind()) {
11160       case CK_BitCast:
11161       case CK_LValueBitCast:
11162       case CK_LValueToRValue:
11163       case CK_ARCReclaimReturnedObject:
11164         e = cast->getSubExpr();
11165         continue;
11166 
11167       default:
11168         return false;
11169       }
11170     }
11171 
11172     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11173       ObjCIvarDecl *ivar = ref->getDecl();
11174       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11175         return false;
11176 
11177       // Try to find a retain cycle in the base.
11178       if (!findRetainCycleOwner(S, ref->getBase(), owner))
11179         return false;
11180 
11181       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11182       owner.Indirect = true;
11183       return true;
11184     }
11185 
11186     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11187       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11188       if (!var) return false;
11189       return considerVariable(var, ref, owner);
11190     }
11191 
11192     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11193       if (member->isArrow()) return false;
11194 
11195       // Don't count this as an indirect ownership.
11196       e = member->getBase();
11197       continue;
11198     }
11199 
11200     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11201       // Only pay attention to pseudo-objects on property references.
11202       ObjCPropertyRefExpr *pre
11203         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11204                                               ->IgnoreParens());
11205       if (!pre) return false;
11206       if (pre->isImplicitProperty()) return false;
11207       ObjCPropertyDecl *property = pre->getExplicitProperty();
11208       if (!property->isRetaining() &&
11209           !(property->getPropertyIvarDecl() &&
11210             property->getPropertyIvarDecl()->getType()
11211               .getObjCLifetime() == Qualifiers::OCL_Strong))
11212           return false;
11213 
11214       owner.Indirect = true;
11215       if (pre->isSuperReceiver()) {
11216         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11217         if (!owner.Variable)
11218           return false;
11219         owner.Loc = pre->getLocation();
11220         owner.Range = pre->getSourceRange();
11221         return true;
11222       }
11223       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11224                               ->getSourceExpr());
11225       continue;
11226     }
11227 
11228     // Array ivars?
11229 
11230     return false;
11231   }
11232 }
11233 
11234 namespace {
11235   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11236     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11237       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11238         Context(Context), Variable(variable), Capturer(nullptr),
11239         VarWillBeReased(false) {}
11240     ASTContext &Context;
11241     VarDecl *Variable;
11242     Expr *Capturer;
11243     bool VarWillBeReased;
11244 
11245     void VisitDeclRefExpr(DeclRefExpr *ref) {
11246       if (ref->getDecl() == Variable && !Capturer)
11247         Capturer = ref;
11248     }
11249 
11250     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11251       if (Capturer) return;
11252       Visit(ref->getBase());
11253       if (Capturer && ref->isFreeIvar())
11254         Capturer = ref;
11255     }
11256 
11257     void VisitBlockExpr(BlockExpr *block) {
11258       // Look inside nested blocks
11259       if (block->getBlockDecl()->capturesVariable(Variable))
11260         Visit(block->getBlockDecl()->getBody());
11261     }
11262 
11263     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11264       if (Capturer) return;
11265       if (OVE->getSourceExpr())
11266         Visit(OVE->getSourceExpr());
11267     }
11268     void VisitBinaryOperator(BinaryOperator *BinOp) {
11269       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11270         return;
11271       Expr *LHS = BinOp->getLHS();
11272       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11273         if (DRE->getDecl() != Variable)
11274           return;
11275         if (Expr *RHS = BinOp->getRHS()) {
11276           RHS = RHS->IgnoreParenCasts();
11277           llvm::APSInt Value;
11278           VarWillBeReased =
11279             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11280         }
11281       }
11282     }
11283   };
11284 } // end anonymous namespace
11285 
11286 /// Check whether the given argument is a block which captures a
11287 /// variable.
11288 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11289   assert(owner.Variable && owner.Loc.isValid());
11290 
11291   e = e->IgnoreParenCasts();
11292 
11293   // Look through [^{...} copy] and Block_copy(^{...}).
11294   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11295     Selector Cmd = ME->getSelector();
11296     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11297       e = ME->getInstanceReceiver();
11298       if (!e)
11299         return nullptr;
11300       e = e->IgnoreParenCasts();
11301     }
11302   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11303     if (CE->getNumArgs() == 1) {
11304       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11305       if (Fn) {
11306         const IdentifierInfo *FnI = Fn->getIdentifier();
11307         if (FnI && FnI->isStr("_Block_copy")) {
11308           e = CE->getArg(0)->IgnoreParenCasts();
11309         }
11310       }
11311     }
11312   }
11313 
11314   BlockExpr *block = dyn_cast<BlockExpr>(e);
11315   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11316     return nullptr;
11317 
11318   FindCaptureVisitor visitor(S.Context, owner.Variable);
11319   visitor.Visit(block->getBlockDecl()->getBody());
11320   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11321 }
11322 
11323 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11324                                 RetainCycleOwner &owner) {
11325   assert(capturer);
11326   assert(owner.Variable && owner.Loc.isValid());
11327 
11328   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11329     << owner.Variable << capturer->getSourceRange();
11330   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11331     << owner.Indirect << owner.Range;
11332 }
11333 
11334 /// Check for a keyword selector that starts with the word 'add' or
11335 /// 'set'.
11336 static bool isSetterLikeSelector(Selector sel) {
11337   if (sel.isUnarySelector()) return false;
11338 
11339   StringRef str = sel.getNameForSlot(0);
11340   while (!str.empty() && str.front() == '_') str = str.substr(1);
11341   if (str.startswith("set"))
11342     str = str.substr(3);
11343   else if (str.startswith("add")) {
11344     // Specially whitelist 'addOperationWithBlock:'.
11345     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11346       return false;
11347     str = str.substr(3);
11348   }
11349   else
11350     return false;
11351 
11352   if (str.empty()) return true;
11353   return !isLowercase(str.front());
11354 }
11355 
11356 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11357                                                     ObjCMessageExpr *Message) {
11358   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11359                                                 Message->getReceiverInterface(),
11360                                                 NSAPI::ClassId_NSMutableArray);
11361   if (!IsMutableArray) {
11362     return None;
11363   }
11364 
11365   Selector Sel = Message->getSelector();
11366 
11367   Optional<NSAPI::NSArrayMethodKind> MKOpt =
11368     S.NSAPIObj->getNSArrayMethodKind(Sel);
11369   if (!MKOpt) {
11370     return None;
11371   }
11372 
11373   NSAPI::NSArrayMethodKind MK = *MKOpt;
11374 
11375   switch (MK) {
11376     case NSAPI::NSMutableArr_addObject:
11377     case NSAPI::NSMutableArr_insertObjectAtIndex:
11378     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11379       return 0;
11380     case NSAPI::NSMutableArr_replaceObjectAtIndex:
11381       return 1;
11382 
11383     default:
11384       return None;
11385   }
11386 
11387   return None;
11388 }
11389 
11390 static
11391 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11392                                                   ObjCMessageExpr *Message) {
11393   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11394                                             Message->getReceiverInterface(),
11395                                             NSAPI::ClassId_NSMutableDictionary);
11396   if (!IsMutableDictionary) {
11397     return None;
11398   }
11399 
11400   Selector Sel = Message->getSelector();
11401 
11402   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11403     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11404   if (!MKOpt) {
11405     return None;
11406   }
11407 
11408   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11409 
11410   switch (MK) {
11411     case NSAPI::NSMutableDict_setObjectForKey:
11412     case NSAPI::NSMutableDict_setValueForKey:
11413     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11414       return 0;
11415 
11416     default:
11417       return None;
11418   }
11419 
11420   return None;
11421 }
11422 
11423 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11424   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11425                                                 Message->getReceiverInterface(),
11426                                                 NSAPI::ClassId_NSMutableSet);
11427 
11428   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11429                                             Message->getReceiverInterface(),
11430                                             NSAPI::ClassId_NSMutableOrderedSet);
11431   if (!IsMutableSet && !IsMutableOrderedSet) {
11432     return None;
11433   }
11434 
11435   Selector Sel = Message->getSelector();
11436 
11437   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11438   if (!MKOpt) {
11439     return None;
11440   }
11441 
11442   NSAPI::NSSetMethodKind MK = *MKOpt;
11443 
11444   switch (MK) {
11445     case NSAPI::NSMutableSet_addObject:
11446     case NSAPI::NSOrderedSet_setObjectAtIndex:
11447     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11448     case NSAPI::NSOrderedSet_insertObjectAtIndex:
11449       return 0;
11450     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11451       return 1;
11452   }
11453 
11454   return None;
11455 }
11456 
11457 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11458   if (!Message->isInstanceMessage()) {
11459     return;
11460   }
11461 
11462   Optional<int> ArgOpt;
11463 
11464   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11465       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11466       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11467     return;
11468   }
11469 
11470   int ArgIndex = *ArgOpt;
11471 
11472   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11473   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11474     Arg = OE->getSourceExpr()->IgnoreImpCasts();
11475   }
11476 
11477   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11478     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11479       if (ArgRE->isObjCSelfExpr()) {
11480         Diag(Message->getSourceRange().getBegin(),
11481              diag::warn_objc_circular_container)
11482           << ArgRE->getDecl()->getName() << StringRef("super");
11483       }
11484     }
11485   } else {
11486     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11487 
11488     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11489       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11490     }
11491 
11492     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11493       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11494         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11495           ValueDecl *Decl = ReceiverRE->getDecl();
11496           Diag(Message->getSourceRange().getBegin(),
11497                diag::warn_objc_circular_container)
11498             << Decl->getName() << Decl->getName();
11499           if (!ArgRE->isObjCSelfExpr()) {
11500             Diag(Decl->getLocation(),
11501                  diag::note_objc_circular_container_declared_here)
11502               << Decl->getName();
11503           }
11504         }
11505       }
11506     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11507       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11508         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11509           ObjCIvarDecl *Decl = IvarRE->getDecl();
11510           Diag(Message->getSourceRange().getBegin(),
11511                diag::warn_objc_circular_container)
11512             << Decl->getName() << Decl->getName();
11513           Diag(Decl->getLocation(),
11514                diag::note_objc_circular_container_declared_here)
11515             << Decl->getName();
11516         }
11517       }
11518     }
11519   }
11520 }
11521 
11522 /// Check a message send to see if it's likely to cause a retain cycle.
11523 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11524   // Only check instance methods whose selector looks like a setter.
11525   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11526     return;
11527 
11528   // Try to find a variable that the receiver is strongly owned by.
11529   RetainCycleOwner owner;
11530   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11531     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11532       return;
11533   } else {
11534     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11535     owner.Variable = getCurMethodDecl()->getSelfDecl();
11536     owner.Loc = msg->getSuperLoc();
11537     owner.Range = msg->getSuperLoc();
11538   }
11539 
11540   // Check whether the receiver is captured by any of the arguments.
11541   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11542     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11543       return diagnoseRetainCycle(*this, capturer, owner);
11544 }
11545 
11546 /// Check a property assign to see if it's likely to cause a retain cycle.
11547 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11548   RetainCycleOwner owner;
11549   if (!findRetainCycleOwner(*this, receiver, owner))
11550     return;
11551 
11552   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11553     diagnoseRetainCycle(*this, capturer, owner);
11554 }
11555 
11556 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11557   RetainCycleOwner Owner;
11558   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11559     return;
11560 
11561   // Because we don't have an expression for the variable, we have to set the
11562   // location explicitly here.
11563   Owner.Loc = Var->getLocation();
11564   Owner.Range = Var->getSourceRange();
11565 
11566   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11567     diagnoseRetainCycle(*this, Capturer, Owner);
11568 }
11569 
11570 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11571                                      Expr *RHS, bool isProperty) {
11572   // Check if RHS is an Objective-C object literal, which also can get
11573   // immediately zapped in a weak reference.  Note that we explicitly
11574   // allow ObjCStringLiterals, since those are designed to never really die.
11575   RHS = RHS->IgnoreParenImpCasts();
11576 
11577   // This enum needs to match with the 'select' in
11578   // warn_objc_arc_literal_assign (off-by-1).
11579   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11580   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11581     return false;
11582 
11583   S.Diag(Loc, diag::warn_arc_literal_assign)
11584     << (unsigned) Kind
11585     << (isProperty ? 0 : 1)
11586     << RHS->getSourceRange();
11587 
11588   return true;
11589 }
11590 
11591 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11592                                     Qualifiers::ObjCLifetime LT,
11593                                     Expr *RHS, bool isProperty) {
11594   // Strip off any implicit cast added to get to the one ARC-specific.
11595   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11596     if (cast->getCastKind() == CK_ARCConsumeObject) {
11597       S.Diag(Loc, diag::warn_arc_retained_assign)
11598         << (LT == Qualifiers::OCL_ExplicitNone)
11599         << (isProperty ? 0 : 1)
11600         << RHS->getSourceRange();
11601       return true;
11602     }
11603     RHS = cast->getSubExpr();
11604   }
11605 
11606   if (LT == Qualifiers::OCL_Weak &&
11607       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11608     return true;
11609 
11610   return false;
11611 }
11612 
11613 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11614                               QualType LHS, Expr *RHS) {
11615   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11616 
11617   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11618     return false;
11619 
11620   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11621     return true;
11622 
11623   return false;
11624 }
11625 
11626 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11627                               Expr *LHS, Expr *RHS) {
11628   QualType LHSType;
11629   // PropertyRef on LHS type need be directly obtained from
11630   // its declaration as it has a PseudoType.
11631   ObjCPropertyRefExpr *PRE
11632     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11633   if (PRE && !PRE->isImplicitProperty()) {
11634     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11635     if (PD)
11636       LHSType = PD->getType();
11637   }
11638 
11639   if (LHSType.isNull())
11640     LHSType = LHS->getType();
11641 
11642   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11643 
11644   if (LT == Qualifiers::OCL_Weak) {
11645     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11646       getCurFunction()->markSafeWeakUse(LHS);
11647   }
11648 
11649   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11650     return;
11651 
11652   // FIXME. Check for other life times.
11653   if (LT != Qualifiers::OCL_None)
11654     return;
11655 
11656   if (PRE) {
11657     if (PRE->isImplicitProperty())
11658       return;
11659     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11660     if (!PD)
11661       return;
11662 
11663     unsigned Attributes = PD->getPropertyAttributes();
11664     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11665       // when 'assign' attribute was not explicitly specified
11666       // by user, ignore it and rely on property type itself
11667       // for lifetime info.
11668       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11669       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11670           LHSType->isObjCRetainableType())
11671         return;
11672 
11673       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11674         if (cast->getCastKind() == CK_ARCConsumeObject) {
11675           Diag(Loc, diag::warn_arc_retained_property_assign)
11676           << RHS->getSourceRange();
11677           return;
11678         }
11679         RHS = cast->getSubExpr();
11680       }
11681     }
11682     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11683       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11684         return;
11685     }
11686   }
11687 }
11688 
11689 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11690 
11691 namespace {
11692 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11693                                  SourceLocation StmtLoc,
11694                                  const NullStmt *Body) {
11695   // Do not warn if the body is a macro that expands to nothing, e.g:
11696   //
11697   // #define CALL(x)
11698   // if (condition)
11699   //   CALL(0);
11700   //
11701   if (Body->hasLeadingEmptyMacro())
11702     return false;
11703 
11704   // Get line numbers of statement and body.
11705   bool StmtLineInvalid;
11706   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11707                                                       &StmtLineInvalid);
11708   if (StmtLineInvalid)
11709     return false;
11710 
11711   bool BodyLineInvalid;
11712   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11713                                                       &BodyLineInvalid);
11714   if (BodyLineInvalid)
11715     return false;
11716 
11717   // Warn if null statement and body are on the same line.
11718   if (StmtLine != BodyLine)
11719     return false;
11720 
11721   return true;
11722 }
11723 } // end anonymous namespace
11724 
11725 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11726                                  const Stmt *Body,
11727                                  unsigned DiagID) {
11728   // Since this is a syntactic check, don't emit diagnostic for template
11729   // instantiations, this just adds noise.
11730   if (CurrentInstantiationScope)
11731     return;
11732 
11733   // The body should be a null statement.
11734   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11735   if (!NBody)
11736     return;
11737 
11738   // Do the usual checks.
11739   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11740     return;
11741 
11742   Diag(NBody->getSemiLoc(), DiagID);
11743   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11744 }
11745 
11746 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11747                                  const Stmt *PossibleBody) {
11748   assert(!CurrentInstantiationScope); // Ensured by caller
11749 
11750   SourceLocation StmtLoc;
11751   const Stmt *Body;
11752   unsigned DiagID;
11753   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11754     StmtLoc = FS->getRParenLoc();
11755     Body = FS->getBody();
11756     DiagID = diag::warn_empty_for_body;
11757   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11758     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11759     Body = WS->getBody();
11760     DiagID = diag::warn_empty_while_body;
11761   } else
11762     return; // Neither `for' nor `while'.
11763 
11764   // The body should be a null statement.
11765   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11766   if (!NBody)
11767     return;
11768 
11769   // Skip expensive checks if diagnostic is disabled.
11770   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11771     return;
11772 
11773   // Do the usual checks.
11774   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11775     return;
11776 
11777   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11778   // noise level low, emit diagnostics only if for/while is followed by a
11779   // CompoundStmt, e.g.:
11780   //    for (int i = 0; i < n; i++);
11781   //    {
11782   //      a(i);
11783   //    }
11784   // or if for/while is followed by a statement with more indentation
11785   // than for/while itself:
11786   //    for (int i = 0; i < n; i++);
11787   //      a(i);
11788   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11789   if (!ProbableTypo) {
11790     bool BodyColInvalid;
11791     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11792                              PossibleBody->getLocStart(),
11793                              &BodyColInvalid);
11794     if (BodyColInvalid)
11795       return;
11796 
11797     bool StmtColInvalid;
11798     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11799                              S->getLocStart(),
11800                              &StmtColInvalid);
11801     if (StmtColInvalid)
11802       return;
11803 
11804     if (BodyCol > StmtCol)
11805       ProbableTypo = true;
11806   }
11807 
11808   if (ProbableTypo) {
11809     Diag(NBody->getSemiLoc(), DiagID);
11810     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11811   }
11812 }
11813 
11814 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11815 
11816 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11817 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11818                              SourceLocation OpLoc) {
11819   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11820     return;
11821 
11822   if (inTemplateInstantiation())
11823     return;
11824 
11825   // Strip parens and casts away.
11826   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11827   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11828 
11829   // Check for a call expression
11830   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11831   if (!CE || CE->getNumArgs() != 1)
11832     return;
11833 
11834   // Check for a call to std::move
11835   if (!CE->isCallToStdMove())
11836     return;
11837 
11838   // Get argument from std::move
11839   RHSExpr = CE->getArg(0);
11840 
11841   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11842   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11843 
11844   // Two DeclRefExpr's, check that the decls are the same.
11845   if (LHSDeclRef && RHSDeclRef) {
11846     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11847       return;
11848     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11849         RHSDeclRef->getDecl()->getCanonicalDecl())
11850       return;
11851 
11852     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11853                                         << LHSExpr->getSourceRange()
11854                                         << RHSExpr->getSourceRange();
11855     return;
11856   }
11857 
11858   // Member variables require a different approach to check for self moves.
11859   // MemberExpr's are the same if every nested MemberExpr refers to the same
11860   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11861   // the base Expr's are CXXThisExpr's.
11862   const Expr *LHSBase = LHSExpr;
11863   const Expr *RHSBase = RHSExpr;
11864   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11865   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11866   if (!LHSME || !RHSME)
11867     return;
11868 
11869   while (LHSME && RHSME) {
11870     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11871         RHSME->getMemberDecl()->getCanonicalDecl())
11872       return;
11873 
11874     LHSBase = LHSME->getBase();
11875     RHSBase = RHSME->getBase();
11876     LHSME = dyn_cast<MemberExpr>(LHSBase);
11877     RHSME = dyn_cast<MemberExpr>(RHSBase);
11878   }
11879 
11880   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11881   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11882   if (LHSDeclRef && RHSDeclRef) {
11883     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11884       return;
11885     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11886         RHSDeclRef->getDecl()->getCanonicalDecl())
11887       return;
11888 
11889     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11890                                         << LHSExpr->getSourceRange()
11891                                         << RHSExpr->getSourceRange();
11892     return;
11893   }
11894 
11895   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11896     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11897                                         << LHSExpr->getSourceRange()
11898                                         << RHSExpr->getSourceRange();
11899 }
11900 
11901 //===--- Layout compatibility ----------------------------------------------//
11902 
11903 namespace {
11904 
11905 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11906 
11907 /// \brief Check if two enumeration types are layout-compatible.
11908 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11909   // C++11 [dcl.enum] p8:
11910   // Two enumeration types are layout-compatible if they have the same
11911   // underlying type.
11912   return ED1->isComplete() && ED2->isComplete() &&
11913          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11914 }
11915 
11916 /// \brief Check if two fields are layout-compatible.
11917 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11918   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11919     return false;
11920 
11921   if (Field1->isBitField() != Field2->isBitField())
11922     return false;
11923 
11924   if (Field1->isBitField()) {
11925     // Make sure that the bit-fields are the same length.
11926     unsigned Bits1 = Field1->getBitWidthValue(C);
11927     unsigned Bits2 = Field2->getBitWidthValue(C);
11928 
11929     if (Bits1 != Bits2)
11930       return false;
11931   }
11932 
11933   return true;
11934 }
11935 
11936 /// \brief Check if two standard-layout structs are layout-compatible.
11937 /// (C++11 [class.mem] p17)
11938 bool isLayoutCompatibleStruct(ASTContext &C,
11939                               RecordDecl *RD1,
11940                               RecordDecl *RD2) {
11941   // If both records are C++ classes, check that base classes match.
11942   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11943     // If one of records is a CXXRecordDecl we are in C++ mode,
11944     // thus the other one is a CXXRecordDecl, too.
11945     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11946     // Check number of base classes.
11947     if (D1CXX->getNumBases() != D2CXX->getNumBases())
11948       return false;
11949 
11950     // Check the base classes.
11951     for (CXXRecordDecl::base_class_const_iterator
11952                Base1 = D1CXX->bases_begin(),
11953            BaseEnd1 = D1CXX->bases_end(),
11954               Base2 = D2CXX->bases_begin();
11955          Base1 != BaseEnd1;
11956          ++Base1, ++Base2) {
11957       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11958         return false;
11959     }
11960   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11961     // If only RD2 is a C++ class, it should have zero base classes.
11962     if (D2CXX->getNumBases() > 0)
11963       return false;
11964   }
11965 
11966   // Check the fields.
11967   RecordDecl::field_iterator Field2 = RD2->field_begin(),
11968                              Field2End = RD2->field_end(),
11969                              Field1 = RD1->field_begin(),
11970                              Field1End = RD1->field_end();
11971   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11972     if (!isLayoutCompatible(C, *Field1, *Field2))
11973       return false;
11974   }
11975   if (Field1 != Field1End || Field2 != Field2End)
11976     return false;
11977 
11978   return true;
11979 }
11980 
11981 /// \brief Check if two standard-layout unions are layout-compatible.
11982 /// (C++11 [class.mem] p18)
11983 bool isLayoutCompatibleUnion(ASTContext &C,
11984                              RecordDecl *RD1,
11985                              RecordDecl *RD2) {
11986   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11987   for (auto *Field2 : RD2->fields())
11988     UnmatchedFields.insert(Field2);
11989 
11990   for (auto *Field1 : RD1->fields()) {
11991     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11992         I = UnmatchedFields.begin(),
11993         E = UnmatchedFields.end();
11994 
11995     for ( ; I != E; ++I) {
11996       if (isLayoutCompatible(C, Field1, *I)) {
11997         bool Result = UnmatchedFields.erase(*I);
11998         (void) Result;
11999         assert(Result);
12000         break;
12001       }
12002     }
12003     if (I == E)
12004       return false;
12005   }
12006 
12007   return UnmatchedFields.empty();
12008 }
12009 
12010 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
12011   if (RD1->isUnion() != RD2->isUnion())
12012     return false;
12013 
12014   if (RD1->isUnion())
12015     return isLayoutCompatibleUnion(C, RD1, RD2);
12016   else
12017     return isLayoutCompatibleStruct(C, RD1, RD2);
12018 }
12019 
12020 /// \brief Check if two types are layout-compatible in C++11 sense.
12021 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12022   if (T1.isNull() || T2.isNull())
12023     return false;
12024 
12025   // C++11 [basic.types] p11:
12026   // If two types T1 and T2 are the same type, then T1 and T2 are
12027   // layout-compatible types.
12028   if (C.hasSameType(T1, T2))
12029     return true;
12030 
12031   T1 = T1.getCanonicalType().getUnqualifiedType();
12032   T2 = T2.getCanonicalType().getUnqualifiedType();
12033 
12034   const Type::TypeClass TC1 = T1->getTypeClass();
12035   const Type::TypeClass TC2 = T2->getTypeClass();
12036 
12037   if (TC1 != TC2)
12038     return false;
12039 
12040   if (TC1 == Type::Enum) {
12041     return isLayoutCompatible(C,
12042                               cast<EnumType>(T1)->getDecl(),
12043                               cast<EnumType>(T2)->getDecl());
12044   } else if (TC1 == Type::Record) {
12045     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12046       return false;
12047 
12048     return isLayoutCompatible(C,
12049                               cast<RecordType>(T1)->getDecl(),
12050                               cast<RecordType>(T2)->getDecl());
12051   }
12052 
12053   return false;
12054 }
12055 } // end anonymous namespace
12056 
12057 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12058 
12059 namespace {
12060 /// \brief Given a type tag expression find the type tag itself.
12061 ///
12062 /// \param TypeExpr Type tag expression, as it appears in user's code.
12063 ///
12064 /// \param VD Declaration of an identifier that appears in a type tag.
12065 ///
12066 /// \param MagicValue Type tag magic value.
12067 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12068                      const ValueDecl **VD, uint64_t *MagicValue) {
12069   while(true) {
12070     if (!TypeExpr)
12071       return false;
12072 
12073     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12074 
12075     switch (TypeExpr->getStmtClass()) {
12076     case Stmt::UnaryOperatorClass: {
12077       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12078       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12079         TypeExpr = UO->getSubExpr();
12080         continue;
12081       }
12082       return false;
12083     }
12084 
12085     case Stmt::DeclRefExprClass: {
12086       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12087       *VD = DRE->getDecl();
12088       return true;
12089     }
12090 
12091     case Stmt::IntegerLiteralClass: {
12092       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12093       llvm::APInt MagicValueAPInt = IL->getValue();
12094       if (MagicValueAPInt.getActiveBits() <= 64) {
12095         *MagicValue = MagicValueAPInt.getZExtValue();
12096         return true;
12097       } else
12098         return false;
12099     }
12100 
12101     case Stmt::BinaryConditionalOperatorClass:
12102     case Stmt::ConditionalOperatorClass: {
12103       const AbstractConditionalOperator *ACO =
12104           cast<AbstractConditionalOperator>(TypeExpr);
12105       bool Result;
12106       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12107         if (Result)
12108           TypeExpr = ACO->getTrueExpr();
12109         else
12110           TypeExpr = ACO->getFalseExpr();
12111         continue;
12112       }
12113       return false;
12114     }
12115 
12116     case Stmt::BinaryOperatorClass: {
12117       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12118       if (BO->getOpcode() == BO_Comma) {
12119         TypeExpr = BO->getRHS();
12120         continue;
12121       }
12122       return false;
12123     }
12124 
12125     default:
12126       return false;
12127     }
12128   }
12129 }
12130 
12131 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
12132 ///
12133 /// \param TypeExpr Expression that specifies a type tag.
12134 ///
12135 /// \param MagicValues Registered magic values.
12136 ///
12137 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12138 ///        kind.
12139 ///
12140 /// \param TypeInfo Information about the corresponding C type.
12141 ///
12142 /// \returns true if the corresponding C type was found.
12143 bool GetMatchingCType(
12144         const IdentifierInfo *ArgumentKind,
12145         const Expr *TypeExpr, const ASTContext &Ctx,
12146         const llvm::DenseMap<Sema::TypeTagMagicValue,
12147                              Sema::TypeTagData> *MagicValues,
12148         bool &FoundWrongKind,
12149         Sema::TypeTagData &TypeInfo) {
12150   FoundWrongKind = false;
12151 
12152   // Variable declaration that has type_tag_for_datatype attribute.
12153   const ValueDecl *VD = nullptr;
12154 
12155   uint64_t MagicValue;
12156 
12157   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12158     return false;
12159 
12160   if (VD) {
12161     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12162       if (I->getArgumentKind() != ArgumentKind) {
12163         FoundWrongKind = true;
12164         return false;
12165       }
12166       TypeInfo.Type = I->getMatchingCType();
12167       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12168       TypeInfo.MustBeNull = I->getMustBeNull();
12169       return true;
12170     }
12171     return false;
12172   }
12173 
12174   if (!MagicValues)
12175     return false;
12176 
12177   llvm::DenseMap<Sema::TypeTagMagicValue,
12178                  Sema::TypeTagData>::const_iterator I =
12179       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12180   if (I == MagicValues->end())
12181     return false;
12182 
12183   TypeInfo = I->second;
12184   return true;
12185 }
12186 } // end anonymous namespace
12187 
12188 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12189                                       uint64_t MagicValue, QualType Type,
12190                                       bool LayoutCompatible,
12191                                       bool MustBeNull) {
12192   if (!TypeTagForDatatypeMagicValues)
12193     TypeTagForDatatypeMagicValues.reset(
12194         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12195 
12196   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12197   (*TypeTagForDatatypeMagicValues)[Magic] =
12198       TypeTagData(Type, LayoutCompatible, MustBeNull);
12199 }
12200 
12201 namespace {
12202 bool IsSameCharType(QualType T1, QualType T2) {
12203   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12204   if (!BT1)
12205     return false;
12206 
12207   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12208   if (!BT2)
12209     return false;
12210 
12211   BuiltinType::Kind T1Kind = BT1->getKind();
12212   BuiltinType::Kind T2Kind = BT2->getKind();
12213 
12214   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
12215          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
12216          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12217          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12218 }
12219 } // end anonymous namespace
12220 
12221 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12222                                     const Expr * const *ExprArgs) {
12223   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12224   bool IsPointerAttr = Attr->getIsPointer();
12225 
12226   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12227   bool FoundWrongKind;
12228   TypeTagData TypeInfo;
12229   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12230                         TypeTagForDatatypeMagicValues.get(),
12231                         FoundWrongKind, TypeInfo)) {
12232     if (FoundWrongKind)
12233       Diag(TypeTagExpr->getExprLoc(),
12234            diag::warn_type_tag_for_datatype_wrong_kind)
12235         << TypeTagExpr->getSourceRange();
12236     return;
12237   }
12238 
12239   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12240   if (IsPointerAttr) {
12241     // Skip implicit cast of pointer to `void *' (as a function argument).
12242     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12243       if (ICE->getType()->isVoidPointerType() &&
12244           ICE->getCastKind() == CK_BitCast)
12245         ArgumentExpr = ICE->getSubExpr();
12246   }
12247   QualType ArgumentType = ArgumentExpr->getType();
12248 
12249   // Passing a `void*' pointer shouldn't trigger a warning.
12250   if (IsPointerAttr && ArgumentType->isVoidPointerType())
12251     return;
12252 
12253   if (TypeInfo.MustBeNull) {
12254     // Type tag with matching void type requires a null pointer.
12255     if (!ArgumentExpr->isNullPointerConstant(Context,
12256                                              Expr::NPC_ValueDependentIsNotNull)) {
12257       Diag(ArgumentExpr->getExprLoc(),
12258            diag::warn_type_safety_null_pointer_required)
12259           << ArgumentKind->getName()
12260           << ArgumentExpr->getSourceRange()
12261           << TypeTagExpr->getSourceRange();
12262     }
12263     return;
12264   }
12265 
12266   QualType RequiredType = TypeInfo.Type;
12267   if (IsPointerAttr)
12268     RequiredType = Context.getPointerType(RequiredType);
12269 
12270   bool mismatch = false;
12271   if (!TypeInfo.LayoutCompatible) {
12272     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12273 
12274     // C++11 [basic.fundamental] p1:
12275     // Plain char, signed char, and unsigned char are three distinct types.
12276     //
12277     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12278     // char' depending on the current char signedness mode.
12279     if (mismatch)
12280       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12281                                            RequiredType->getPointeeType())) ||
12282           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12283         mismatch = false;
12284   } else
12285     if (IsPointerAttr)
12286       mismatch = !isLayoutCompatible(Context,
12287                                      ArgumentType->getPointeeType(),
12288                                      RequiredType->getPointeeType());
12289     else
12290       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12291 
12292   if (mismatch)
12293     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12294         << ArgumentType << ArgumentKind
12295         << TypeInfo.LayoutCompatible << RequiredType
12296         << ArgumentExpr->getSourceRange()
12297         << TypeTagExpr->getSourceRange();
12298 }
12299 
12300 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12301                                          CharUnits Alignment) {
12302   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12303 }
12304 
12305 void Sema::DiagnoseMisalignedMembers() {
12306   for (MisalignedMember &m : MisalignedMembers) {
12307     const NamedDecl *ND = m.RD;
12308     if (ND->getName().empty()) {
12309       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12310         ND = TD;
12311     }
12312     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12313         << m.MD << ND << m.E->getSourceRange();
12314   }
12315   MisalignedMembers.clear();
12316 }
12317 
12318 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12319   E = E->IgnoreParens();
12320   if (!T->isPointerType() && !T->isIntegerType())
12321     return;
12322   if (isa<UnaryOperator>(E) &&
12323       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12324     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12325     if (isa<MemberExpr>(Op)) {
12326       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12327                           MisalignedMember(Op));
12328       if (MA != MisalignedMembers.end() &&
12329           (T->isIntegerType() ||
12330            (T->isPointerType() &&
12331             Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
12332         MisalignedMembers.erase(MA);
12333     }
12334   }
12335 }
12336 
12337 void Sema::RefersToMemberWithReducedAlignment(
12338     Expr *E,
12339     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12340         Action) {
12341   const auto *ME = dyn_cast<MemberExpr>(E);
12342   if (!ME)
12343     return;
12344 
12345   // No need to check expressions with an __unaligned-qualified type.
12346   if (E->getType().getQualifiers().hasUnaligned())
12347     return;
12348 
12349   // For a chain of MemberExpr like "a.b.c.d" this list
12350   // will keep FieldDecl's like [d, c, b].
12351   SmallVector<FieldDecl *, 4> ReverseMemberChain;
12352   const MemberExpr *TopME = nullptr;
12353   bool AnyIsPacked = false;
12354   do {
12355     QualType BaseType = ME->getBase()->getType();
12356     if (ME->isArrow())
12357       BaseType = BaseType->getPointeeType();
12358     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12359     if (RD->isInvalidDecl())
12360       return;
12361 
12362     ValueDecl *MD = ME->getMemberDecl();
12363     auto *FD = dyn_cast<FieldDecl>(MD);
12364     // We do not care about non-data members.
12365     if (!FD || FD->isInvalidDecl())
12366       return;
12367 
12368     AnyIsPacked =
12369         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12370     ReverseMemberChain.push_back(FD);
12371 
12372     TopME = ME;
12373     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12374   } while (ME);
12375   assert(TopME && "We did not compute a topmost MemberExpr!");
12376 
12377   // Not the scope of this diagnostic.
12378   if (!AnyIsPacked)
12379     return;
12380 
12381   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12382   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12383   // TODO: The innermost base of the member expression may be too complicated.
12384   // For now, just disregard these cases. This is left for future
12385   // improvement.
12386   if (!DRE && !isa<CXXThisExpr>(TopBase))
12387       return;
12388 
12389   // Alignment expected by the whole expression.
12390   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12391 
12392   // No need to do anything else with this case.
12393   if (ExpectedAlignment.isOne())
12394     return;
12395 
12396   // Synthesize offset of the whole access.
12397   CharUnits Offset;
12398   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12399        I++) {
12400     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12401   }
12402 
12403   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12404   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12405       ReverseMemberChain.back()->getParent()->getTypeForDecl());
12406 
12407   // The base expression of the innermost MemberExpr may give
12408   // stronger guarantees than the class containing the member.
12409   if (DRE && !TopME->isArrow()) {
12410     const ValueDecl *VD = DRE->getDecl();
12411     if (!VD->getType()->isReferenceType())
12412       CompleteObjectAlignment =
12413           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12414   }
12415 
12416   // Check if the synthesized offset fulfills the alignment.
12417   if (Offset % ExpectedAlignment != 0 ||
12418       // It may fulfill the offset it but the effective alignment may still be
12419       // lower than the expected expression alignment.
12420       CompleteObjectAlignment < ExpectedAlignment) {
12421     // If this happens, we want to determine a sensible culprit of this.
12422     // Intuitively, watching the chain of member expressions from right to
12423     // left, we start with the required alignment (as required by the field
12424     // type) but some packed attribute in that chain has reduced the alignment.
12425     // It may happen that another packed structure increases it again. But if
12426     // we are here such increase has not been enough. So pointing the first
12427     // FieldDecl that either is packed or else its RecordDecl is,
12428     // seems reasonable.
12429     FieldDecl *FD = nullptr;
12430     CharUnits Alignment;
12431     for (FieldDecl *FDI : ReverseMemberChain) {
12432       if (FDI->hasAttr<PackedAttr>() ||
12433           FDI->getParent()->hasAttr<PackedAttr>()) {
12434         FD = FDI;
12435         Alignment = std::min(
12436             Context.getTypeAlignInChars(FD->getType()),
12437             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12438         break;
12439       }
12440     }
12441     assert(FD && "We did not find a packed FieldDecl!");
12442     Action(E, FD->getParent(), FD, Alignment);
12443   }
12444 }
12445 
12446 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12447   using namespace std::placeholders;
12448   RefersToMemberWithReducedAlignment(
12449       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12450                      _2, _3, _4));
12451 }
12452 
12453