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/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/ConvertUTF.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/Locale.h"
42 #include "llvm/Support/raw_ostream.h"
43 
44 using namespace clang;
45 using namespace sema;
46 
47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48                                                     unsigned ByteNo) const {
49   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50                                Context.getTargetInfo());
51 }
52 
53 /// Checks that a call expression's argument count is the desired number.
54 /// This is useful when doing custom type-checking.  Returns true on error.
55 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56   unsigned argCount = call->getNumArgs();
57   if (argCount == desiredArgCount) return false;
58 
59   if (argCount < desiredArgCount)
60     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61         << 0 /*function call*/ << desiredArgCount << argCount
62         << call->getSourceRange();
63 
64   // Highlight all the excess arguments.
65   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66                     call->getArg(argCount - 1)->getLocEnd());
67 
68   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69     << 0 /*function call*/ << desiredArgCount << argCount
70     << call->getArg(1)->getSourceRange();
71 }
72 
73 /// Check that the first argument to __builtin_annotation is an integer
74 /// and the second argument is a non-wide string literal.
75 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76   if (checkArgCount(S, TheCall, 2))
77     return true;
78 
79   // First argument should be an integer.
80   Expr *ValArg = TheCall->getArg(0);
81   QualType Ty = ValArg->getType();
82   if (!Ty->isIntegerType()) {
83     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84       << ValArg->getSourceRange();
85     return true;
86   }
87 
88   // Second argument should be a constant string.
89   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91   if (!Literal || !Literal->isAscii()) {
92     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93       << StrArg->getSourceRange();
94     return true;
95   }
96 
97   TheCall->setType(Ty);
98   return false;
99 }
100 
101 /// Check that the argument to __builtin_addressof is a glvalue, and set the
102 /// result type to the corresponding pointer type.
103 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104   if (checkArgCount(S, TheCall, 1))
105     return true;
106 
107   ExprResult Arg(TheCall->getArg(0));
108   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109   if (ResultType.isNull())
110     return true;
111 
112   TheCall->setArg(0, Arg.get());
113   TheCall->setType(ResultType);
114   return false;
115 }
116 
117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118   if (checkArgCount(S, TheCall, 3))
119     return true;
120 
121   // First two arguments should be integers.
122   for (unsigned I = 0; I < 2; ++I) {
123     Expr *Arg = TheCall->getArg(I);
124     QualType Ty = Arg->getType();
125     if (!Ty->isIntegerType()) {
126       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127           << Ty << Arg->getSourceRange();
128       return true;
129     }
130   }
131 
132   // Third argument should be a pointer to a non-const integer.
133   // IRGen correctly handles volatile, restrict, and address spaces, and
134   // the other qualifiers aren't possible.
135   {
136     Expr *Arg = TheCall->getArg(2);
137     QualType Ty = Arg->getType();
138     const auto *PtrTy = Ty->getAs<PointerType>();
139     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140           !PtrTy->getPointeeType().isConstQualified())) {
141       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142           << Ty << Arg->getSourceRange();
143       return true;
144     }
145   }
146 
147   return false;
148 }
149 
150 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 		                  CallExpr *TheCall, unsigned SizeIdx,
152                                   unsigned DstSizeIdx) {
153   if (TheCall->getNumArgs() <= SizeIdx ||
154       TheCall->getNumArgs() <= DstSizeIdx)
155     return;
156 
157   const Expr *SizeArg = TheCall->getArg(SizeIdx);
158   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159 
160   llvm::APSInt Size, DstSize;
161 
162   // find out if both sizes are known at compile time
163   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165     return;
166 
167   if (Size.ule(DstSize))
168     return;
169 
170   // confirmed overflow so generate the diagnostic.
171   IdentifierInfo *FnName = FDecl->getIdentifier();
172   SourceLocation SL = TheCall->getLocStart();
173   SourceRange SR = TheCall->getSourceRange();
174 
175   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176 }
177 
178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179   if (checkArgCount(S, BuiltinCall, 2))
180     return true;
181 
182   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184   Expr *Call = BuiltinCall->getArg(0);
185   Expr *Chain = BuiltinCall->getArg(1);
186 
187   if (Call->getStmtClass() != Stmt::CallExprClass) {
188     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189         << Call->getSourceRange();
190     return true;
191   }
192 
193   auto CE = cast<CallExpr>(Call);
194   if (CE->getCallee()->getType()->isBlockPointerType()) {
195     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196         << Call->getSourceRange();
197     return true;
198   }
199 
200   const Decl *TargetDecl = CE->getCalleeDecl();
201   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202     if (FD->getBuiltinID()) {
203       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204           << Call->getSourceRange();
205       return true;
206     }
207 
208   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210         << Call->getSourceRange();
211     return true;
212   }
213 
214   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215   if (ChainResult.isInvalid())
216     return true;
217   if (!ChainResult.get()->getType()->isPointerType()) {
218     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219         << Chain->getSourceRange();
220     return true;
221   }
222 
223   QualType ReturnTy = CE->getCallReturnType(S.Context);
224   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225   QualType BuiltinTy = S.Context.getFunctionType(
226       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228 
229   Builtin =
230       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231 
232   BuiltinCall->setType(CE->getType());
233   BuiltinCall->setValueKind(CE->getValueKind());
234   BuiltinCall->setObjectKind(CE->getObjectKind());
235   BuiltinCall->setCallee(Builtin);
236   BuiltinCall->setArg(1, ChainResult.get());
237 
238   return false;
239 }
240 
241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242                                      Scope::ScopeFlags NeededScopeFlags,
243                                      unsigned DiagID) {
244   // Scopes aren't available during instantiation. Fortunately, builtin
245   // functions cannot be template args so they cannot be formed through template
246   // instantiation. Therefore checking once during the parse is sufficient.
247   if (!SemaRef.ActiveTemplateInstantiations.empty())
248     return false;
249 
250   Scope *S = SemaRef.getCurScope();
251   while (S && !S->isSEHExceptScope())
252     S = S->getParent();
253   if (!S || !(S->getFlags() & NeededScopeFlags)) {
254     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256         << DRE->getDecl()->getIdentifier();
257     return true;
258   }
259 
260   return false;
261 }
262 
263 static inline bool isBlockPointer(Expr *Arg) {
264   return Arg->getType()->isBlockPointerType();
265 }
266 
267 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268 /// void*, which is a requirement of device side enqueue.
269 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270   const BlockPointerType *BPT =
271       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272   ArrayRef<QualType> Params =
273       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274   unsigned ArgCounter = 0;
275   bool IllegalParams = false;
276   // Iterate through the block parameters until either one is found that is not
277   // a local void*, or the block is valid.
278   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279        I != E; ++I, ++ArgCounter) {
280     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282             LangAS::opencl_local) {
283       // Get the location of the error. If a block literal has been passed
284       // (BlockExpr) then we can point straight to the offending argument,
285       // else we just point to the variable reference.
286       SourceLocation ErrorLoc;
287       if (isa<BlockExpr>(BlockArg)) {
288         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290       } else if (isa<DeclRefExpr>(BlockArg)) {
291         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292       }
293       S.Diag(ErrorLoc,
294              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295       IllegalParams = true;
296     }
297   }
298 
299   return IllegalParams;
300 }
301 
302 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303 /// get_kernel_work_group_size
304 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
305 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306   if (checkArgCount(S, TheCall, 1))
307     return true;
308 
309   Expr *BlockArg = TheCall->getArg(0);
310   if (!isBlockPointer(BlockArg)) {
311     S.Diag(BlockArg->getLocStart(),
312            diag::err_opencl_enqueue_kernel_expected_type) << "block";
313     return true;
314   }
315   return checkOpenCLBlockArgs(S, BlockArg);
316 }
317 
318 /// Diagnose integer type and any valid implicit convertion to it.
319 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
320                                       const QualType &IntType);
321 
322 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
323                                             unsigned Start, unsigned End) {
324   bool IllegalParams = false;
325   for (unsigned I = Start; I <= End; ++I)
326     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
327                                               S.Context.getSizeType());
328   return IllegalParams;
329 }
330 
331 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
332 /// 'local void*' parameter of passed block.
333 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
334                                            Expr *BlockArg,
335                                            unsigned NumNonVarArgs) {
336   const BlockPointerType *BPT =
337       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
338   unsigned NumBlockParams =
339       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
340   unsigned TotalNumArgs = TheCall->getNumArgs();
341 
342   // For each argument passed to the block, a corresponding uint needs to
343   // be passed to describe the size of the local memory.
344   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
345     S.Diag(TheCall->getLocStart(),
346            diag::err_opencl_enqueue_kernel_local_size_args);
347     return true;
348   }
349 
350   // Check that the sizes of the local memory are specified by integers.
351   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
352                                          TotalNumArgs - 1);
353 }
354 
355 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
356 /// overload formats specified in Table 6.13.17.1.
357 /// int enqueue_kernel(queue_t queue,
358 ///                    kernel_enqueue_flags_t flags,
359 ///                    const ndrange_t ndrange,
360 ///                    void (^block)(void))
361 /// int enqueue_kernel(queue_t queue,
362 ///                    kernel_enqueue_flags_t flags,
363 ///                    const ndrange_t ndrange,
364 ///                    uint num_events_in_wait_list,
365 ///                    clk_event_t *event_wait_list,
366 ///                    clk_event_t *event_ret,
367 ///                    void (^block)(void))
368 /// int enqueue_kernel(queue_t queue,
369 ///                    kernel_enqueue_flags_t flags,
370 ///                    const ndrange_t ndrange,
371 ///                    void (^block)(local void*, ...),
372 ///                    uint size0, ...)
373 /// int enqueue_kernel(queue_t queue,
374 ///                    kernel_enqueue_flags_t flags,
375 ///                    const ndrange_t ndrange,
376 ///                    uint num_events_in_wait_list,
377 ///                    clk_event_t *event_wait_list,
378 ///                    clk_event_t *event_ret,
379 ///                    void (^block)(local void*, ...),
380 ///                    uint size0, ...)
381 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
382   unsigned NumArgs = TheCall->getNumArgs();
383 
384   if (NumArgs < 4) {
385     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
386     return true;
387   }
388 
389   Expr *Arg0 = TheCall->getArg(0);
390   Expr *Arg1 = TheCall->getArg(1);
391   Expr *Arg2 = TheCall->getArg(2);
392   Expr *Arg3 = TheCall->getArg(3);
393 
394   // First argument always needs to be a queue_t type.
395   if (!Arg0->getType()->isQueueT()) {
396     S.Diag(TheCall->getArg(0)->getLocStart(),
397            diag::err_opencl_enqueue_kernel_expected_type)
398         << S.Context.OCLQueueTy;
399     return true;
400   }
401 
402   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
403   if (!Arg1->getType()->isIntegerType()) {
404     S.Diag(TheCall->getArg(1)->getLocStart(),
405            diag::err_opencl_enqueue_kernel_expected_type)
406         << "'kernel_enqueue_flags_t' (i.e. uint)";
407     return true;
408   }
409 
410   // Third argument is always an ndrange_t type.
411   if (!Arg2->getType()->isNDRangeT()) {
412     S.Diag(TheCall->getArg(2)->getLocStart(),
413            diag::err_opencl_enqueue_kernel_expected_type)
414         << S.Context.OCLNDRangeTy;
415     return true;
416   }
417 
418   // With four arguments, there is only one form that the function could be
419   // called in: no events and no variable arguments.
420   if (NumArgs == 4) {
421     // check that the last argument is the right block type.
422     if (!isBlockPointer(Arg3)) {
423       S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
424           << "block";
425       return true;
426     }
427     // we have a block type, check the prototype
428     const BlockPointerType *BPT =
429         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
430     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
431       S.Diag(Arg3->getLocStart(),
432              diag::err_opencl_enqueue_kernel_blocks_no_args);
433       return true;
434     }
435     return false;
436   }
437   // we can have block + varargs.
438   if (isBlockPointer(Arg3))
439     return (checkOpenCLBlockArgs(S, Arg3) ||
440             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
441   // last two cases with either exactly 7 args or 7 args and varargs.
442   if (NumArgs >= 7) {
443     // check common block argument.
444     Expr *Arg6 = TheCall->getArg(6);
445     if (!isBlockPointer(Arg6)) {
446       S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
447           << "block";
448       return true;
449     }
450     if (checkOpenCLBlockArgs(S, Arg6))
451       return true;
452 
453     // Forth argument has to be any integer type.
454     if (!Arg3->getType()->isIntegerType()) {
455       S.Diag(TheCall->getArg(3)->getLocStart(),
456              diag::err_opencl_enqueue_kernel_expected_type)
457           << "integer";
458       return true;
459     }
460     // check remaining common arguments.
461     Expr *Arg4 = TheCall->getArg(4);
462     Expr *Arg5 = TheCall->getArg(5);
463 
464     // Fifth argument is always passed as a pointer to clk_event_t.
465     if (!Arg4->isNullPointerConstant(S.Context,
466                                      Expr::NPC_ValueDependentIsNotNull) &&
467         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
468       S.Diag(TheCall->getArg(4)->getLocStart(),
469              diag::err_opencl_enqueue_kernel_expected_type)
470           << S.Context.getPointerType(S.Context.OCLClkEventTy);
471       return true;
472     }
473 
474     // Sixth argument is always passed as a pointer to clk_event_t.
475     if (!Arg5->isNullPointerConstant(S.Context,
476                                      Expr::NPC_ValueDependentIsNotNull) &&
477         !(Arg5->getType()->isPointerType() &&
478           Arg5->getType()->getPointeeType()->isClkEventT())) {
479       S.Diag(TheCall->getArg(5)->getLocStart(),
480              diag::err_opencl_enqueue_kernel_expected_type)
481           << S.Context.getPointerType(S.Context.OCLClkEventTy);
482       return true;
483     }
484 
485     if (NumArgs == 7)
486       return false;
487 
488     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
489   }
490 
491   // None of the specific case has been detected, give generic error
492   S.Diag(TheCall->getLocStart(),
493          diag::err_opencl_enqueue_kernel_incorrect_args);
494   return true;
495 }
496 
497 /// Returns OpenCL access qual.
498 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
499     return D->getAttr<OpenCLAccessAttr>();
500 }
501 
502 /// Returns true if pipe element type is different from the pointer.
503 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
504   const Expr *Arg0 = Call->getArg(0);
505   // First argument type should always be pipe.
506   if (!Arg0->getType()->isPipeType()) {
507     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
508         << Call->getDirectCallee() << Arg0->getSourceRange();
509     return true;
510   }
511   OpenCLAccessAttr *AccessQual =
512       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
513   // Validates the access qualifier is compatible with the call.
514   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
515   // read_only and write_only, and assumed to be read_only if no qualifier is
516   // specified.
517   switch (Call->getDirectCallee()->getBuiltinID()) {
518   case Builtin::BIread_pipe:
519   case Builtin::BIreserve_read_pipe:
520   case Builtin::BIcommit_read_pipe:
521   case Builtin::BIwork_group_reserve_read_pipe:
522   case Builtin::BIsub_group_reserve_read_pipe:
523   case Builtin::BIwork_group_commit_read_pipe:
524   case Builtin::BIsub_group_commit_read_pipe:
525     if (!(!AccessQual || AccessQual->isReadOnly())) {
526       S.Diag(Arg0->getLocStart(),
527              diag::err_opencl_builtin_pipe_invalid_access_modifier)
528           << "read_only" << Arg0->getSourceRange();
529       return true;
530     }
531     break;
532   case Builtin::BIwrite_pipe:
533   case Builtin::BIreserve_write_pipe:
534   case Builtin::BIcommit_write_pipe:
535   case Builtin::BIwork_group_reserve_write_pipe:
536   case Builtin::BIsub_group_reserve_write_pipe:
537   case Builtin::BIwork_group_commit_write_pipe:
538   case Builtin::BIsub_group_commit_write_pipe:
539     if (!(AccessQual && AccessQual->isWriteOnly())) {
540       S.Diag(Arg0->getLocStart(),
541              diag::err_opencl_builtin_pipe_invalid_access_modifier)
542           << "write_only" << Arg0->getSourceRange();
543       return true;
544     }
545     break;
546   default:
547     break;
548   }
549   return false;
550 }
551 
552 /// Returns true if pipe element type is different from the pointer.
553 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
554   const Expr *Arg0 = Call->getArg(0);
555   const Expr *ArgIdx = Call->getArg(Idx);
556   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
557   const QualType EltTy = PipeTy->getElementType();
558   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
559   // The Idx argument should be a pointer and the type of the pointer and
560   // the type of pipe element should also be the same.
561   if (!ArgTy ||
562       !S.Context.hasSameType(
563           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
564     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
565         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
566         << ArgIdx->getType() << ArgIdx->getSourceRange();
567     return true;
568   }
569   return false;
570 }
571 
572 // \brief Performs semantic analysis for the read/write_pipe call.
573 // \param S Reference to the semantic analyzer.
574 // \param Call A pointer to the builtin call.
575 // \return True if a semantic error has been found, false otherwise.
576 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
577   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
578   // functions have two forms.
579   switch (Call->getNumArgs()) {
580   case 2: {
581     if (checkOpenCLPipeArg(S, Call))
582       return true;
583     // The call with 2 arguments should be
584     // read/write_pipe(pipe T, T*).
585     // Check packet type T.
586     if (checkOpenCLPipePacketType(S, Call, 1))
587       return true;
588   } break;
589 
590   case 4: {
591     if (checkOpenCLPipeArg(S, Call))
592       return true;
593     // The call with 4 arguments should be
594     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
595     // Check reserve_id_t.
596     if (!Call->getArg(1)->getType()->isReserveIDT()) {
597       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
598           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
599           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
600       return true;
601     }
602 
603     // Check the index.
604     const Expr *Arg2 = Call->getArg(2);
605     if (!Arg2->getType()->isIntegerType() &&
606         !Arg2->getType()->isUnsignedIntegerType()) {
607       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
608           << Call->getDirectCallee() << S.Context.UnsignedIntTy
609           << Arg2->getType() << Arg2->getSourceRange();
610       return true;
611     }
612 
613     // Check packet type T.
614     if (checkOpenCLPipePacketType(S, Call, 3))
615       return true;
616   } break;
617   default:
618     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
619         << Call->getDirectCallee() << Call->getSourceRange();
620     return true;
621   }
622 
623   return false;
624 }
625 
626 // \brief Performs a semantic analysis on the {work_group_/sub_group_
627 //        /_}reserve_{read/write}_pipe
628 // \param S Reference to the semantic analyzer.
629 // \param Call The call to the builtin function to be analyzed.
630 // \return True if a semantic error was found, false otherwise.
631 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
632   if (checkArgCount(S, Call, 2))
633     return true;
634 
635   if (checkOpenCLPipeArg(S, Call))
636     return true;
637 
638   // Check the reserve size.
639   if (!Call->getArg(1)->getType()->isIntegerType() &&
640       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
641     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
642         << Call->getDirectCallee() << S.Context.UnsignedIntTy
643         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
644     return true;
645   }
646 
647   return false;
648 }
649 
650 // \brief Performs a semantic analysis on {work_group_/sub_group_
651 //        /_}commit_{read/write}_pipe
652 // \param S Reference to the semantic analyzer.
653 // \param Call The call to the builtin function to be analyzed.
654 // \return True if a semantic error was found, false otherwise.
655 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
656   if (checkArgCount(S, Call, 2))
657     return true;
658 
659   if (checkOpenCLPipeArg(S, Call))
660     return true;
661 
662   // Check reserve_id_t.
663   if (!Call->getArg(1)->getType()->isReserveIDT()) {
664     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
665         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
666         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
667     return true;
668   }
669 
670   return false;
671 }
672 
673 // \brief Performs a semantic analysis on the call to built-in Pipe
674 //        Query Functions.
675 // \param S Reference to the semantic analyzer.
676 // \param Call The call to the builtin function to be analyzed.
677 // \return True if a semantic error was found, false otherwise.
678 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
679   if (checkArgCount(S, Call, 1))
680     return true;
681 
682   if (!Call->getArg(0)->getType()->isPipeType()) {
683     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
684         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
685     return true;
686   }
687 
688   return false;
689 }
690 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
691 // \brief Performs semantic analysis for the to_global/local/private call.
692 // \param S Reference to the semantic analyzer.
693 // \param BuiltinID ID of the builtin function.
694 // \param Call A pointer to the builtin call.
695 // \return True if a semantic error has been found, false otherwise.
696 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
697                                     CallExpr *Call) {
698   if (Call->getNumArgs() != 1) {
699     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
700         << Call->getDirectCallee() << Call->getSourceRange();
701     return true;
702   }
703 
704   auto RT = Call->getArg(0)->getType();
705   if (!RT->isPointerType() || RT->getPointeeType()
706       .getAddressSpace() == LangAS::opencl_constant) {
707     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
708         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
709     return true;
710   }
711 
712   RT = RT->getPointeeType();
713   auto Qual = RT.getQualifiers();
714   switch (BuiltinID) {
715   case Builtin::BIto_global:
716     Qual.setAddressSpace(LangAS::opencl_global);
717     break;
718   case Builtin::BIto_local:
719     Qual.setAddressSpace(LangAS::opencl_local);
720     break;
721   default:
722     Qual.removeAddressSpace();
723   }
724   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
725       RT.getUnqualifiedType(), Qual)));
726 
727   return false;
728 }
729 
730 ExprResult
731 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
732                                CallExpr *TheCall) {
733   ExprResult TheCallResult(TheCall);
734 
735   // Find out if any arguments are required to be integer constant expressions.
736   unsigned ICEArguments = 0;
737   ASTContext::GetBuiltinTypeError Error;
738   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
739   if (Error != ASTContext::GE_None)
740     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
741 
742   // If any arguments are required to be ICE's, check and diagnose.
743   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
744     // Skip arguments not required to be ICE's.
745     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
746 
747     llvm::APSInt Result;
748     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
749       return true;
750     ICEArguments &= ~(1 << ArgNo);
751   }
752 
753   switch (BuiltinID) {
754   case Builtin::BI__builtin___CFStringMakeConstantString:
755     assert(TheCall->getNumArgs() == 1 &&
756            "Wrong # arguments to builtin CFStringMakeConstantString");
757     if (CheckObjCString(TheCall->getArg(0)))
758       return ExprError();
759     break;
760   case Builtin::BI__builtin_stdarg_start:
761   case Builtin::BI__builtin_va_start:
762     if (SemaBuiltinVAStart(TheCall))
763       return ExprError();
764     break;
765   case Builtin::BI__va_start: {
766     switch (Context.getTargetInfo().getTriple().getArch()) {
767     case llvm::Triple::arm:
768     case llvm::Triple::thumb:
769       if (SemaBuiltinVAStartARM(TheCall))
770         return ExprError();
771       break;
772     default:
773       if (SemaBuiltinVAStart(TheCall))
774         return ExprError();
775       break;
776     }
777     break;
778   }
779   case Builtin::BI__builtin_isgreater:
780   case Builtin::BI__builtin_isgreaterequal:
781   case Builtin::BI__builtin_isless:
782   case Builtin::BI__builtin_islessequal:
783   case Builtin::BI__builtin_islessgreater:
784   case Builtin::BI__builtin_isunordered:
785     if (SemaBuiltinUnorderedCompare(TheCall))
786       return ExprError();
787     break;
788   case Builtin::BI__builtin_fpclassify:
789     if (SemaBuiltinFPClassification(TheCall, 6))
790       return ExprError();
791     break;
792   case Builtin::BI__builtin_isfinite:
793   case Builtin::BI__builtin_isinf:
794   case Builtin::BI__builtin_isinf_sign:
795   case Builtin::BI__builtin_isnan:
796   case Builtin::BI__builtin_isnormal:
797     if (SemaBuiltinFPClassification(TheCall, 1))
798       return ExprError();
799     break;
800   case Builtin::BI__builtin_shufflevector:
801     return SemaBuiltinShuffleVector(TheCall);
802     // TheCall will be freed by the smart pointer here, but that's fine, since
803     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
804   case Builtin::BI__builtin_prefetch:
805     if (SemaBuiltinPrefetch(TheCall))
806       return ExprError();
807     break;
808   case Builtin::BI__builtin_alloca_with_align:
809     if (SemaBuiltinAllocaWithAlign(TheCall))
810       return ExprError();
811     break;
812   case Builtin::BI__assume:
813   case Builtin::BI__builtin_assume:
814     if (SemaBuiltinAssume(TheCall))
815       return ExprError();
816     break;
817   case Builtin::BI__builtin_assume_aligned:
818     if (SemaBuiltinAssumeAligned(TheCall))
819       return ExprError();
820     break;
821   case Builtin::BI__builtin_object_size:
822     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
823       return ExprError();
824     break;
825   case Builtin::BI__builtin_longjmp:
826     if (SemaBuiltinLongjmp(TheCall))
827       return ExprError();
828     break;
829   case Builtin::BI__builtin_setjmp:
830     if (SemaBuiltinSetjmp(TheCall))
831       return ExprError();
832     break;
833   case Builtin::BI_setjmp:
834   case Builtin::BI_setjmpex:
835     if (checkArgCount(*this, TheCall, 1))
836       return true;
837     break;
838 
839   case Builtin::BI__builtin_classify_type:
840     if (checkArgCount(*this, TheCall, 1)) return true;
841     TheCall->setType(Context.IntTy);
842     break;
843   case Builtin::BI__builtin_constant_p:
844     if (checkArgCount(*this, TheCall, 1)) return true;
845     TheCall->setType(Context.IntTy);
846     break;
847   case Builtin::BI__sync_fetch_and_add:
848   case Builtin::BI__sync_fetch_and_add_1:
849   case Builtin::BI__sync_fetch_and_add_2:
850   case Builtin::BI__sync_fetch_and_add_4:
851   case Builtin::BI__sync_fetch_and_add_8:
852   case Builtin::BI__sync_fetch_and_add_16:
853   case Builtin::BI__sync_fetch_and_sub:
854   case Builtin::BI__sync_fetch_and_sub_1:
855   case Builtin::BI__sync_fetch_and_sub_2:
856   case Builtin::BI__sync_fetch_and_sub_4:
857   case Builtin::BI__sync_fetch_and_sub_8:
858   case Builtin::BI__sync_fetch_and_sub_16:
859   case Builtin::BI__sync_fetch_and_or:
860   case Builtin::BI__sync_fetch_and_or_1:
861   case Builtin::BI__sync_fetch_and_or_2:
862   case Builtin::BI__sync_fetch_and_or_4:
863   case Builtin::BI__sync_fetch_and_or_8:
864   case Builtin::BI__sync_fetch_and_or_16:
865   case Builtin::BI__sync_fetch_and_and:
866   case Builtin::BI__sync_fetch_and_and_1:
867   case Builtin::BI__sync_fetch_and_and_2:
868   case Builtin::BI__sync_fetch_and_and_4:
869   case Builtin::BI__sync_fetch_and_and_8:
870   case Builtin::BI__sync_fetch_and_and_16:
871   case Builtin::BI__sync_fetch_and_xor:
872   case Builtin::BI__sync_fetch_and_xor_1:
873   case Builtin::BI__sync_fetch_and_xor_2:
874   case Builtin::BI__sync_fetch_and_xor_4:
875   case Builtin::BI__sync_fetch_and_xor_8:
876   case Builtin::BI__sync_fetch_and_xor_16:
877   case Builtin::BI__sync_fetch_and_nand:
878   case Builtin::BI__sync_fetch_and_nand_1:
879   case Builtin::BI__sync_fetch_and_nand_2:
880   case Builtin::BI__sync_fetch_and_nand_4:
881   case Builtin::BI__sync_fetch_and_nand_8:
882   case Builtin::BI__sync_fetch_and_nand_16:
883   case Builtin::BI__sync_add_and_fetch:
884   case Builtin::BI__sync_add_and_fetch_1:
885   case Builtin::BI__sync_add_and_fetch_2:
886   case Builtin::BI__sync_add_and_fetch_4:
887   case Builtin::BI__sync_add_and_fetch_8:
888   case Builtin::BI__sync_add_and_fetch_16:
889   case Builtin::BI__sync_sub_and_fetch:
890   case Builtin::BI__sync_sub_and_fetch_1:
891   case Builtin::BI__sync_sub_and_fetch_2:
892   case Builtin::BI__sync_sub_and_fetch_4:
893   case Builtin::BI__sync_sub_and_fetch_8:
894   case Builtin::BI__sync_sub_and_fetch_16:
895   case Builtin::BI__sync_and_and_fetch:
896   case Builtin::BI__sync_and_and_fetch_1:
897   case Builtin::BI__sync_and_and_fetch_2:
898   case Builtin::BI__sync_and_and_fetch_4:
899   case Builtin::BI__sync_and_and_fetch_8:
900   case Builtin::BI__sync_and_and_fetch_16:
901   case Builtin::BI__sync_or_and_fetch:
902   case Builtin::BI__sync_or_and_fetch_1:
903   case Builtin::BI__sync_or_and_fetch_2:
904   case Builtin::BI__sync_or_and_fetch_4:
905   case Builtin::BI__sync_or_and_fetch_8:
906   case Builtin::BI__sync_or_and_fetch_16:
907   case Builtin::BI__sync_xor_and_fetch:
908   case Builtin::BI__sync_xor_and_fetch_1:
909   case Builtin::BI__sync_xor_and_fetch_2:
910   case Builtin::BI__sync_xor_and_fetch_4:
911   case Builtin::BI__sync_xor_and_fetch_8:
912   case Builtin::BI__sync_xor_and_fetch_16:
913   case Builtin::BI__sync_nand_and_fetch:
914   case Builtin::BI__sync_nand_and_fetch_1:
915   case Builtin::BI__sync_nand_and_fetch_2:
916   case Builtin::BI__sync_nand_and_fetch_4:
917   case Builtin::BI__sync_nand_and_fetch_8:
918   case Builtin::BI__sync_nand_and_fetch_16:
919   case Builtin::BI__sync_val_compare_and_swap:
920   case Builtin::BI__sync_val_compare_and_swap_1:
921   case Builtin::BI__sync_val_compare_and_swap_2:
922   case Builtin::BI__sync_val_compare_and_swap_4:
923   case Builtin::BI__sync_val_compare_and_swap_8:
924   case Builtin::BI__sync_val_compare_and_swap_16:
925   case Builtin::BI__sync_bool_compare_and_swap:
926   case Builtin::BI__sync_bool_compare_and_swap_1:
927   case Builtin::BI__sync_bool_compare_and_swap_2:
928   case Builtin::BI__sync_bool_compare_and_swap_4:
929   case Builtin::BI__sync_bool_compare_and_swap_8:
930   case Builtin::BI__sync_bool_compare_and_swap_16:
931   case Builtin::BI__sync_lock_test_and_set:
932   case Builtin::BI__sync_lock_test_and_set_1:
933   case Builtin::BI__sync_lock_test_and_set_2:
934   case Builtin::BI__sync_lock_test_and_set_4:
935   case Builtin::BI__sync_lock_test_and_set_8:
936   case Builtin::BI__sync_lock_test_and_set_16:
937   case Builtin::BI__sync_lock_release:
938   case Builtin::BI__sync_lock_release_1:
939   case Builtin::BI__sync_lock_release_2:
940   case Builtin::BI__sync_lock_release_4:
941   case Builtin::BI__sync_lock_release_8:
942   case Builtin::BI__sync_lock_release_16:
943   case Builtin::BI__sync_swap:
944   case Builtin::BI__sync_swap_1:
945   case Builtin::BI__sync_swap_2:
946   case Builtin::BI__sync_swap_4:
947   case Builtin::BI__sync_swap_8:
948   case Builtin::BI__sync_swap_16:
949     return SemaBuiltinAtomicOverloaded(TheCallResult);
950   case Builtin::BI__builtin_nontemporal_load:
951   case Builtin::BI__builtin_nontemporal_store:
952     return SemaBuiltinNontemporalOverloaded(TheCallResult);
953 #define BUILTIN(ID, TYPE, ATTRS)
954 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
955   case Builtin::BI##ID: \
956     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
957 #include "clang/Basic/Builtins.def"
958   case Builtin::BI__builtin_annotation:
959     if (SemaBuiltinAnnotation(*this, TheCall))
960       return ExprError();
961     break;
962   case Builtin::BI__builtin_addressof:
963     if (SemaBuiltinAddressof(*this, TheCall))
964       return ExprError();
965     break;
966   case Builtin::BI__builtin_add_overflow:
967   case Builtin::BI__builtin_sub_overflow:
968   case Builtin::BI__builtin_mul_overflow:
969     if (SemaBuiltinOverflow(*this, TheCall))
970       return ExprError();
971     break;
972   case Builtin::BI__builtin_operator_new:
973   case Builtin::BI__builtin_operator_delete:
974     if (!getLangOpts().CPlusPlus) {
975       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
976         << (BuiltinID == Builtin::BI__builtin_operator_new
977                 ? "__builtin_operator_new"
978                 : "__builtin_operator_delete")
979         << "C++";
980       return ExprError();
981     }
982     // CodeGen assumes it can find the global new and delete to call,
983     // so ensure that they are declared.
984     DeclareGlobalNewDelete();
985     break;
986 
987   // check secure string manipulation functions where overflows
988   // are detectable at compile time
989   case Builtin::BI__builtin___memcpy_chk:
990   case Builtin::BI__builtin___memmove_chk:
991   case Builtin::BI__builtin___memset_chk:
992   case Builtin::BI__builtin___strlcat_chk:
993   case Builtin::BI__builtin___strlcpy_chk:
994   case Builtin::BI__builtin___strncat_chk:
995   case Builtin::BI__builtin___strncpy_chk:
996   case Builtin::BI__builtin___stpncpy_chk:
997     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
998     break;
999   case Builtin::BI__builtin___memccpy_chk:
1000     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1001     break;
1002   case Builtin::BI__builtin___snprintf_chk:
1003   case Builtin::BI__builtin___vsnprintf_chk:
1004     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1005     break;
1006   case Builtin::BI__builtin_call_with_static_chain:
1007     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1008       return ExprError();
1009     break;
1010   case Builtin::BI__exception_code:
1011   case Builtin::BI_exception_code:
1012     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1013                                  diag::err_seh___except_block))
1014       return ExprError();
1015     break;
1016   case Builtin::BI__exception_info:
1017   case Builtin::BI_exception_info:
1018     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1019                                  diag::err_seh___except_filter))
1020       return ExprError();
1021     break;
1022   case Builtin::BI__GetExceptionInfo:
1023     if (checkArgCount(*this, TheCall, 1))
1024       return ExprError();
1025 
1026     if (CheckCXXThrowOperand(
1027             TheCall->getLocStart(),
1028             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1029             TheCall))
1030       return ExprError();
1031 
1032     TheCall->setType(Context.VoidPtrTy);
1033     break;
1034   // OpenCL v2.0, s6.13.16 - Pipe functions
1035   case Builtin::BIread_pipe:
1036   case Builtin::BIwrite_pipe:
1037     // Since those two functions are declared with var args, we need a semantic
1038     // check for the argument.
1039     if (SemaBuiltinRWPipe(*this, TheCall))
1040       return ExprError();
1041     TheCall->setType(Context.IntTy);
1042     break;
1043   case Builtin::BIreserve_read_pipe:
1044   case Builtin::BIreserve_write_pipe:
1045   case Builtin::BIwork_group_reserve_read_pipe:
1046   case Builtin::BIwork_group_reserve_write_pipe:
1047   case Builtin::BIsub_group_reserve_read_pipe:
1048   case Builtin::BIsub_group_reserve_write_pipe:
1049     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1050       return ExprError();
1051     // Since return type of reserve_read/write_pipe built-in function is
1052     // reserve_id_t, which is not defined in the builtin def file , we used int
1053     // as return type and need to override the return type of these functions.
1054     TheCall->setType(Context.OCLReserveIDTy);
1055     break;
1056   case Builtin::BIcommit_read_pipe:
1057   case Builtin::BIcommit_write_pipe:
1058   case Builtin::BIwork_group_commit_read_pipe:
1059   case Builtin::BIwork_group_commit_write_pipe:
1060   case Builtin::BIsub_group_commit_read_pipe:
1061   case Builtin::BIsub_group_commit_write_pipe:
1062     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1063       return ExprError();
1064     break;
1065   case Builtin::BIget_pipe_num_packets:
1066   case Builtin::BIget_pipe_max_packets:
1067     if (SemaBuiltinPipePackets(*this, TheCall))
1068       return ExprError();
1069     TheCall->setType(Context.UnsignedIntTy);
1070     break;
1071   case Builtin::BIto_global:
1072   case Builtin::BIto_local:
1073   case Builtin::BIto_private:
1074     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1075       return ExprError();
1076     break;
1077   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1078   case Builtin::BIenqueue_kernel:
1079     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1080       return ExprError();
1081     break;
1082   case Builtin::BIget_kernel_work_group_size:
1083   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1084     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1085       return ExprError();
1086     break;
1087   case Builtin::BI__builtin_os_log_format:
1088   case Builtin::BI__builtin_os_log_format_buffer_size:
1089     if (SemaBuiltinOSLogFormat(TheCall)) {
1090       return ExprError();
1091     }
1092     break;
1093   }
1094 
1095   // Since the target specific builtins for each arch overlap, only check those
1096   // of the arch we are compiling for.
1097   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1098     switch (Context.getTargetInfo().getTriple().getArch()) {
1099       case llvm::Triple::arm:
1100       case llvm::Triple::armeb:
1101       case llvm::Triple::thumb:
1102       case llvm::Triple::thumbeb:
1103         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1104           return ExprError();
1105         break;
1106       case llvm::Triple::aarch64:
1107       case llvm::Triple::aarch64_be:
1108         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1109           return ExprError();
1110         break;
1111       case llvm::Triple::mips:
1112       case llvm::Triple::mipsel:
1113       case llvm::Triple::mips64:
1114       case llvm::Triple::mips64el:
1115         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1116           return ExprError();
1117         break;
1118       case llvm::Triple::systemz:
1119         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1120           return ExprError();
1121         break;
1122       case llvm::Triple::x86:
1123       case llvm::Triple::x86_64:
1124         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1125           return ExprError();
1126         break;
1127       case llvm::Triple::ppc:
1128       case llvm::Triple::ppc64:
1129       case llvm::Triple::ppc64le:
1130         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1131           return ExprError();
1132         break;
1133       default:
1134         break;
1135     }
1136   }
1137 
1138   return TheCallResult;
1139 }
1140 
1141 // Get the valid immediate range for the specified NEON type code.
1142 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1143   NeonTypeFlags Type(t);
1144   int IsQuad = ForceQuad ? true : Type.isQuad();
1145   switch (Type.getEltType()) {
1146   case NeonTypeFlags::Int8:
1147   case NeonTypeFlags::Poly8:
1148     return shift ? 7 : (8 << IsQuad) - 1;
1149   case NeonTypeFlags::Int16:
1150   case NeonTypeFlags::Poly16:
1151     return shift ? 15 : (4 << IsQuad) - 1;
1152   case NeonTypeFlags::Int32:
1153     return shift ? 31 : (2 << IsQuad) - 1;
1154   case NeonTypeFlags::Int64:
1155   case NeonTypeFlags::Poly64:
1156     return shift ? 63 : (1 << IsQuad) - 1;
1157   case NeonTypeFlags::Poly128:
1158     return shift ? 127 : (1 << IsQuad) - 1;
1159   case NeonTypeFlags::Float16:
1160     assert(!shift && "cannot shift float types!");
1161     return (4 << IsQuad) - 1;
1162   case NeonTypeFlags::Float32:
1163     assert(!shift && "cannot shift float types!");
1164     return (2 << IsQuad) - 1;
1165   case NeonTypeFlags::Float64:
1166     assert(!shift && "cannot shift float types!");
1167     return (1 << IsQuad) - 1;
1168   }
1169   llvm_unreachable("Invalid NeonTypeFlag!");
1170 }
1171 
1172 /// getNeonEltType - Return the QualType corresponding to the elements of
1173 /// the vector type specified by the NeonTypeFlags.  This is used to check
1174 /// the pointer arguments for Neon load/store intrinsics.
1175 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1176                                bool IsPolyUnsigned, bool IsInt64Long) {
1177   switch (Flags.getEltType()) {
1178   case NeonTypeFlags::Int8:
1179     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1180   case NeonTypeFlags::Int16:
1181     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1182   case NeonTypeFlags::Int32:
1183     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1184   case NeonTypeFlags::Int64:
1185     if (IsInt64Long)
1186       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1187     else
1188       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1189                                 : Context.LongLongTy;
1190   case NeonTypeFlags::Poly8:
1191     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1192   case NeonTypeFlags::Poly16:
1193     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1194   case NeonTypeFlags::Poly64:
1195     if (IsInt64Long)
1196       return Context.UnsignedLongTy;
1197     else
1198       return Context.UnsignedLongLongTy;
1199   case NeonTypeFlags::Poly128:
1200     break;
1201   case NeonTypeFlags::Float16:
1202     return Context.HalfTy;
1203   case NeonTypeFlags::Float32:
1204     return Context.FloatTy;
1205   case NeonTypeFlags::Float64:
1206     return Context.DoubleTy;
1207   }
1208   llvm_unreachable("Invalid NeonTypeFlag!");
1209 }
1210 
1211 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1212   llvm::APSInt Result;
1213   uint64_t mask = 0;
1214   unsigned TV = 0;
1215   int PtrArgNum = -1;
1216   bool HasConstPtr = false;
1217   switch (BuiltinID) {
1218 #define GET_NEON_OVERLOAD_CHECK
1219 #include "clang/Basic/arm_neon.inc"
1220 #undef GET_NEON_OVERLOAD_CHECK
1221   }
1222 
1223   // For NEON intrinsics which are overloaded on vector element type, validate
1224   // the immediate which specifies which variant to emit.
1225   unsigned ImmArg = TheCall->getNumArgs()-1;
1226   if (mask) {
1227     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1228       return true;
1229 
1230     TV = Result.getLimitedValue(64);
1231     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1232       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1233         << TheCall->getArg(ImmArg)->getSourceRange();
1234   }
1235 
1236   if (PtrArgNum >= 0) {
1237     // Check that pointer arguments have the specified type.
1238     Expr *Arg = TheCall->getArg(PtrArgNum);
1239     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1240       Arg = ICE->getSubExpr();
1241     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1242     QualType RHSTy = RHS.get()->getType();
1243 
1244     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1245     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
1246     bool IsInt64Long =
1247         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1248     QualType EltTy =
1249         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1250     if (HasConstPtr)
1251       EltTy = EltTy.withConst();
1252     QualType LHSTy = Context.getPointerType(EltTy);
1253     AssignConvertType ConvTy;
1254     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1255     if (RHS.isInvalid())
1256       return true;
1257     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1258                                  RHS.get(), AA_Assigning))
1259       return true;
1260   }
1261 
1262   // For NEON intrinsics which take an immediate value as part of the
1263   // instruction, range check them here.
1264   unsigned i = 0, l = 0, u = 0;
1265   switch (BuiltinID) {
1266   default:
1267     return false;
1268 #define GET_NEON_IMMEDIATE_CHECK
1269 #include "clang/Basic/arm_neon.inc"
1270 #undef GET_NEON_IMMEDIATE_CHECK
1271   }
1272 
1273   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1274 }
1275 
1276 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1277                                         unsigned MaxWidth) {
1278   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1279           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1280           BuiltinID == ARM::BI__builtin_arm_strex ||
1281           BuiltinID == ARM::BI__builtin_arm_stlex ||
1282           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1283           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1284           BuiltinID == AArch64::BI__builtin_arm_strex ||
1285           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1286          "unexpected ARM builtin");
1287   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1288                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1289                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1290                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1291 
1292   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1293 
1294   // Ensure that we have the proper number of arguments.
1295   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1296     return true;
1297 
1298   // Inspect the pointer argument of the atomic builtin.  This should always be
1299   // a pointer type, whose element is an integral scalar or pointer type.
1300   // Because it is a pointer type, we don't have to worry about any implicit
1301   // casts here.
1302   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1303   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1304   if (PointerArgRes.isInvalid())
1305     return true;
1306   PointerArg = PointerArgRes.get();
1307 
1308   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1309   if (!pointerType) {
1310     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1311       << PointerArg->getType() << PointerArg->getSourceRange();
1312     return true;
1313   }
1314 
1315   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1316   // task is to insert the appropriate casts into the AST. First work out just
1317   // what the appropriate type is.
1318   QualType ValType = pointerType->getPointeeType();
1319   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1320   if (IsLdrex)
1321     AddrType.addConst();
1322 
1323   // Issue a warning if the cast is dodgy.
1324   CastKind CastNeeded = CK_NoOp;
1325   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1326     CastNeeded = CK_BitCast;
1327     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1328       << PointerArg->getType()
1329       << Context.getPointerType(AddrType)
1330       << AA_Passing << PointerArg->getSourceRange();
1331   }
1332 
1333   // Finally, do the cast and replace the argument with the corrected version.
1334   AddrType = Context.getPointerType(AddrType);
1335   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1336   if (PointerArgRes.isInvalid())
1337     return true;
1338   PointerArg = PointerArgRes.get();
1339 
1340   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1341 
1342   // In general, we allow ints, floats and pointers to be loaded and stored.
1343   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1344       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1345     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1346       << PointerArg->getType() << PointerArg->getSourceRange();
1347     return true;
1348   }
1349 
1350   // But ARM doesn't have instructions to deal with 128-bit versions.
1351   if (Context.getTypeSize(ValType) > MaxWidth) {
1352     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1353     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1354       << PointerArg->getType() << PointerArg->getSourceRange();
1355     return true;
1356   }
1357 
1358   switch (ValType.getObjCLifetime()) {
1359   case Qualifiers::OCL_None:
1360   case Qualifiers::OCL_ExplicitNone:
1361     // okay
1362     break;
1363 
1364   case Qualifiers::OCL_Weak:
1365   case Qualifiers::OCL_Strong:
1366   case Qualifiers::OCL_Autoreleasing:
1367     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1368       << ValType << PointerArg->getSourceRange();
1369     return true;
1370   }
1371 
1372   if (IsLdrex) {
1373     TheCall->setType(ValType);
1374     return false;
1375   }
1376 
1377   // Initialize the argument to be stored.
1378   ExprResult ValArg = TheCall->getArg(0);
1379   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1380       Context, ValType, /*consume*/ false);
1381   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1382   if (ValArg.isInvalid())
1383     return true;
1384   TheCall->setArg(0, ValArg.get());
1385 
1386   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1387   // but the custom checker bypasses all default analysis.
1388   TheCall->setType(Context.IntTy);
1389   return false;
1390 }
1391 
1392 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1393   llvm::APSInt Result;
1394 
1395   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1396       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1397       BuiltinID == ARM::BI__builtin_arm_strex ||
1398       BuiltinID == ARM::BI__builtin_arm_stlex) {
1399     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1400   }
1401 
1402   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1403     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1404       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1405   }
1406 
1407   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1408       BuiltinID == ARM::BI__builtin_arm_wsr64)
1409     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1410 
1411   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1412       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1413       BuiltinID == ARM::BI__builtin_arm_wsr ||
1414       BuiltinID == ARM::BI__builtin_arm_wsrp)
1415     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1416 
1417   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1418     return true;
1419 
1420   // For intrinsics which take an immediate value as part of the instruction,
1421   // range check them here.
1422   unsigned i = 0, l = 0, u = 0;
1423   switch (BuiltinID) {
1424   default: return false;
1425   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1426   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1427   case ARM::BI__builtin_arm_vcvtr_f:
1428   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1429   case ARM::BI__builtin_arm_dmb:
1430   case ARM::BI__builtin_arm_dsb:
1431   case ARM::BI__builtin_arm_isb:
1432   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1433   }
1434 
1435   // FIXME: VFP Intrinsics should error if VFP not present.
1436   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1437 }
1438 
1439 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1440                                          CallExpr *TheCall) {
1441   llvm::APSInt Result;
1442 
1443   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1444       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1445       BuiltinID == AArch64::BI__builtin_arm_strex ||
1446       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1447     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1448   }
1449 
1450   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1451     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1452       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1453       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1454       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1455   }
1456 
1457   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1458       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1459     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1460 
1461   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1462       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1463       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1464       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1465     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1466 
1467   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1468     return true;
1469 
1470   // For intrinsics which take an immediate value as part of the instruction,
1471   // range check them here.
1472   unsigned i = 0, l = 0, u = 0;
1473   switch (BuiltinID) {
1474   default: return false;
1475   case AArch64::BI__builtin_arm_dmb:
1476   case AArch64::BI__builtin_arm_dsb:
1477   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1478   }
1479 
1480   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1481 }
1482 
1483 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1484 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1485 // ordering for DSP is unspecified. MSA is ordered by the data format used
1486 // by the underlying instruction i.e., df/m, df/n and then by size.
1487 //
1488 // FIXME: The size tests here should instead be tablegen'd along with the
1489 //        definitions from include/clang/Basic/BuiltinsMips.def.
1490 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1491 //        be too.
1492 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1493   unsigned i = 0, l = 0, u = 0, m = 0;
1494   switch (BuiltinID) {
1495   default: return false;
1496   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1497   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1498   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1499   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1500   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1501   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1502   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1503   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1504   // df/m field.
1505   // These intrinsics take an unsigned 3 bit immediate.
1506   case Mips::BI__builtin_msa_bclri_b:
1507   case Mips::BI__builtin_msa_bnegi_b:
1508   case Mips::BI__builtin_msa_bseti_b:
1509   case Mips::BI__builtin_msa_sat_s_b:
1510   case Mips::BI__builtin_msa_sat_u_b:
1511   case Mips::BI__builtin_msa_slli_b:
1512   case Mips::BI__builtin_msa_srai_b:
1513   case Mips::BI__builtin_msa_srari_b:
1514   case Mips::BI__builtin_msa_srli_b:
1515   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1516   case Mips::BI__builtin_msa_binsli_b:
1517   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1518   // These intrinsics take an unsigned 4 bit immediate.
1519   case Mips::BI__builtin_msa_bclri_h:
1520   case Mips::BI__builtin_msa_bnegi_h:
1521   case Mips::BI__builtin_msa_bseti_h:
1522   case Mips::BI__builtin_msa_sat_s_h:
1523   case Mips::BI__builtin_msa_sat_u_h:
1524   case Mips::BI__builtin_msa_slli_h:
1525   case Mips::BI__builtin_msa_srai_h:
1526   case Mips::BI__builtin_msa_srari_h:
1527   case Mips::BI__builtin_msa_srli_h:
1528   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1529   case Mips::BI__builtin_msa_binsli_h:
1530   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1531   // These intrinsics take an unsigned 5 bit immedate.
1532   // The first block of intrinsics actually have an unsigned 5 bit field,
1533   // not a df/n field.
1534   case Mips::BI__builtin_msa_clei_u_b:
1535   case Mips::BI__builtin_msa_clei_u_h:
1536   case Mips::BI__builtin_msa_clei_u_w:
1537   case Mips::BI__builtin_msa_clei_u_d:
1538   case Mips::BI__builtin_msa_clti_u_b:
1539   case Mips::BI__builtin_msa_clti_u_h:
1540   case Mips::BI__builtin_msa_clti_u_w:
1541   case Mips::BI__builtin_msa_clti_u_d:
1542   case Mips::BI__builtin_msa_maxi_u_b:
1543   case Mips::BI__builtin_msa_maxi_u_h:
1544   case Mips::BI__builtin_msa_maxi_u_w:
1545   case Mips::BI__builtin_msa_maxi_u_d:
1546   case Mips::BI__builtin_msa_mini_u_b:
1547   case Mips::BI__builtin_msa_mini_u_h:
1548   case Mips::BI__builtin_msa_mini_u_w:
1549   case Mips::BI__builtin_msa_mini_u_d:
1550   case Mips::BI__builtin_msa_addvi_b:
1551   case Mips::BI__builtin_msa_addvi_h:
1552   case Mips::BI__builtin_msa_addvi_w:
1553   case Mips::BI__builtin_msa_addvi_d:
1554   case Mips::BI__builtin_msa_bclri_w:
1555   case Mips::BI__builtin_msa_bnegi_w:
1556   case Mips::BI__builtin_msa_bseti_w:
1557   case Mips::BI__builtin_msa_sat_s_w:
1558   case Mips::BI__builtin_msa_sat_u_w:
1559   case Mips::BI__builtin_msa_slli_w:
1560   case Mips::BI__builtin_msa_srai_w:
1561   case Mips::BI__builtin_msa_srari_w:
1562   case Mips::BI__builtin_msa_srli_w:
1563   case Mips::BI__builtin_msa_srlri_w:
1564   case Mips::BI__builtin_msa_subvi_b:
1565   case Mips::BI__builtin_msa_subvi_h:
1566   case Mips::BI__builtin_msa_subvi_w:
1567   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1568   case Mips::BI__builtin_msa_binsli_w:
1569   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1570   // These intrinsics take an unsigned 6 bit immediate.
1571   case Mips::BI__builtin_msa_bclri_d:
1572   case Mips::BI__builtin_msa_bnegi_d:
1573   case Mips::BI__builtin_msa_bseti_d:
1574   case Mips::BI__builtin_msa_sat_s_d:
1575   case Mips::BI__builtin_msa_sat_u_d:
1576   case Mips::BI__builtin_msa_slli_d:
1577   case Mips::BI__builtin_msa_srai_d:
1578   case Mips::BI__builtin_msa_srari_d:
1579   case Mips::BI__builtin_msa_srli_d:
1580   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1581   case Mips::BI__builtin_msa_binsli_d:
1582   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1583   // These intrinsics take a signed 5 bit immediate.
1584   case Mips::BI__builtin_msa_ceqi_b:
1585   case Mips::BI__builtin_msa_ceqi_h:
1586   case Mips::BI__builtin_msa_ceqi_w:
1587   case Mips::BI__builtin_msa_ceqi_d:
1588   case Mips::BI__builtin_msa_clti_s_b:
1589   case Mips::BI__builtin_msa_clti_s_h:
1590   case Mips::BI__builtin_msa_clti_s_w:
1591   case Mips::BI__builtin_msa_clti_s_d:
1592   case Mips::BI__builtin_msa_clei_s_b:
1593   case Mips::BI__builtin_msa_clei_s_h:
1594   case Mips::BI__builtin_msa_clei_s_w:
1595   case Mips::BI__builtin_msa_clei_s_d:
1596   case Mips::BI__builtin_msa_maxi_s_b:
1597   case Mips::BI__builtin_msa_maxi_s_h:
1598   case Mips::BI__builtin_msa_maxi_s_w:
1599   case Mips::BI__builtin_msa_maxi_s_d:
1600   case Mips::BI__builtin_msa_mini_s_b:
1601   case Mips::BI__builtin_msa_mini_s_h:
1602   case Mips::BI__builtin_msa_mini_s_w:
1603   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1604   // These intrinsics take an unsigned 8 bit immediate.
1605   case Mips::BI__builtin_msa_andi_b:
1606   case Mips::BI__builtin_msa_nori_b:
1607   case Mips::BI__builtin_msa_ori_b:
1608   case Mips::BI__builtin_msa_shf_b:
1609   case Mips::BI__builtin_msa_shf_h:
1610   case Mips::BI__builtin_msa_shf_w:
1611   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1612   case Mips::BI__builtin_msa_bseli_b:
1613   case Mips::BI__builtin_msa_bmnzi_b:
1614   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1615   // df/n format
1616   // These intrinsics take an unsigned 4 bit immediate.
1617   case Mips::BI__builtin_msa_copy_s_b:
1618   case Mips::BI__builtin_msa_copy_u_b:
1619   case Mips::BI__builtin_msa_insve_b:
1620   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1621   case Mips::BI__builtin_msa_sld_b:
1622   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1623   // These intrinsics take an unsigned 3 bit immediate.
1624   case Mips::BI__builtin_msa_copy_s_h:
1625   case Mips::BI__builtin_msa_copy_u_h:
1626   case Mips::BI__builtin_msa_insve_h:
1627   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1628   case Mips::BI__builtin_msa_sld_h:
1629   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1630   // These intrinsics take an unsigned 2 bit immediate.
1631   case Mips::BI__builtin_msa_copy_s_w:
1632   case Mips::BI__builtin_msa_copy_u_w:
1633   case Mips::BI__builtin_msa_insve_w:
1634   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1635   case Mips::BI__builtin_msa_sld_w:
1636   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1637   // These intrinsics take an unsigned 1 bit immediate.
1638   case Mips::BI__builtin_msa_copy_s_d:
1639   case Mips::BI__builtin_msa_copy_u_d:
1640   case Mips::BI__builtin_msa_insve_d:
1641   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1642   case Mips::BI__builtin_msa_sld_d:
1643   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1644   // Memory offsets and immediate loads.
1645   // These intrinsics take a signed 10 bit immediate.
1646   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1647   case Mips::BI__builtin_msa_ldi_h:
1648   case Mips::BI__builtin_msa_ldi_w:
1649   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1650   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1651   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1652   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1653   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1654   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1655   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1656   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1657   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1658   }
1659 
1660   if (!m)
1661     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1662 
1663   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1664          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1665 }
1666 
1667 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1668   unsigned i = 0, l = 0, u = 0;
1669   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1670                       BuiltinID == PPC::BI__builtin_divdeu ||
1671                       BuiltinID == PPC::BI__builtin_bpermd;
1672   bool IsTarget64Bit = Context.getTargetInfo()
1673                               .getTypeWidth(Context
1674                                             .getTargetInfo()
1675                                             .getIntPtrType()) == 64;
1676   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1677                        BuiltinID == PPC::BI__builtin_divweu ||
1678                        BuiltinID == PPC::BI__builtin_divde ||
1679                        BuiltinID == PPC::BI__builtin_divdeu;
1680 
1681   if (Is64BitBltin && !IsTarget64Bit)
1682       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1683              << TheCall->getSourceRange();
1684 
1685   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1686       (BuiltinID == PPC::BI__builtin_bpermd &&
1687        !Context.getTargetInfo().hasFeature("bpermd")))
1688     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1689            << TheCall->getSourceRange();
1690 
1691   switch (BuiltinID) {
1692   default: return false;
1693   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1694   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1695     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1696            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1697   case PPC::BI__builtin_tbegin:
1698   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1699   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1700   case PPC::BI__builtin_tabortwc:
1701   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1702   case PPC::BI__builtin_tabortwci:
1703   case PPC::BI__builtin_tabortdci:
1704     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1705            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1706   }
1707   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1708 }
1709 
1710 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1711                                            CallExpr *TheCall) {
1712   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1713     Expr *Arg = TheCall->getArg(0);
1714     llvm::APSInt AbortCode(32);
1715     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1716         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1717       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1718              << Arg->getSourceRange();
1719   }
1720 
1721   // For intrinsics which take an immediate value as part of the instruction,
1722   // range check them here.
1723   unsigned i = 0, l = 0, u = 0;
1724   switch (BuiltinID) {
1725   default: return false;
1726   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1727   case SystemZ::BI__builtin_s390_verimb:
1728   case SystemZ::BI__builtin_s390_verimh:
1729   case SystemZ::BI__builtin_s390_verimf:
1730   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1731   case SystemZ::BI__builtin_s390_vfaeb:
1732   case SystemZ::BI__builtin_s390_vfaeh:
1733   case SystemZ::BI__builtin_s390_vfaef:
1734   case SystemZ::BI__builtin_s390_vfaebs:
1735   case SystemZ::BI__builtin_s390_vfaehs:
1736   case SystemZ::BI__builtin_s390_vfaefs:
1737   case SystemZ::BI__builtin_s390_vfaezb:
1738   case SystemZ::BI__builtin_s390_vfaezh:
1739   case SystemZ::BI__builtin_s390_vfaezf:
1740   case SystemZ::BI__builtin_s390_vfaezbs:
1741   case SystemZ::BI__builtin_s390_vfaezhs:
1742   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1743   case SystemZ::BI__builtin_s390_vfidb:
1744     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1745            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1746   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1747   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1748   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1749   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1750   case SystemZ::BI__builtin_s390_vstrcb:
1751   case SystemZ::BI__builtin_s390_vstrch:
1752   case SystemZ::BI__builtin_s390_vstrcf:
1753   case SystemZ::BI__builtin_s390_vstrczb:
1754   case SystemZ::BI__builtin_s390_vstrczh:
1755   case SystemZ::BI__builtin_s390_vstrczf:
1756   case SystemZ::BI__builtin_s390_vstrcbs:
1757   case SystemZ::BI__builtin_s390_vstrchs:
1758   case SystemZ::BI__builtin_s390_vstrcfs:
1759   case SystemZ::BI__builtin_s390_vstrczbs:
1760   case SystemZ::BI__builtin_s390_vstrczhs:
1761   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1762   }
1763   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1764 }
1765 
1766 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1767 /// This checks that the target supports __builtin_cpu_supports and
1768 /// that the string argument is constant and valid.
1769 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1770   Expr *Arg = TheCall->getArg(0);
1771 
1772   // Check if the argument is a string literal.
1773   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1774     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1775            << Arg->getSourceRange();
1776 
1777   // Check the contents of the string.
1778   StringRef Feature =
1779       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1780   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1781     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1782            << Arg->getSourceRange();
1783   return false;
1784 }
1785 
1786 // Check if the rounding mode is legal.
1787 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1788   // Indicates if this instruction has rounding control or just SAE.
1789   bool HasRC = false;
1790 
1791   unsigned ArgNum = 0;
1792   switch (BuiltinID) {
1793   default:
1794     return false;
1795   case X86::BI__builtin_ia32_vcvttsd2si32:
1796   case X86::BI__builtin_ia32_vcvttsd2si64:
1797   case X86::BI__builtin_ia32_vcvttsd2usi32:
1798   case X86::BI__builtin_ia32_vcvttsd2usi64:
1799   case X86::BI__builtin_ia32_vcvttss2si32:
1800   case X86::BI__builtin_ia32_vcvttss2si64:
1801   case X86::BI__builtin_ia32_vcvttss2usi32:
1802   case X86::BI__builtin_ia32_vcvttss2usi64:
1803     ArgNum = 1;
1804     break;
1805   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1806   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1807   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1808   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1809   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1810   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1811   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1812   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1813   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1814   case X86::BI__builtin_ia32_exp2pd_mask:
1815   case X86::BI__builtin_ia32_exp2ps_mask:
1816   case X86::BI__builtin_ia32_getexppd512_mask:
1817   case X86::BI__builtin_ia32_getexpps512_mask:
1818   case X86::BI__builtin_ia32_rcp28pd_mask:
1819   case X86::BI__builtin_ia32_rcp28ps_mask:
1820   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1821   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1822   case X86::BI__builtin_ia32_vcomisd:
1823   case X86::BI__builtin_ia32_vcomiss:
1824   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1825     ArgNum = 3;
1826     break;
1827   case X86::BI__builtin_ia32_cmppd512_mask:
1828   case X86::BI__builtin_ia32_cmpps512_mask:
1829   case X86::BI__builtin_ia32_cmpsd_mask:
1830   case X86::BI__builtin_ia32_cmpss_mask:
1831   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1832   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1833   case X86::BI__builtin_ia32_getexpss128_round_mask:
1834   case X86::BI__builtin_ia32_maxpd512_mask:
1835   case X86::BI__builtin_ia32_maxps512_mask:
1836   case X86::BI__builtin_ia32_maxsd_round_mask:
1837   case X86::BI__builtin_ia32_maxss_round_mask:
1838   case X86::BI__builtin_ia32_minpd512_mask:
1839   case X86::BI__builtin_ia32_minps512_mask:
1840   case X86::BI__builtin_ia32_minsd_round_mask:
1841   case X86::BI__builtin_ia32_minss_round_mask:
1842   case X86::BI__builtin_ia32_rcp28sd_round_mask:
1843   case X86::BI__builtin_ia32_rcp28ss_round_mask:
1844   case X86::BI__builtin_ia32_reducepd512_mask:
1845   case X86::BI__builtin_ia32_reduceps512_mask:
1846   case X86::BI__builtin_ia32_rndscalepd_mask:
1847   case X86::BI__builtin_ia32_rndscaleps_mask:
1848   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1849   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1850     ArgNum = 4;
1851     break;
1852   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1853   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1854   case X86::BI__builtin_ia32_fixupimmps512_mask:
1855   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1856   case X86::BI__builtin_ia32_fixupimmsd_mask:
1857   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1858   case X86::BI__builtin_ia32_fixupimmss_mask:
1859   case X86::BI__builtin_ia32_fixupimmss_maskz:
1860   case X86::BI__builtin_ia32_rangepd512_mask:
1861   case X86::BI__builtin_ia32_rangeps512_mask:
1862   case X86::BI__builtin_ia32_rangesd128_round_mask:
1863   case X86::BI__builtin_ia32_rangess128_round_mask:
1864   case X86::BI__builtin_ia32_reducesd_mask:
1865   case X86::BI__builtin_ia32_reducess_mask:
1866   case X86::BI__builtin_ia32_rndscalesd_round_mask:
1867   case X86::BI__builtin_ia32_rndscaless_round_mask:
1868     ArgNum = 5;
1869     break;
1870   case X86::BI__builtin_ia32_vcvtsd2si64:
1871   case X86::BI__builtin_ia32_vcvtsd2si32:
1872   case X86::BI__builtin_ia32_vcvtsd2usi32:
1873   case X86::BI__builtin_ia32_vcvtsd2usi64:
1874   case X86::BI__builtin_ia32_vcvtss2si32:
1875   case X86::BI__builtin_ia32_vcvtss2si64:
1876   case X86::BI__builtin_ia32_vcvtss2usi32:
1877   case X86::BI__builtin_ia32_vcvtss2usi64:
1878     ArgNum = 1;
1879     HasRC = true;
1880     break;
1881   case X86::BI__builtin_ia32_cvtsi2sd64:
1882   case X86::BI__builtin_ia32_cvtsi2ss32:
1883   case X86::BI__builtin_ia32_cvtsi2ss64:
1884   case X86::BI__builtin_ia32_cvtusi2sd64:
1885   case X86::BI__builtin_ia32_cvtusi2ss32:
1886   case X86::BI__builtin_ia32_cvtusi2ss64:
1887     ArgNum = 2;
1888     HasRC = true;
1889     break;
1890   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1891   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1892   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1893   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1894   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1895   case X86::BI__builtin_ia32_cvtps2qq512_mask:
1896   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1897   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1898   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1899   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1900   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1901   case X86::BI__builtin_ia32_sqrtpd512_mask:
1902   case X86::BI__builtin_ia32_sqrtps512_mask:
1903     ArgNum = 3;
1904     HasRC = true;
1905     break;
1906   case X86::BI__builtin_ia32_addpd512_mask:
1907   case X86::BI__builtin_ia32_addps512_mask:
1908   case X86::BI__builtin_ia32_divpd512_mask:
1909   case X86::BI__builtin_ia32_divps512_mask:
1910   case X86::BI__builtin_ia32_mulpd512_mask:
1911   case X86::BI__builtin_ia32_mulps512_mask:
1912   case X86::BI__builtin_ia32_subpd512_mask:
1913   case X86::BI__builtin_ia32_subps512_mask:
1914   case X86::BI__builtin_ia32_addss_round_mask:
1915   case X86::BI__builtin_ia32_addsd_round_mask:
1916   case X86::BI__builtin_ia32_divss_round_mask:
1917   case X86::BI__builtin_ia32_divsd_round_mask:
1918   case X86::BI__builtin_ia32_mulss_round_mask:
1919   case X86::BI__builtin_ia32_mulsd_round_mask:
1920   case X86::BI__builtin_ia32_subss_round_mask:
1921   case X86::BI__builtin_ia32_subsd_round_mask:
1922   case X86::BI__builtin_ia32_scalefpd512_mask:
1923   case X86::BI__builtin_ia32_scalefps512_mask:
1924   case X86::BI__builtin_ia32_scalefsd_round_mask:
1925   case X86::BI__builtin_ia32_scalefss_round_mask:
1926   case X86::BI__builtin_ia32_getmantpd512_mask:
1927   case X86::BI__builtin_ia32_getmantps512_mask:
1928   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1929   case X86::BI__builtin_ia32_sqrtsd_round_mask:
1930   case X86::BI__builtin_ia32_sqrtss_round_mask:
1931   case X86::BI__builtin_ia32_vfmaddpd512_mask:
1932   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1933   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1934   case X86::BI__builtin_ia32_vfmaddps512_mask:
1935   case X86::BI__builtin_ia32_vfmaddps512_mask3:
1936   case X86::BI__builtin_ia32_vfmaddps512_maskz:
1937   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1938   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1939   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1940   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1941   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1942   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1943   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1944   case X86::BI__builtin_ia32_vfmsubps512_mask3:
1945   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1946   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1947   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1948   case X86::BI__builtin_ia32_vfnmaddps512_mask:
1949   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1950   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1951   case X86::BI__builtin_ia32_vfnmsubps512_mask:
1952   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1953   case X86::BI__builtin_ia32_vfmaddsd3_mask:
1954   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1955   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1956   case X86::BI__builtin_ia32_vfmaddss3_mask:
1957   case X86::BI__builtin_ia32_vfmaddss3_maskz:
1958   case X86::BI__builtin_ia32_vfmaddss3_mask3:
1959     ArgNum = 4;
1960     HasRC = true;
1961     break;
1962   case X86::BI__builtin_ia32_getmantsd_round_mask:
1963   case X86::BI__builtin_ia32_getmantss_round_mask:
1964     ArgNum = 5;
1965     HasRC = true;
1966     break;
1967   }
1968 
1969   llvm::APSInt Result;
1970 
1971   // We can't check the value of a dependent argument.
1972   Expr *Arg = TheCall->getArg(ArgNum);
1973   if (Arg->isTypeDependent() || Arg->isValueDependent())
1974     return false;
1975 
1976   // Check constant-ness first.
1977   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1978     return true;
1979 
1980   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1981   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1982   // combined with ROUND_NO_EXC.
1983   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1984       Result == 8/*ROUND_NO_EXC*/ ||
1985       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1986     return false;
1987 
1988   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1989     << Arg->getSourceRange();
1990 }
1991 
1992 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1993   if (BuiltinID == X86::BI__builtin_cpu_supports)
1994     return SemaBuiltinCpuSupports(*this, TheCall);
1995 
1996   if (BuiltinID == X86::BI__builtin_ms_va_start)
1997     return SemaBuiltinMSVAStart(TheCall);
1998 
1999   // If the intrinsic has rounding or SAE make sure its valid.
2000   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2001     return true;
2002 
2003   // For intrinsics which take an immediate value as part of the instruction,
2004   // range check them here.
2005   int i = 0, l = 0, u = 0;
2006   switch (BuiltinID) {
2007   default:
2008     return false;
2009   case X86::BI_mm_prefetch:
2010     i = 1; l = 0; u = 3;
2011     break;
2012   case X86::BI__builtin_ia32_sha1rnds4:
2013   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2014   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2015   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2016   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2017     i = 2; l = 0; u = 3;
2018     break;
2019   case X86::BI__builtin_ia32_vpermil2pd:
2020   case X86::BI__builtin_ia32_vpermil2pd256:
2021   case X86::BI__builtin_ia32_vpermil2ps:
2022   case X86::BI__builtin_ia32_vpermil2ps256:
2023     i = 3; l = 0; u = 3;
2024     break;
2025   case X86::BI__builtin_ia32_cmpb128_mask:
2026   case X86::BI__builtin_ia32_cmpw128_mask:
2027   case X86::BI__builtin_ia32_cmpd128_mask:
2028   case X86::BI__builtin_ia32_cmpq128_mask:
2029   case X86::BI__builtin_ia32_cmpb256_mask:
2030   case X86::BI__builtin_ia32_cmpw256_mask:
2031   case X86::BI__builtin_ia32_cmpd256_mask:
2032   case X86::BI__builtin_ia32_cmpq256_mask:
2033   case X86::BI__builtin_ia32_cmpb512_mask:
2034   case X86::BI__builtin_ia32_cmpw512_mask:
2035   case X86::BI__builtin_ia32_cmpd512_mask:
2036   case X86::BI__builtin_ia32_cmpq512_mask:
2037   case X86::BI__builtin_ia32_ucmpb128_mask:
2038   case X86::BI__builtin_ia32_ucmpw128_mask:
2039   case X86::BI__builtin_ia32_ucmpd128_mask:
2040   case X86::BI__builtin_ia32_ucmpq128_mask:
2041   case X86::BI__builtin_ia32_ucmpb256_mask:
2042   case X86::BI__builtin_ia32_ucmpw256_mask:
2043   case X86::BI__builtin_ia32_ucmpd256_mask:
2044   case X86::BI__builtin_ia32_ucmpq256_mask:
2045   case X86::BI__builtin_ia32_ucmpb512_mask:
2046   case X86::BI__builtin_ia32_ucmpw512_mask:
2047   case X86::BI__builtin_ia32_ucmpd512_mask:
2048   case X86::BI__builtin_ia32_ucmpq512_mask:
2049   case X86::BI__builtin_ia32_vpcomub:
2050   case X86::BI__builtin_ia32_vpcomuw:
2051   case X86::BI__builtin_ia32_vpcomud:
2052   case X86::BI__builtin_ia32_vpcomuq:
2053   case X86::BI__builtin_ia32_vpcomb:
2054   case X86::BI__builtin_ia32_vpcomw:
2055   case X86::BI__builtin_ia32_vpcomd:
2056   case X86::BI__builtin_ia32_vpcomq:
2057     i = 2; l = 0; u = 7;
2058     break;
2059   case X86::BI__builtin_ia32_roundps:
2060   case X86::BI__builtin_ia32_roundpd:
2061   case X86::BI__builtin_ia32_roundps256:
2062   case X86::BI__builtin_ia32_roundpd256:
2063     i = 1; l = 0; u = 15;
2064     break;
2065   case X86::BI__builtin_ia32_roundss:
2066   case X86::BI__builtin_ia32_roundsd:
2067   case X86::BI__builtin_ia32_rangepd128_mask:
2068   case X86::BI__builtin_ia32_rangepd256_mask:
2069   case X86::BI__builtin_ia32_rangepd512_mask:
2070   case X86::BI__builtin_ia32_rangeps128_mask:
2071   case X86::BI__builtin_ia32_rangeps256_mask:
2072   case X86::BI__builtin_ia32_rangeps512_mask:
2073   case X86::BI__builtin_ia32_getmantsd_round_mask:
2074   case X86::BI__builtin_ia32_getmantss_round_mask:
2075     i = 2; l = 0; u = 15;
2076     break;
2077   case X86::BI__builtin_ia32_cmpps:
2078   case X86::BI__builtin_ia32_cmpss:
2079   case X86::BI__builtin_ia32_cmppd:
2080   case X86::BI__builtin_ia32_cmpsd:
2081   case X86::BI__builtin_ia32_cmpps256:
2082   case X86::BI__builtin_ia32_cmppd256:
2083   case X86::BI__builtin_ia32_cmpps128_mask:
2084   case X86::BI__builtin_ia32_cmppd128_mask:
2085   case X86::BI__builtin_ia32_cmpps256_mask:
2086   case X86::BI__builtin_ia32_cmppd256_mask:
2087   case X86::BI__builtin_ia32_cmpps512_mask:
2088   case X86::BI__builtin_ia32_cmppd512_mask:
2089   case X86::BI__builtin_ia32_cmpsd_mask:
2090   case X86::BI__builtin_ia32_cmpss_mask:
2091     i = 2; l = 0; u = 31;
2092     break;
2093   case X86::BI__builtin_ia32_xabort:
2094     i = 0; l = -128; u = 255;
2095     break;
2096   case X86::BI__builtin_ia32_pshufw:
2097   case X86::BI__builtin_ia32_aeskeygenassist128:
2098     i = 1; l = -128; u = 255;
2099     break;
2100   case X86::BI__builtin_ia32_vcvtps2ph:
2101   case X86::BI__builtin_ia32_vcvtps2ph256:
2102   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2103   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2104   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2105   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2106   case X86::BI__builtin_ia32_rndscaleps_mask:
2107   case X86::BI__builtin_ia32_rndscalepd_mask:
2108   case X86::BI__builtin_ia32_reducepd128_mask:
2109   case X86::BI__builtin_ia32_reducepd256_mask:
2110   case X86::BI__builtin_ia32_reducepd512_mask:
2111   case X86::BI__builtin_ia32_reduceps128_mask:
2112   case X86::BI__builtin_ia32_reduceps256_mask:
2113   case X86::BI__builtin_ia32_reduceps512_mask:
2114   case X86::BI__builtin_ia32_prold512_mask:
2115   case X86::BI__builtin_ia32_prolq512_mask:
2116   case X86::BI__builtin_ia32_prold128_mask:
2117   case X86::BI__builtin_ia32_prold256_mask:
2118   case X86::BI__builtin_ia32_prolq128_mask:
2119   case X86::BI__builtin_ia32_prolq256_mask:
2120   case X86::BI__builtin_ia32_prord128_mask:
2121   case X86::BI__builtin_ia32_prord256_mask:
2122   case X86::BI__builtin_ia32_prorq128_mask:
2123   case X86::BI__builtin_ia32_prorq256_mask:
2124   case X86::BI__builtin_ia32_fpclasspd128_mask:
2125   case X86::BI__builtin_ia32_fpclasspd256_mask:
2126   case X86::BI__builtin_ia32_fpclassps128_mask:
2127   case X86::BI__builtin_ia32_fpclassps256_mask:
2128   case X86::BI__builtin_ia32_fpclassps512_mask:
2129   case X86::BI__builtin_ia32_fpclasspd512_mask:
2130   case X86::BI__builtin_ia32_fpclasssd_mask:
2131   case X86::BI__builtin_ia32_fpclassss_mask:
2132     i = 1; l = 0; u = 255;
2133     break;
2134   case X86::BI__builtin_ia32_palignr:
2135   case X86::BI__builtin_ia32_insertps128:
2136   case X86::BI__builtin_ia32_dpps:
2137   case X86::BI__builtin_ia32_dppd:
2138   case X86::BI__builtin_ia32_dpps256:
2139   case X86::BI__builtin_ia32_mpsadbw128:
2140   case X86::BI__builtin_ia32_mpsadbw256:
2141   case X86::BI__builtin_ia32_pcmpistrm128:
2142   case X86::BI__builtin_ia32_pcmpistri128:
2143   case X86::BI__builtin_ia32_pcmpistria128:
2144   case X86::BI__builtin_ia32_pcmpistric128:
2145   case X86::BI__builtin_ia32_pcmpistrio128:
2146   case X86::BI__builtin_ia32_pcmpistris128:
2147   case X86::BI__builtin_ia32_pcmpistriz128:
2148   case X86::BI__builtin_ia32_pclmulqdq128:
2149   case X86::BI__builtin_ia32_vperm2f128_pd256:
2150   case X86::BI__builtin_ia32_vperm2f128_ps256:
2151   case X86::BI__builtin_ia32_vperm2f128_si256:
2152   case X86::BI__builtin_ia32_permti256:
2153     i = 2; l = -128; u = 255;
2154     break;
2155   case X86::BI__builtin_ia32_palignr128:
2156   case X86::BI__builtin_ia32_palignr256:
2157   case X86::BI__builtin_ia32_palignr512_mask:
2158   case X86::BI__builtin_ia32_vcomisd:
2159   case X86::BI__builtin_ia32_vcomiss:
2160   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2161   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2162   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2163   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2164   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2165   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2166   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2167     i = 2; l = 0; u = 255;
2168     break;
2169   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2170   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2171   case X86::BI__builtin_ia32_fixupimmps512_mask:
2172   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2173   case X86::BI__builtin_ia32_fixupimmsd_mask:
2174   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2175   case X86::BI__builtin_ia32_fixupimmss_mask:
2176   case X86::BI__builtin_ia32_fixupimmss_maskz:
2177   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2178   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2179   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2180   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2181   case X86::BI__builtin_ia32_fixupimmps128_mask:
2182   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2183   case X86::BI__builtin_ia32_fixupimmps256_mask:
2184   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2185   case X86::BI__builtin_ia32_pternlogd512_mask:
2186   case X86::BI__builtin_ia32_pternlogd512_maskz:
2187   case X86::BI__builtin_ia32_pternlogq512_mask:
2188   case X86::BI__builtin_ia32_pternlogq512_maskz:
2189   case X86::BI__builtin_ia32_pternlogd128_mask:
2190   case X86::BI__builtin_ia32_pternlogd128_maskz:
2191   case X86::BI__builtin_ia32_pternlogd256_mask:
2192   case X86::BI__builtin_ia32_pternlogd256_maskz:
2193   case X86::BI__builtin_ia32_pternlogq128_mask:
2194   case X86::BI__builtin_ia32_pternlogq128_maskz:
2195   case X86::BI__builtin_ia32_pternlogq256_mask:
2196   case X86::BI__builtin_ia32_pternlogq256_maskz:
2197     i = 3; l = 0; u = 255;
2198     break;
2199   case X86::BI__builtin_ia32_pcmpestrm128:
2200   case X86::BI__builtin_ia32_pcmpestri128:
2201   case X86::BI__builtin_ia32_pcmpestria128:
2202   case X86::BI__builtin_ia32_pcmpestric128:
2203   case X86::BI__builtin_ia32_pcmpestrio128:
2204   case X86::BI__builtin_ia32_pcmpestris128:
2205   case X86::BI__builtin_ia32_pcmpestriz128:
2206     i = 4; l = -128; u = 255;
2207     break;
2208   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2209   case X86::BI__builtin_ia32_rndscaless_round_mask:
2210     i = 4; l = 0; u = 255;
2211     break;
2212   }
2213   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2214 }
2215 
2216 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2217 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2218 /// Returns true when the format fits the function and the FormatStringInfo has
2219 /// been populated.
2220 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2221                                FormatStringInfo *FSI) {
2222   FSI->HasVAListArg = Format->getFirstArg() == 0;
2223   FSI->FormatIdx = Format->getFormatIdx() - 1;
2224   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2225 
2226   // The way the format attribute works in GCC, the implicit this argument
2227   // of member functions is counted. However, it doesn't appear in our own
2228   // lists, so decrement format_idx in that case.
2229   if (IsCXXMember) {
2230     if(FSI->FormatIdx == 0)
2231       return false;
2232     --FSI->FormatIdx;
2233     if (FSI->FirstDataArg != 0)
2234       --FSI->FirstDataArg;
2235   }
2236   return true;
2237 }
2238 
2239 /// Checks if a the given expression evaluates to null.
2240 ///
2241 /// \brief Returns true if the value evaluates to null.
2242 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2243   // If the expression has non-null type, it doesn't evaluate to null.
2244   if (auto nullability
2245         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2246     if (*nullability == NullabilityKind::NonNull)
2247       return false;
2248   }
2249 
2250   // As a special case, transparent unions initialized with zero are
2251   // considered null for the purposes of the nonnull attribute.
2252   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2253     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2254       if (const CompoundLiteralExpr *CLE =
2255           dyn_cast<CompoundLiteralExpr>(Expr))
2256         if (const InitListExpr *ILE =
2257             dyn_cast<InitListExpr>(CLE->getInitializer()))
2258           Expr = ILE->getInit(0);
2259   }
2260 
2261   bool Result;
2262   return (!Expr->isValueDependent() &&
2263           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2264           !Result);
2265 }
2266 
2267 static void CheckNonNullArgument(Sema &S,
2268                                  const Expr *ArgExpr,
2269                                  SourceLocation CallSiteLoc) {
2270   if (CheckNonNullExpr(S, ArgExpr))
2271     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2272            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2273 }
2274 
2275 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2276   FormatStringInfo FSI;
2277   if ((GetFormatStringType(Format) == FST_NSString) &&
2278       getFormatStringInfo(Format, false, &FSI)) {
2279     Idx = FSI.FormatIdx;
2280     return true;
2281   }
2282   return false;
2283 }
2284 /// \brief Diagnose use of %s directive in an NSString which is being passed
2285 /// as formatting string to formatting method.
2286 static void
2287 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2288                                         const NamedDecl *FDecl,
2289                                         Expr **Args,
2290                                         unsigned NumArgs) {
2291   unsigned Idx = 0;
2292   bool Format = false;
2293   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2294   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2295     Idx = 2;
2296     Format = true;
2297   }
2298   else
2299     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2300       if (S.GetFormatNSStringIdx(I, Idx)) {
2301         Format = true;
2302         break;
2303       }
2304     }
2305   if (!Format || NumArgs <= Idx)
2306     return;
2307   const Expr *FormatExpr = Args[Idx];
2308   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2309     FormatExpr = CSCE->getSubExpr();
2310   const StringLiteral *FormatString;
2311   if (const ObjCStringLiteral *OSL =
2312       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2313     FormatString = OSL->getString();
2314   else
2315     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2316   if (!FormatString)
2317     return;
2318   if (S.FormatStringHasSArg(FormatString)) {
2319     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2320       << "%s" << 1 << 1;
2321     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2322       << FDecl->getDeclName();
2323   }
2324 }
2325 
2326 /// Determine whether the given type has a non-null nullability annotation.
2327 static bool isNonNullType(ASTContext &ctx, QualType type) {
2328   if (auto nullability = type->getNullability(ctx))
2329     return *nullability == NullabilityKind::NonNull;
2330 
2331   return false;
2332 }
2333 
2334 static void CheckNonNullArguments(Sema &S,
2335                                   const NamedDecl *FDecl,
2336                                   const FunctionProtoType *Proto,
2337                                   ArrayRef<const Expr *> Args,
2338                                   SourceLocation CallSiteLoc) {
2339   assert((FDecl || Proto) && "Need a function declaration or prototype");
2340 
2341   // Check the attributes attached to the method/function itself.
2342   llvm::SmallBitVector NonNullArgs;
2343   if (FDecl) {
2344     // Handle the nonnull attribute on the function/method declaration itself.
2345     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2346       if (!NonNull->args_size()) {
2347         // Easy case: all pointer arguments are nonnull.
2348         for (const auto *Arg : Args)
2349           if (S.isValidPointerAttrType(Arg->getType()))
2350             CheckNonNullArgument(S, Arg, CallSiteLoc);
2351         return;
2352       }
2353 
2354       for (unsigned Val : NonNull->args()) {
2355         if (Val >= Args.size())
2356           continue;
2357         if (NonNullArgs.empty())
2358           NonNullArgs.resize(Args.size());
2359         NonNullArgs.set(Val);
2360       }
2361     }
2362   }
2363 
2364   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2365     // Handle the nonnull attribute on the parameters of the
2366     // function/method.
2367     ArrayRef<ParmVarDecl*> parms;
2368     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2369       parms = FD->parameters();
2370     else
2371       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2372 
2373     unsigned ParamIndex = 0;
2374     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2375          I != E; ++I, ++ParamIndex) {
2376       const ParmVarDecl *PVD = *I;
2377       if (PVD->hasAttr<NonNullAttr>() ||
2378           isNonNullType(S.Context, PVD->getType())) {
2379         if (NonNullArgs.empty())
2380           NonNullArgs.resize(Args.size());
2381 
2382         NonNullArgs.set(ParamIndex);
2383       }
2384     }
2385   } else {
2386     // If we have a non-function, non-method declaration but no
2387     // function prototype, try to dig out the function prototype.
2388     if (!Proto) {
2389       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2390         QualType type = VD->getType().getNonReferenceType();
2391         if (auto pointerType = type->getAs<PointerType>())
2392           type = pointerType->getPointeeType();
2393         else if (auto blockType = type->getAs<BlockPointerType>())
2394           type = blockType->getPointeeType();
2395         // FIXME: data member pointers?
2396 
2397         // Dig out the function prototype, if there is one.
2398         Proto = type->getAs<FunctionProtoType>();
2399       }
2400     }
2401 
2402     // Fill in non-null argument information from the nullability
2403     // information on the parameter types (if we have them).
2404     if (Proto) {
2405       unsigned Index = 0;
2406       for (auto paramType : Proto->getParamTypes()) {
2407         if (isNonNullType(S.Context, paramType)) {
2408           if (NonNullArgs.empty())
2409             NonNullArgs.resize(Args.size());
2410 
2411           NonNullArgs.set(Index);
2412         }
2413 
2414         ++Index;
2415       }
2416     }
2417   }
2418 
2419   // Check for non-null arguments.
2420   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2421        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2422     if (NonNullArgs[ArgIndex])
2423       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2424   }
2425 }
2426 
2427 /// Handles the checks for format strings, non-POD arguments to vararg
2428 /// functions, and NULL arguments passed to non-NULL parameters.
2429 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2430                      ArrayRef<const Expr *> Args, bool IsMemberFunction,
2431                      SourceLocation Loc, SourceRange Range,
2432                      VariadicCallType CallType) {
2433   // FIXME: We should check as much as we can in the template definition.
2434   if (CurContext->isDependentContext())
2435     return;
2436 
2437   // Printf and scanf checking.
2438   llvm::SmallBitVector CheckedVarArgs;
2439   if (FDecl) {
2440     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2441       // Only create vector if there are format attributes.
2442       CheckedVarArgs.resize(Args.size());
2443 
2444       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2445                            CheckedVarArgs);
2446     }
2447   }
2448 
2449   // Refuse POD arguments that weren't caught by the format string
2450   // checks above.
2451   if (CallType != VariadicDoesNotApply) {
2452     unsigned NumParams = Proto ? Proto->getNumParams()
2453                        : FDecl && isa<FunctionDecl>(FDecl)
2454                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2455                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2456                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2457                        : 0;
2458 
2459     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2460       // Args[ArgIdx] can be null in malformed code.
2461       if (const Expr *Arg = Args[ArgIdx]) {
2462         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2463           checkVariadicArgument(Arg, CallType);
2464       }
2465     }
2466   }
2467 
2468   if (FDecl || Proto) {
2469     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2470 
2471     // Type safety checking.
2472     if (FDecl) {
2473       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2474         CheckArgumentWithTypeTag(I, Args.data());
2475     }
2476   }
2477 }
2478 
2479 /// CheckConstructorCall - Check a constructor call for correctness and safety
2480 /// properties not enforced by the C type system.
2481 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2482                                 ArrayRef<const Expr *> Args,
2483                                 const FunctionProtoType *Proto,
2484                                 SourceLocation Loc) {
2485   VariadicCallType CallType =
2486     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2487   checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2488             CallType);
2489 }
2490 
2491 /// CheckFunctionCall - Check a direct function call for various correctness
2492 /// and safety properties not strictly enforced by the C type system.
2493 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2494                              const FunctionProtoType *Proto) {
2495   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2496                               isa<CXXMethodDecl>(FDecl);
2497   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2498                           IsMemberOperatorCall;
2499   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2500                                                   TheCall->getCallee());
2501   Expr** Args = TheCall->getArgs();
2502   unsigned NumArgs = TheCall->getNumArgs();
2503   if (IsMemberOperatorCall) {
2504     // If this is a call to a member operator, hide the first argument
2505     // from checkCall.
2506     // FIXME: Our choice of AST representation here is less than ideal.
2507     ++Args;
2508     --NumArgs;
2509   }
2510   checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
2511             IsMemberFunction, TheCall->getRParenLoc(),
2512             TheCall->getCallee()->getSourceRange(), CallType);
2513 
2514   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2515   // None of the checks below are needed for functions that don't have
2516   // simple names (e.g., C++ conversion functions).
2517   if (!FnInfo)
2518     return false;
2519 
2520   CheckAbsoluteValueFunction(TheCall, FDecl);
2521   CheckMaxUnsignedZero(TheCall, FDecl);
2522 
2523   if (getLangOpts().ObjC1)
2524     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2525 
2526   unsigned CMId = FDecl->getMemoryFunctionKind();
2527   if (CMId == 0)
2528     return false;
2529 
2530   // Handle memory setting and copying functions.
2531   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2532     CheckStrlcpycatArguments(TheCall, FnInfo);
2533   else if (CMId == Builtin::BIstrncat)
2534     CheckStrncatArguments(TheCall, FnInfo);
2535   else
2536     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2537 
2538   return false;
2539 }
2540 
2541 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2542                                ArrayRef<const Expr *> Args) {
2543   VariadicCallType CallType =
2544       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2545 
2546   checkCall(Method, nullptr, Args,
2547             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2548             CallType);
2549 
2550   return false;
2551 }
2552 
2553 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2554                             const FunctionProtoType *Proto) {
2555   QualType Ty;
2556   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2557     Ty = V->getType().getNonReferenceType();
2558   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2559     Ty = F->getType().getNonReferenceType();
2560   else
2561     return false;
2562 
2563   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2564       !Ty->isFunctionProtoType())
2565     return false;
2566 
2567   VariadicCallType CallType;
2568   if (!Proto || !Proto->isVariadic()) {
2569     CallType = VariadicDoesNotApply;
2570   } else if (Ty->isBlockPointerType()) {
2571     CallType = VariadicBlock;
2572   } else { // Ty->isFunctionPointerType()
2573     CallType = VariadicFunction;
2574   }
2575 
2576   checkCall(NDecl, Proto,
2577             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2578             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2579             TheCall->getCallee()->getSourceRange(), CallType);
2580 
2581   return false;
2582 }
2583 
2584 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2585 /// such as function pointers returned from functions.
2586 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2587   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2588                                                   TheCall->getCallee());
2589   checkCall(/*FDecl=*/nullptr, Proto,
2590             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2591             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2592             TheCall->getCallee()->getSourceRange(), CallType);
2593 
2594   return false;
2595 }
2596 
2597 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2598   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2599     return false;
2600 
2601   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2602   switch (Op) {
2603   case AtomicExpr::AO__c11_atomic_init:
2604     llvm_unreachable("There is no ordering argument for an init");
2605 
2606   case AtomicExpr::AO__c11_atomic_load:
2607   case AtomicExpr::AO__atomic_load_n:
2608   case AtomicExpr::AO__atomic_load:
2609     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2610            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2611 
2612   case AtomicExpr::AO__c11_atomic_store:
2613   case AtomicExpr::AO__atomic_store:
2614   case AtomicExpr::AO__atomic_store_n:
2615     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2616            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2617            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2618 
2619   default:
2620     return true;
2621   }
2622 }
2623 
2624 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2625                                          AtomicExpr::AtomicOp Op) {
2626   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2627   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2628 
2629   // All these operations take one of the following forms:
2630   enum {
2631     // C    __c11_atomic_init(A *, C)
2632     Init,
2633     // C    __c11_atomic_load(A *, int)
2634     Load,
2635     // void __atomic_load(A *, CP, int)
2636     LoadCopy,
2637     // void __atomic_store(A *, CP, int)
2638     Copy,
2639     // C    __c11_atomic_add(A *, M, int)
2640     Arithmetic,
2641     // C    __atomic_exchange_n(A *, CP, int)
2642     Xchg,
2643     // void __atomic_exchange(A *, C *, CP, int)
2644     GNUXchg,
2645     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2646     C11CmpXchg,
2647     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2648     GNUCmpXchg
2649   } Form = Init;
2650   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2651   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2652   // where:
2653   //   C is an appropriate type,
2654   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2655   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2656   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2657   //   the int parameters are for orderings.
2658 
2659   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2660                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2661                         AtomicExpr::AO__atomic_load,
2662                 "need to update code for modified C11 atomics");
2663   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2664                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2665   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2666              Op == AtomicExpr::AO__atomic_store_n ||
2667              Op == AtomicExpr::AO__atomic_exchange_n ||
2668              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2669   bool IsAddSub = false;
2670 
2671   switch (Op) {
2672   case AtomicExpr::AO__c11_atomic_init:
2673     Form = Init;
2674     break;
2675 
2676   case AtomicExpr::AO__c11_atomic_load:
2677   case AtomicExpr::AO__atomic_load_n:
2678     Form = Load;
2679     break;
2680 
2681   case AtomicExpr::AO__atomic_load:
2682     Form = LoadCopy;
2683     break;
2684 
2685   case AtomicExpr::AO__c11_atomic_store:
2686   case AtomicExpr::AO__atomic_store:
2687   case AtomicExpr::AO__atomic_store_n:
2688     Form = Copy;
2689     break;
2690 
2691   case AtomicExpr::AO__c11_atomic_fetch_add:
2692   case AtomicExpr::AO__c11_atomic_fetch_sub:
2693   case AtomicExpr::AO__atomic_fetch_add:
2694   case AtomicExpr::AO__atomic_fetch_sub:
2695   case AtomicExpr::AO__atomic_add_fetch:
2696   case AtomicExpr::AO__atomic_sub_fetch:
2697     IsAddSub = true;
2698     // Fall through.
2699   case AtomicExpr::AO__c11_atomic_fetch_and:
2700   case AtomicExpr::AO__c11_atomic_fetch_or:
2701   case AtomicExpr::AO__c11_atomic_fetch_xor:
2702   case AtomicExpr::AO__atomic_fetch_and:
2703   case AtomicExpr::AO__atomic_fetch_or:
2704   case AtomicExpr::AO__atomic_fetch_xor:
2705   case AtomicExpr::AO__atomic_fetch_nand:
2706   case AtomicExpr::AO__atomic_and_fetch:
2707   case AtomicExpr::AO__atomic_or_fetch:
2708   case AtomicExpr::AO__atomic_xor_fetch:
2709   case AtomicExpr::AO__atomic_nand_fetch:
2710     Form = Arithmetic;
2711     break;
2712 
2713   case AtomicExpr::AO__c11_atomic_exchange:
2714   case AtomicExpr::AO__atomic_exchange_n:
2715     Form = Xchg;
2716     break;
2717 
2718   case AtomicExpr::AO__atomic_exchange:
2719     Form = GNUXchg;
2720     break;
2721 
2722   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2723   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2724     Form = C11CmpXchg;
2725     break;
2726 
2727   case AtomicExpr::AO__atomic_compare_exchange:
2728   case AtomicExpr::AO__atomic_compare_exchange_n:
2729     Form = GNUCmpXchg;
2730     break;
2731   }
2732 
2733   // Check we have the right number of arguments.
2734   if (TheCall->getNumArgs() < NumArgs[Form]) {
2735     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2736       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2737       << TheCall->getCallee()->getSourceRange();
2738     return ExprError();
2739   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2740     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2741          diag::err_typecheck_call_too_many_args)
2742       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2743       << TheCall->getCallee()->getSourceRange();
2744     return ExprError();
2745   }
2746 
2747   // Inspect the first argument of the atomic operation.
2748   Expr *Ptr = TheCall->getArg(0);
2749   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2750   if (ConvertedPtr.isInvalid())
2751     return ExprError();
2752 
2753   Ptr = ConvertedPtr.get();
2754   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2755   if (!pointerType) {
2756     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2757       << Ptr->getType() << Ptr->getSourceRange();
2758     return ExprError();
2759   }
2760 
2761   // For a __c11 builtin, this should be a pointer to an _Atomic type.
2762   QualType AtomTy = pointerType->getPointeeType(); // 'A'
2763   QualType ValType = AtomTy; // 'C'
2764   if (IsC11) {
2765     if (!AtomTy->isAtomicType()) {
2766       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2767         << Ptr->getType() << Ptr->getSourceRange();
2768       return ExprError();
2769     }
2770     if (AtomTy.isConstQualified()) {
2771       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2772         << Ptr->getType() << Ptr->getSourceRange();
2773       return ExprError();
2774     }
2775     ValType = AtomTy->getAs<AtomicType>()->getValueType();
2776   } else if (Form != Load && Form != LoadCopy) {
2777     if (ValType.isConstQualified()) {
2778       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2779         << Ptr->getType() << Ptr->getSourceRange();
2780       return ExprError();
2781     }
2782   }
2783 
2784   // For an arithmetic operation, the implied arithmetic must be well-formed.
2785   if (Form == Arithmetic) {
2786     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2787     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2788       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2789         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2790       return ExprError();
2791     }
2792     if (!IsAddSub && !ValType->isIntegerType()) {
2793       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2794         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2795       return ExprError();
2796     }
2797     if (IsC11 && ValType->isPointerType() &&
2798         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2799                             diag::err_incomplete_type)) {
2800       return ExprError();
2801     }
2802   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2803     // For __atomic_*_n operations, the value type must be a scalar integral or
2804     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2805     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2806       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2807     return ExprError();
2808   }
2809 
2810   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2811       !AtomTy->isScalarType()) {
2812     // For GNU atomics, require a trivially-copyable type. This is not part of
2813     // the GNU atomics specification, but we enforce it for sanity.
2814     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2815       << Ptr->getType() << Ptr->getSourceRange();
2816     return ExprError();
2817   }
2818 
2819   switch (ValType.getObjCLifetime()) {
2820   case Qualifiers::OCL_None:
2821   case Qualifiers::OCL_ExplicitNone:
2822     // okay
2823     break;
2824 
2825   case Qualifiers::OCL_Weak:
2826   case Qualifiers::OCL_Strong:
2827   case Qualifiers::OCL_Autoreleasing:
2828     // FIXME: Can this happen? By this point, ValType should be known
2829     // to be trivially copyable.
2830     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2831       << ValType << Ptr->getSourceRange();
2832     return ExprError();
2833   }
2834 
2835   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
2836   // volatile-ness of the pointee-type inject itself into the result or the
2837   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2838   ValType.removeLocalVolatile();
2839   ValType.removeLocalConst();
2840   QualType ResultType = ValType;
2841   if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2842     ResultType = Context.VoidTy;
2843   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2844     ResultType = Context.BoolTy;
2845 
2846   // The type of a parameter passed 'by value'. In the GNU atomics, such
2847   // arguments are actually passed as pointers.
2848   QualType ByValType = ValType; // 'CP'
2849   if (!IsC11 && !IsN)
2850     ByValType = Ptr->getType();
2851 
2852   // The first argument --- the pointer --- has a fixed type; we
2853   // deduce the types of the rest of the arguments accordingly.  Walk
2854   // the remaining arguments, converting them to the deduced value type.
2855   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2856     QualType Ty;
2857     if (i < NumVals[Form] + 1) {
2858       switch (i) {
2859       case 1:
2860         // The second argument is the non-atomic operand. For arithmetic, this
2861         // is always passed by value, and for a compare_exchange it is always
2862         // passed by address. For the rest, GNU uses by-address and C11 uses
2863         // by-value.
2864         assert(Form != Load);
2865         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2866           Ty = ValType;
2867         else if (Form == Copy || Form == Xchg)
2868           Ty = ByValType;
2869         else if (Form == Arithmetic)
2870           Ty = Context.getPointerDiffType();
2871         else {
2872           Expr *ValArg = TheCall->getArg(i);
2873           // Treat this argument as _Nonnull as we want to show a warning if
2874           // NULL is passed into it.
2875           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
2876           unsigned AS = 0;
2877           // Keep address space of non-atomic pointer type.
2878           if (const PointerType *PtrTy =
2879                   ValArg->getType()->getAs<PointerType>()) {
2880             AS = PtrTy->getPointeeType().getAddressSpace();
2881           }
2882           Ty = Context.getPointerType(
2883               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2884         }
2885         break;
2886       case 2:
2887         // The third argument to compare_exchange / GNU exchange is a
2888         // (pointer to a) desired value.
2889         Ty = ByValType;
2890         break;
2891       case 3:
2892         // The fourth argument to GNU compare_exchange is a 'weak' flag.
2893         Ty = Context.BoolTy;
2894         break;
2895       }
2896     } else {
2897       // The order(s) are always converted to int.
2898       Ty = Context.IntTy;
2899     }
2900 
2901     InitializedEntity Entity =
2902         InitializedEntity::InitializeParameter(Context, Ty, false);
2903     ExprResult Arg = TheCall->getArg(i);
2904     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2905     if (Arg.isInvalid())
2906       return true;
2907     TheCall->setArg(i, Arg.get());
2908   }
2909 
2910   // Permute the arguments into a 'consistent' order.
2911   SmallVector<Expr*, 5> SubExprs;
2912   SubExprs.push_back(Ptr);
2913   switch (Form) {
2914   case Init:
2915     // Note, AtomicExpr::getVal1() has a special case for this atomic.
2916     SubExprs.push_back(TheCall->getArg(1)); // Val1
2917     break;
2918   case Load:
2919     SubExprs.push_back(TheCall->getArg(1)); // Order
2920     break;
2921   case LoadCopy:
2922   case Copy:
2923   case Arithmetic:
2924   case Xchg:
2925     SubExprs.push_back(TheCall->getArg(2)); // Order
2926     SubExprs.push_back(TheCall->getArg(1)); // Val1
2927     break;
2928   case GNUXchg:
2929     // Note, AtomicExpr::getVal2() has a special case for this atomic.
2930     SubExprs.push_back(TheCall->getArg(3)); // Order
2931     SubExprs.push_back(TheCall->getArg(1)); // Val1
2932     SubExprs.push_back(TheCall->getArg(2)); // Val2
2933     break;
2934   case C11CmpXchg:
2935     SubExprs.push_back(TheCall->getArg(3)); // Order
2936     SubExprs.push_back(TheCall->getArg(1)); // Val1
2937     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2938     SubExprs.push_back(TheCall->getArg(2)); // Val2
2939     break;
2940   case GNUCmpXchg:
2941     SubExprs.push_back(TheCall->getArg(4)); // Order
2942     SubExprs.push_back(TheCall->getArg(1)); // Val1
2943     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2944     SubExprs.push_back(TheCall->getArg(2)); // Val2
2945     SubExprs.push_back(TheCall->getArg(3)); // Weak
2946     break;
2947   }
2948 
2949   if (SubExprs.size() >= 2 && Form != Init) {
2950     llvm::APSInt Result(32);
2951     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2952         !isValidOrderingForOp(Result.getSExtValue(), Op))
2953       Diag(SubExprs[1]->getLocStart(),
2954            diag::warn_atomic_op_has_invalid_memory_order)
2955           << SubExprs[1]->getSourceRange();
2956   }
2957 
2958   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2959                                             SubExprs, ResultType, Op,
2960                                             TheCall->getRParenLoc());
2961 
2962   if ((Op == AtomicExpr::AO__c11_atomic_load ||
2963        (Op == AtomicExpr::AO__c11_atomic_store)) &&
2964       Context.AtomicUsesUnsupportedLibcall(AE))
2965     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2966     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2967 
2968   return AE;
2969 }
2970 
2971 /// checkBuiltinArgument - Given a call to a builtin function, perform
2972 /// normal type-checking on the given argument, updating the call in
2973 /// place.  This is useful when a builtin function requires custom
2974 /// type-checking for some of its arguments but not necessarily all of
2975 /// them.
2976 ///
2977 /// Returns true on error.
2978 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2979   FunctionDecl *Fn = E->getDirectCallee();
2980   assert(Fn && "builtin call without direct callee!");
2981 
2982   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2983   InitializedEntity Entity =
2984     InitializedEntity::InitializeParameter(S.Context, Param);
2985 
2986   ExprResult Arg = E->getArg(0);
2987   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2988   if (Arg.isInvalid())
2989     return true;
2990 
2991   E->setArg(ArgIndex, Arg.get());
2992   return false;
2993 }
2994 
2995 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
2996 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
2997 /// type of its first argument.  The main ActOnCallExpr routines have already
2998 /// promoted the types of arguments because all of these calls are prototyped as
2999 /// void(...).
3000 ///
3001 /// This function goes through and does final semantic checking for these
3002 /// builtins,
3003 ExprResult
3004 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3005   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3006   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3007   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3008 
3009   // Ensure that we have at least one argument to do type inference from.
3010   if (TheCall->getNumArgs() < 1) {
3011     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3012       << 0 << 1 << TheCall->getNumArgs()
3013       << TheCall->getCallee()->getSourceRange();
3014     return ExprError();
3015   }
3016 
3017   // Inspect the first argument of the atomic builtin.  This should always be
3018   // a pointer type, whose element is an integral scalar or pointer type.
3019   // Because it is a pointer type, we don't have to worry about any implicit
3020   // casts here.
3021   // FIXME: We don't allow floating point scalars as input.
3022   Expr *FirstArg = TheCall->getArg(0);
3023   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3024   if (FirstArgResult.isInvalid())
3025     return ExprError();
3026   FirstArg = FirstArgResult.get();
3027   TheCall->setArg(0, FirstArg);
3028 
3029   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3030   if (!pointerType) {
3031     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3032       << FirstArg->getType() << FirstArg->getSourceRange();
3033     return ExprError();
3034   }
3035 
3036   QualType ValType = pointerType->getPointeeType();
3037   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3038       !ValType->isBlockPointerType()) {
3039     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3040       << FirstArg->getType() << FirstArg->getSourceRange();
3041     return ExprError();
3042   }
3043 
3044   switch (ValType.getObjCLifetime()) {
3045   case Qualifiers::OCL_None:
3046   case Qualifiers::OCL_ExplicitNone:
3047     // okay
3048     break;
3049 
3050   case Qualifiers::OCL_Weak:
3051   case Qualifiers::OCL_Strong:
3052   case Qualifiers::OCL_Autoreleasing:
3053     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3054       << ValType << FirstArg->getSourceRange();
3055     return ExprError();
3056   }
3057 
3058   // Strip any qualifiers off ValType.
3059   ValType = ValType.getUnqualifiedType();
3060 
3061   // The majority of builtins return a value, but a few have special return
3062   // types, so allow them to override appropriately below.
3063   QualType ResultType = ValType;
3064 
3065   // We need to figure out which concrete builtin this maps onto.  For example,
3066   // __sync_fetch_and_add with a 2 byte object turns into
3067   // __sync_fetch_and_add_2.
3068 #define BUILTIN_ROW(x) \
3069   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3070     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3071 
3072   static const unsigned BuiltinIndices[][5] = {
3073     BUILTIN_ROW(__sync_fetch_and_add),
3074     BUILTIN_ROW(__sync_fetch_and_sub),
3075     BUILTIN_ROW(__sync_fetch_and_or),
3076     BUILTIN_ROW(__sync_fetch_and_and),
3077     BUILTIN_ROW(__sync_fetch_and_xor),
3078     BUILTIN_ROW(__sync_fetch_and_nand),
3079 
3080     BUILTIN_ROW(__sync_add_and_fetch),
3081     BUILTIN_ROW(__sync_sub_and_fetch),
3082     BUILTIN_ROW(__sync_and_and_fetch),
3083     BUILTIN_ROW(__sync_or_and_fetch),
3084     BUILTIN_ROW(__sync_xor_and_fetch),
3085     BUILTIN_ROW(__sync_nand_and_fetch),
3086 
3087     BUILTIN_ROW(__sync_val_compare_and_swap),
3088     BUILTIN_ROW(__sync_bool_compare_and_swap),
3089     BUILTIN_ROW(__sync_lock_test_and_set),
3090     BUILTIN_ROW(__sync_lock_release),
3091     BUILTIN_ROW(__sync_swap)
3092   };
3093 #undef BUILTIN_ROW
3094 
3095   // Determine the index of the size.
3096   unsigned SizeIndex;
3097   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3098   case 1: SizeIndex = 0; break;
3099   case 2: SizeIndex = 1; break;
3100   case 4: SizeIndex = 2; break;
3101   case 8: SizeIndex = 3; break;
3102   case 16: SizeIndex = 4; break;
3103   default:
3104     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3105       << FirstArg->getType() << FirstArg->getSourceRange();
3106     return ExprError();
3107   }
3108 
3109   // Each of these builtins has one pointer argument, followed by some number of
3110   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3111   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3112   // as the number of fixed args.
3113   unsigned BuiltinID = FDecl->getBuiltinID();
3114   unsigned BuiltinIndex, NumFixed = 1;
3115   bool WarnAboutSemanticsChange = false;
3116   switch (BuiltinID) {
3117   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3118   case Builtin::BI__sync_fetch_and_add:
3119   case Builtin::BI__sync_fetch_and_add_1:
3120   case Builtin::BI__sync_fetch_and_add_2:
3121   case Builtin::BI__sync_fetch_and_add_4:
3122   case Builtin::BI__sync_fetch_and_add_8:
3123   case Builtin::BI__sync_fetch_and_add_16:
3124     BuiltinIndex = 0;
3125     break;
3126 
3127   case Builtin::BI__sync_fetch_and_sub:
3128   case Builtin::BI__sync_fetch_and_sub_1:
3129   case Builtin::BI__sync_fetch_and_sub_2:
3130   case Builtin::BI__sync_fetch_and_sub_4:
3131   case Builtin::BI__sync_fetch_and_sub_8:
3132   case Builtin::BI__sync_fetch_and_sub_16:
3133     BuiltinIndex = 1;
3134     break;
3135 
3136   case Builtin::BI__sync_fetch_and_or:
3137   case Builtin::BI__sync_fetch_and_or_1:
3138   case Builtin::BI__sync_fetch_and_or_2:
3139   case Builtin::BI__sync_fetch_and_or_4:
3140   case Builtin::BI__sync_fetch_and_or_8:
3141   case Builtin::BI__sync_fetch_and_or_16:
3142     BuiltinIndex = 2;
3143     break;
3144 
3145   case Builtin::BI__sync_fetch_and_and:
3146   case Builtin::BI__sync_fetch_and_and_1:
3147   case Builtin::BI__sync_fetch_and_and_2:
3148   case Builtin::BI__sync_fetch_and_and_4:
3149   case Builtin::BI__sync_fetch_and_and_8:
3150   case Builtin::BI__sync_fetch_and_and_16:
3151     BuiltinIndex = 3;
3152     break;
3153 
3154   case Builtin::BI__sync_fetch_and_xor:
3155   case Builtin::BI__sync_fetch_and_xor_1:
3156   case Builtin::BI__sync_fetch_and_xor_2:
3157   case Builtin::BI__sync_fetch_and_xor_4:
3158   case Builtin::BI__sync_fetch_and_xor_8:
3159   case Builtin::BI__sync_fetch_and_xor_16:
3160     BuiltinIndex = 4;
3161     break;
3162 
3163   case Builtin::BI__sync_fetch_and_nand:
3164   case Builtin::BI__sync_fetch_and_nand_1:
3165   case Builtin::BI__sync_fetch_and_nand_2:
3166   case Builtin::BI__sync_fetch_and_nand_4:
3167   case Builtin::BI__sync_fetch_and_nand_8:
3168   case Builtin::BI__sync_fetch_and_nand_16:
3169     BuiltinIndex = 5;
3170     WarnAboutSemanticsChange = true;
3171     break;
3172 
3173   case Builtin::BI__sync_add_and_fetch:
3174   case Builtin::BI__sync_add_and_fetch_1:
3175   case Builtin::BI__sync_add_and_fetch_2:
3176   case Builtin::BI__sync_add_and_fetch_4:
3177   case Builtin::BI__sync_add_and_fetch_8:
3178   case Builtin::BI__sync_add_and_fetch_16:
3179     BuiltinIndex = 6;
3180     break;
3181 
3182   case Builtin::BI__sync_sub_and_fetch:
3183   case Builtin::BI__sync_sub_and_fetch_1:
3184   case Builtin::BI__sync_sub_and_fetch_2:
3185   case Builtin::BI__sync_sub_and_fetch_4:
3186   case Builtin::BI__sync_sub_and_fetch_8:
3187   case Builtin::BI__sync_sub_and_fetch_16:
3188     BuiltinIndex = 7;
3189     break;
3190 
3191   case Builtin::BI__sync_and_and_fetch:
3192   case Builtin::BI__sync_and_and_fetch_1:
3193   case Builtin::BI__sync_and_and_fetch_2:
3194   case Builtin::BI__sync_and_and_fetch_4:
3195   case Builtin::BI__sync_and_and_fetch_8:
3196   case Builtin::BI__sync_and_and_fetch_16:
3197     BuiltinIndex = 8;
3198     break;
3199 
3200   case Builtin::BI__sync_or_and_fetch:
3201   case Builtin::BI__sync_or_and_fetch_1:
3202   case Builtin::BI__sync_or_and_fetch_2:
3203   case Builtin::BI__sync_or_and_fetch_4:
3204   case Builtin::BI__sync_or_and_fetch_8:
3205   case Builtin::BI__sync_or_and_fetch_16:
3206     BuiltinIndex = 9;
3207     break;
3208 
3209   case Builtin::BI__sync_xor_and_fetch:
3210   case Builtin::BI__sync_xor_and_fetch_1:
3211   case Builtin::BI__sync_xor_and_fetch_2:
3212   case Builtin::BI__sync_xor_and_fetch_4:
3213   case Builtin::BI__sync_xor_and_fetch_8:
3214   case Builtin::BI__sync_xor_and_fetch_16:
3215     BuiltinIndex = 10;
3216     break;
3217 
3218   case Builtin::BI__sync_nand_and_fetch:
3219   case Builtin::BI__sync_nand_and_fetch_1:
3220   case Builtin::BI__sync_nand_and_fetch_2:
3221   case Builtin::BI__sync_nand_and_fetch_4:
3222   case Builtin::BI__sync_nand_and_fetch_8:
3223   case Builtin::BI__sync_nand_and_fetch_16:
3224     BuiltinIndex = 11;
3225     WarnAboutSemanticsChange = true;
3226     break;
3227 
3228   case Builtin::BI__sync_val_compare_and_swap:
3229   case Builtin::BI__sync_val_compare_and_swap_1:
3230   case Builtin::BI__sync_val_compare_and_swap_2:
3231   case Builtin::BI__sync_val_compare_and_swap_4:
3232   case Builtin::BI__sync_val_compare_and_swap_8:
3233   case Builtin::BI__sync_val_compare_and_swap_16:
3234     BuiltinIndex = 12;
3235     NumFixed = 2;
3236     break;
3237 
3238   case Builtin::BI__sync_bool_compare_and_swap:
3239   case Builtin::BI__sync_bool_compare_and_swap_1:
3240   case Builtin::BI__sync_bool_compare_and_swap_2:
3241   case Builtin::BI__sync_bool_compare_and_swap_4:
3242   case Builtin::BI__sync_bool_compare_and_swap_8:
3243   case Builtin::BI__sync_bool_compare_and_swap_16:
3244     BuiltinIndex = 13;
3245     NumFixed = 2;
3246     ResultType = Context.BoolTy;
3247     break;
3248 
3249   case Builtin::BI__sync_lock_test_and_set:
3250   case Builtin::BI__sync_lock_test_and_set_1:
3251   case Builtin::BI__sync_lock_test_and_set_2:
3252   case Builtin::BI__sync_lock_test_and_set_4:
3253   case Builtin::BI__sync_lock_test_and_set_8:
3254   case Builtin::BI__sync_lock_test_and_set_16:
3255     BuiltinIndex = 14;
3256     break;
3257 
3258   case Builtin::BI__sync_lock_release:
3259   case Builtin::BI__sync_lock_release_1:
3260   case Builtin::BI__sync_lock_release_2:
3261   case Builtin::BI__sync_lock_release_4:
3262   case Builtin::BI__sync_lock_release_8:
3263   case Builtin::BI__sync_lock_release_16:
3264     BuiltinIndex = 15;
3265     NumFixed = 0;
3266     ResultType = Context.VoidTy;
3267     break;
3268 
3269   case Builtin::BI__sync_swap:
3270   case Builtin::BI__sync_swap_1:
3271   case Builtin::BI__sync_swap_2:
3272   case Builtin::BI__sync_swap_4:
3273   case Builtin::BI__sync_swap_8:
3274   case Builtin::BI__sync_swap_16:
3275     BuiltinIndex = 16;
3276     break;
3277   }
3278 
3279   // Now that we know how many fixed arguments we expect, first check that we
3280   // have at least that many.
3281   if (TheCall->getNumArgs() < 1+NumFixed) {
3282     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3283       << 0 << 1+NumFixed << TheCall->getNumArgs()
3284       << TheCall->getCallee()->getSourceRange();
3285     return ExprError();
3286   }
3287 
3288   if (WarnAboutSemanticsChange) {
3289     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3290       << TheCall->getCallee()->getSourceRange();
3291   }
3292 
3293   // Get the decl for the concrete builtin from this, we can tell what the
3294   // concrete integer type we should convert to is.
3295   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3296   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3297   FunctionDecl *NewBuiltinDecl;
3298   if (NewBuiltinID == BuiltinID)
3299     NewBuiltinDecl = FDecl;
3300   else {
3301     // Perform builtin lookup to avoid redeclaring it.
3302     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3303     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3304     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3305     assert(Res.getFoundDecl());
3306     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3307     if (!NewBuiltinDecl)
3308       return ExprError();
3309   }
3310 
3311   // The first argument --- the pointer --- has a fixed type; we
3312   // deduce the types of the rest of the arguments accordingly.  Walk
3313   // the remaining arguments, converting them to the deduced value type.
3314   for (unsigned i = 0; i != NumFixed; ++i) {
3315     ExprResult Arg = TheCall->getArg(i+1);
3316 
3317     // GCC does an implicit conversion to the pointer or integer ValType.  This
3318     // can fail in some cases (1i -> int**), check for this error case now.
3319     // Initialize the argument.
3320     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3321                                                    ValType, /*consume*/ false);
3322     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3323     if (Arg.isInvalid())
3324       return ExprError();
3325 
3326     // Okay, we have something that *can* be converted to the right type.  Check
3327     // to see if there is a potentially weird extension going on here.  This can
3328     // happen when you do an atomic operation on something like an char* and
3329     // pass in 42.  The 42 gets converted to char.  This is even more strange
3330     // for things like 45.123 -> char, etc.
3331     // FIXME: Do this check.
3332     TheCall->setArg(i+1, Arg.get());
3333   }
3334 
3335   ASTContext& Context = this->getASTContext();
3336 
3337   // Create a new DeclRefExpr to refer to the new decl.
3338   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3339       Context,
3340       DRE->getQualifierLoc(),
3341       SourceLocation(),
3342       NewBuiltinDecl,
3343       /*enclosing*/ false,
3344       DRE->getLocation(),
3345       Context.BuiltinFnTy,
3346       DRE->getValueKind());
3347 
3348   // Set the callee in the CallExpr.
3349   // FIXME: This loses syntactic information.
3350   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3351   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3352                                               CK_BuiltinFnToFnPtr);
3353   TheCall->setCallee(PromotedCall.get());
3354 
3355   // Change the result type of the call to match the original value type. This
3356   // is arbitrary, but the codegen for these builtins ins design to handle it
3357   // gracefully.
3358   TheCall->setType(ResultType);
3359 
3360   return TheCallResult;
3361 }
3362 
3363 /// SemaBuiltinNontemporalOverloaded - We have a call to
3364 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3365 /// overloaded function based on the pointer type of its last argument.
3366 ///
3367 /// This function goes through and does final semantic checking for these
3368 /// builtins.
3369 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3370   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3371   DeclRefExpr *DRE =
3372       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3373   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3374   unsigned BuiltinID = FDecl->getBuiltinID();
3375   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3376           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3377          "Unexpected nontemporal load/store builtin!");
3378   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3379   unsigned numArgs = isStore ? 2 : 1;
3380 
3381   // Ensure that we have the proper number of arguments.
3382   if (checkArgCount(*this, TheCall, numArgs))
3383     return ExprError();
3384 
3385   // Inspect the last argument of the nontemporal builtin.  This should always
3386   // be a pointer type, from which we imply the type of the memory access.
3387   // Because it is a pointer type, we don't have to worry about any implicit
3388   // casts here.
3389   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3390   ExprResult PointerArgResult =
3391       DefaultFunctionArrayLvalueConversion(PointerArg);
3392 
3393   if (PointerArgResult.isInvalid())
3394     return ExprError();
3395   PointerArg = PointerArgResult.get();
3396   TheCall->setArg(numArgs - 1, PointerArg);
3397 
3398   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3399   if (!pointerType) {
3400     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3401         << PointerArg->getType() << PointerArg->getSourceRange();
3402     return ExprError();
3403   }
3404 
3405   QualType ValType = pointerType->getPointeeType();
3406 
3407   // Strip any qualifiers off ValType.
3408   ValType = ValType.getUnqualifiedType();
3409   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3410       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3411       !ValType->isVectorType()) {
3412     Diag(DRE->getLocStart(),
3413          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3414         << PointerArg->getType() << PointerArg->getSourceRange();
3415     return ExprError();
3416   }
3417 
3418   if (!isStore) {
3419     TheCall->setType(ValType);
3420     return TheCallResult;
3421   }
3422 
3423   ExprResult ValArg = TheCall->getArg(0);
3424   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3425       Context, ValType, /*consume*/ false);
3426   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3427   if (ValArg.isInvalid())
3428     return ExprError();
3429 
3430   TheCall->setArg(0, ValArg.get());
3431   TheCall->setType(Context.VoidTy);
3432   return TheCallResult;
3433 }
3434 
3435 /// CheckObjCString - Checks that the argument to the builtin
3436 /// CFString constructor is correct
3437 /// Note: It might also make sense to do the UTF-16 conversion here (would
3438 /// simplify the backend).
3439 bool Sema::CheckObjCString(Expr *Arg) {
3440   Arg = Arg->IgnoreParenCasts();
3441   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3442 
3443   if (!Literal || !Literal->isAscii()) {
3444     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3445       << Arg->getSourceRange();
3446     return true;
3447   }
3448 
3449   if (Literal->containsNonAsciiOrNull()) {
3450     StringRef String = Literal->getString();
3451     unsigned NumBytes = String.size();
3452     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3453     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3454     llvm::UTF16 *ToPtr = &ToBuf[0];
3455 
3456     llvm::ConversionResult Result =
3457         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3458                                  ToPtr + NumBytes, llvm::strictConversion);
3459     // Check for conversion failure.
3460     if (Result != llvm::conversionOK)
3461       Diag(Arg->getLocStart(),
3462            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3463   }
3464   return false;
3465 }
3466 
3467 /// CheckObjCString - Checks that the format string argument to the os_log()
3468 /// and os_trace() functions is correct, and converts it to const char *.
3469 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3470   Arg = Arg->IgnoreParenCasts();
3471   auto *Literal = dyn_cast<StringLiteral>(Arg);
3472   if (!Literal) {
3473     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3474       Literal = ObjcLiteral->getString();
3475     }
3476   }
3477 
3478   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3479     return ExprError(
3480         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3481         << Arg->getSourceRange());
3482   }
3483 
3484   ExprResult Result(Literal);
3485   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3486   InitializedEntity Entity =
3487       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3488   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3489   return Result;
3490 }
3491 
3492 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3493 /// for validity.  Emit an error and return true on failure; return false
3494 /// on success.
3495 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
3496   Expr *Fn = TheCall->getCallee();
3497   if (TheCall->getNumArgs() > 2) {
3498     Diag(TheCall->getArg(2)->getLocStart(),
3499          diag::err_typecheck_call_too_many_args)
3500       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3501       << Fn->getSourceRange()
3502       << SourceRange(TheCall->getArg(2)->getLocStart(),
3503                      (*(TheCall->arg_end()-1))->getLocEnd());
3504     return true;
3505   }
3506 
3507   if (TheCall->getNumArgs() < 2) {
3508     return Diag(TheCall->getLocEnd(),
3509       diag::err_typecheck_call_too_few_args_at_least)
3510       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3511   }
3512 
3513   // Type-check the first argument normally.
3514   if (checkBuiltinArgument(*this, TheCall, 0))
3515     return true;
3516 
3517   // Determine whether the current function is variadic or not.
3518   BlockScopeInfo *CurBlock = getCurBlock();
3519   bool isVariadic;
3520   if (CurBlock)
3521     isVariadic = CurBlock->TheDecl->isVariadic();
3522   else if (FunctionDecl *FD = getCurFunctionDecl())
3523     isVariadic = FD->isVariadic();
3524   else
3525     isVariadic = getCurMethodDecl()->isVariadic();
3526 
3527   if (!isVariadic) {
3528     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3529     return true;
3530   }
3531 
3532   // Verify that the second argument to the builtin is the last argument of the
3533   // current function or method.
3534   bool SecondArgIsLastNamedArgument = false;
3535   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3536 
3537   // These are valid if SecondArgIsLastNamedArgument is false after the next
3538   // block.
3539   QualType Type;
3540   SourceLocation ParamLoc;
3541   bool IsCRegister = false;
3542 
3543   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3544     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3545       // FIXME: This isn't correct for methods (results in bogus warning).
3546       // Get the last formal in the current function.
3547       const ParmVarDecl *LastArg;
3548       if (CurBlock)
3549         LastArg = CurBlock->TheDecl->parameters().back();
3550       else if (FunctionDecl *FD = getCurFunctionDecl())
3551         LastArg = FD->parameters().back();
3552       else
3553         LastArg = getCurMethodDecl()->parameters().back();
3554       SecondArgIsLastNamedArgument = PV == LastArg;
3555 
3556       Type = PV->getType();
3557       ParamLoc = PV->getLocation();
3558       IsCRegister =
3559           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3560     }
3561   }
3562 
3563   if (!SecondArgIsLastNamedArgument)
3564     Diag(TheCall->getArg(1)->getLocStart(),
3565          diag::warn_second_arg_of_va_start_not_last_named_param);
3566   else if (IsCRegister || Type->isReferenceType() ||
3567            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3568              // Promotable integers are UB, but enumerations need a bit of
3569              // extra checking to see what their promotable type actually is.
3570              if (!Type->isPromotableIntegerType())
3571                return false;
3572              if (!Type->isEnumeralType())
3573                return true;
3574              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3575              return !(ED &&
3576                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3577            }()) {
3578     unsigned Reason = 0;
3579     if (Type->isReferenceType())  Reason = 1;
3580     else if (IsCRegister)         Reason = 2;
3581     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3582     Diag(ParamLoc, diag::note_parameter_type) << Type;
3583   }
3584 
3585   TheCall->setType(Context.VoidTy);
3586   return false;
3587 }
3588 
3589 /// Check the arguments to '__builtin_va_start' for validity, and that
3590 /// it was called from a function of the native ABI.
3591 /// Emit an error and return true on failure; return false on success.
3592 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3593   // On x86-64 Unix, don't allow this in Win64 ABI functions.
3594   // On x64 Windows, don't allow this in System V ABI functions.
3595   // (Yes, that means there's no corresponding way to support variadic
3596   // System V ABI functions on Windows.)
3597   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3598     unsigned OS = Context.getTargetInfo().getTriple().getOS();
3599     clang::CallingConv CC = CC_C;
3600     if (const FunctionDecl *FD = getCurFunctionDecl())
3601       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3602     if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3603         (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3604       return Diag(TheCall->getCallee()->getLocStart(),
3605                   diag::err_va_start_used_in_wrong_abi_function)
3606              << (OS != llvm::Triple::Win32);
3607   }
3608   return SemaBuiltinVAStartImpl(TheCall);
3609 }
3610 
3611 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3612 /// it was called from a Win64 ABI function.
3613 /// Emit an error and return true on failure; return false on success.
3614 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3615   // This only makes sense for x86-64.
3616   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3617   Expr *Callee = TheCall->getCallee();
3618   if (TT.getArch() != llvm::Triple::x86_64)
3619     return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3620   // Don't allow this in System V ABI functions.
3621   clang::CallingConv CC = CC_C;
3622   if (const FunctionDecl *FD = getCurFunctionDecl())
3623     CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3624   if (CC == CC_X86_64SysV ||
3625       (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3626     return Diag(Callee->getLocStart(),
3627                 diag::err_ms_va_start_used_in_sysv_function);
3628   return SemaBuiltinVAStartImpl(TheCall);
3629 }
3630 
3631 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3632   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3633   //                 const char *named_addr);
3634 
3635   Expr *Func = Call->getCallee();
3636 
3637   if (Call->getNumArgs() < 3)
3638     return Diag(Call->getLocEnd(),
3639                 diag::err_typecheck_call_too_few_args_at_least)
3640            << 0 /*function call*/ << 3 << Call->getNumArgs();
3641 
3642   // Determine whether the current function is variadic or not.
3643   bool IsVariadic;
3644   if (BlockScopeInfo *CurBlock = getCurBlock())
3645     IsVariadic = CurBlock->TheDecl->isVariadic();
3646   else if (FunctionDecl *FD = getCurFunctionDecl())
3647     IsVariadic = FD->isVariadic();
3648   else if (ObjCMethodDecl *MD = getCurMethodDecl())
3649     IsVariadic = MD->isVariadic();
3650   else
3651     llvm_unreachable("unexpected statement type");
3652 
3653   if (!IsVariadic) {
3654     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3655     return true;
3656   }
3657 
3658   // Type-check the first argument normally.
3659   if (checkBuiltinArgument(*this, Call, 0))
3660     return true;
3661 
3662   const struct {
3663     unsigned ArgNo;
3664     QualType Type;
3665   } ArgumentTypes[] = {
3666     { 1, Context.getPointerType(Context.CharTy.withConst()) },
3667     { 2, Context.getSizeType() },
3668   };
3669 
3670   for (const auto &AT : ArgumentTypes) {
3671     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3672     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3673       continue;
3674     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3675       << Arg->getType() << AT.Type << 1 /* different class */
3676       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3677       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3678   }
3679 
3680   return false;
3681 }
3682 
3683 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3684 /// friends.  This is declared to take (...), so we have to check everything.
3685 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3686   if (TheCall->getNumArgs() < 2)
3687     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3688       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3689   if (TheCall->getNumArgs() > 2)
3690     return Diag(TheCall->getArg(2)->getLocStart(),
3691                 diag::err_typecheck_call_too_many_args)
3692       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3693       << SourceRange(TheCall->getArg(2)->getLocStart(),
3694                      (*(TheCall->arg_end()-1))->getLocEnd());
3695 
3696   ExprResult OrigArg0 = TheCall->getArg(0);
3697   ExprResult OrigArg1 = TheCall->getArg(1);
3698 
3699   // Do standard promotions between the two arguments, returning their common
3700   // type.
3701   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3702   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3703     return true;
3704 
3705   // Make sure any conversions are pushed back into the call; this is
3706   // type safe since unordered compare builtins are declared as "_Bool
3707   // foo(...)".
3708   TheCall->setArg(0, OrigArg0.get());
3709   TheCall->setArg(1, OrigArg1.get());
3710 
3711   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3712     return false;
3713 
3714   // If the common type isn't a real floating type, then the arguments were
3715   // invalid for this operation.
3716   if (Res.isNull() || !Res->isRealFloatingType())
3717     return Diag(OrigArg0.get()->getLocStart(),
3718                 diag::err_typecheck_call_invalid_ordered_compare)
3719       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3720       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3721 
3722   return false;
3723 }
3724 
3725 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3726 /// __builtin_isnan and friends.  This is declared to take (...), so we have
3727 /// to check everything. We expect the last argument to be a floating point
3728 /// value.
3729 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3730   if (TheCall->getNumArgs() < NumArgs)
3731     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3732       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3733   if (TheCall->getNumArgs() > NumArgs)
3734     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3735                 diag::err_typecheck_call_too_many_args)
3736       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3737       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3738                      (*(TheCall->arg_end()-1))->getLocEnd());
3739 
3740   Expr *OrigArg = TheCall->getArg(NumArgs-1);
3741 
3742   if (OrigArg->isTypeDependent())
3743     return false;
3744 
3745   // This operation requires a non-_Complex floating-point number.
3746   if (!OrigArg->getType()->isRealFloatingType())
3747     return Diag(OrigArg->getLocStart(),
3748                 diag::err_typecheck_call_invalid_unary_fp)
3749       << OrigArg->getType() << OrigArg->getSourceRange();
3750 
3751   // If this is an implicit conversion from float -> double, remove it.
3752   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3753     Expr *CastArg = Cast->getSubExpr();
3754     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3755       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3756              "promotion from float to double is the only expected cast here");
3757       Cast->setSubExpr(nullptr);
3758       TheCall->setArg(NumArgs-1, CastArg);
3759     }
3760   }
3761 
3762   return false;
3763 }
3764 
3765 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3766 // This is declared to take (...), so we have to check everything.
3767 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3768   if (TheCall->getNumArgs() < 2)
3769     return ExprError(Diag(TheCall->getLocEnd(),
3770                           diag::err_typecheck_call_too_few_args_at_least)
3771                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3772                      << TheCall->getSourceRange());
3773 
3774   // Determine which of the following types of shufflevector we're checking:
3775   // 1) unary, vector mask: (lhs, mask)
3776   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3777   QualType resType = TheCall->getArg(0)->getType();
3778   unsigned numElements = 0;
3779 
3780   if (!TheCall->getArg(0)->isTypeDependent() &&
3781       !TheCall->getArg(1)->isTypeDependent()) {
3782     QualType LHSType = TheCall->getArg(0)->getType();
3783     QualType RHSType = TheCall->getArg(1)->getType();
3784 
3785     if (!LHSType->isVectorType() || !RHSType->isVectorType())
3786       return ExprError(Diag(TheCall->getLocStart(),
3787                             diag::err_shufflevector_non_vector)
3788                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3789                                       TheCall->getArg(1)->getLocEnd()));
3790 
3791     numElements = LHSType->getAs<VectorType>()->getNumElements();
3792     unsigned numResElements = TheCall->getNumArgs() - 2;
3793 
3794     // Check to see if we have a call with 2 vector arguments, the unary shuffle
3795     // with mask.  If so, verify that RHS is an integer vector type with the
3796     // same number of elts as lhs.
3797     if (TheCall->getNumArgs() == 2) {
3798       if (!RHSType->hasIntegerRepresentation() ||
3799           RHSType->getAs<VectorType>()->getNumElements() != numElements)
3800         return ExprError(Diag(TheCall->getLocStart(),
3801                               diag::err_shufflevector_incompatible_vector)
3802                          << SourceRange(TheCall->getArg(1)->getLocStart(),
3803                                         TheCall->getArg(1)->getLocEnd()));
3804     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3805       return ExprError(Diag(TheCall->getLocStart(),
3806                             diag::err_shufflevector_incompatible_vector)
3807                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3808                                       TheCall->getArg(1)->getLocEnd()));
3809     } else if (numElements != numResElements) {
3810       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3811       resType = Context.getVectorType(eltType, numResElements,
3812                                       VectorType::GenericVector);
3813     }
3814   }
3815 
3816   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3817     if (TheCall->getArg(i)->isTypeDependent() ||
3818         TheCall->getArg(i)->isValueDependent())
3819       continue;
3820 
3821     llvm::APSInt Result(32);
3822     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3823       return ExprError(Diag(TheCall->getLocStart(),
3824                             diag::err_shufflevector_nonconstant_argument)
3825                        << TheCall->getArg(i)->getSourceRange());
3826 
3827     // Allow -1 which will be translated to undef in the IR.
3828     if (Result.isSigned() && Result.isAllOnesValue())
3829       continue;
3830 
3831     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3832       return ExprError(Diag(TheCall->getLocStart(),
3833                             diag::err_shufflevector_argument_too_large)
3834                        << TheCall->getArg(i)->getSourceRange());
3835   }
3836 
3837   SmallVector<Expr*, 32> exprs;
3838 
3839   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3840     exprs.push_back(TheCall->getArg(i));
3841     TheCall->setArg(i, nullptr);
3842   }
3843 
3844   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3845                                          TheCall->getCallee()->getLocStart(),
3846                                          TheCall->getRParenLoc());
3847 }
3848 
3849 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3850 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3851                                        SourceLocation BuiltinLoc,
3852                                        SourceLocation RParenLoc) {
3853   ExprValueKind VK = VK_RValue;
3854   ExprObjectKind OK = OK_Ordinary;
3855   QualType DstTy = TInfo->getType();
3856   QualType SrcTy = E->getType();
3857 
3858   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3859     return ExprError(Diag(BuiltinLoc,
3860                           diag::err_convertvector_non_vector)
3861                      << E->getSourceRange());
3862   if (!DstTy->isVectorType() && !DstTy->isDependentType())
3863     return ExprError(Diag(BuiltinLoc,
3864                           diag::err_convertvector_non_vector_type));
3865 
3866   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3867     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3868     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3869     if (SrcElts != DstElts)
3870       return ExprError(Diag(BuiltinLoc,
3871                             diag::err_convertvector_incompatible_vector)
3872                        << E->getSourceRange());
3873   }
3874 
3875   return new (Context)
3876       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3877 }
3878 
3879 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3880 // This is declared to take (const void*, ...) and can take two
3881 // optional constant int args.
3882 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3883   unsigned NumArgs = TheCall->getNumArgs();
3884 
3885   if (NumArgs > 3)
3886     return Diag(TheCall->getLocEnd(),
3887              diag::err_typecheck_call_too_many_args_at_most)
3888              << 0 /*function call*/ << 3 << NumArgs
3889              << TheCall->getSourceRange();
3890 
3891   // Argument 0 is checked for us and the remaining arguments must be
3892   // constant integers.
3893   for (unsigned i = 1; i != NumArgs; ++i)
3894     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3895       return true;
3896 
3897   return false;
3898 }
3899 
3900 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3901 // __assume does not evaluate its arguments, and should warn if its argument
3902 // has side effects.
3903 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3904   Expr *Arg = TheCall->getArg(0);
3905   if (Arg->isInstantiationDependent()) return false;
3906 
3907   if (Arg->HasSideEffects(Context))
3908     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3909       << Arg->getSourceRange()
3910       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3911 
3912   return false;
3913 }
3914 
3915 /// Handle __builtin_alloca_with_align. This is declared
3916 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3917 /// than 8.
3918 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3919   // The alignment must be a constant integer.
3920   Expr *Arg = TheCall->getArg(1);
3921 
3922   // We can't check the value of a dependent argument.
3923   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3924     if (const auto *UE =
3925             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3926       if (UE->getKind() == UETT_AlignOf)
3927         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3928           << Arg->getSourceRange();
3929 
3930     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3931 
3932     if (!Result.isPowerOf2())
3933       return Diag(TheCall->getLocStart(),
3934                   diag::err_alignment_not_power_of_two)
3935            << Arg->getSourceRange();
3936 
3937     if (Result < Context.getCharWidth())
3938       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3939            << (unsigned)Context.getCharWidth()
3940            << Arg->getSourceRange();
3941 
3942     if (Result > INT32_MAX)
3943       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3944            << INT32_MAX
3945            << Arg->getSourceRange();
3946   }
3947 
3948   return false;
3949 }
3950 
3951 /// Handle __builtin_assume_aligned. This is declared
3952 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3953 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3954   unsigned NumArgs = TheCall->getNumArgs();
3955 
3956   if (NumArgs > 3)
3957     return Diag(TheCall->getLocEnd(),
3958              diag::err_typecheck_call_too_many_args_at_most)
3959              << 0 /*function call*/ << 3 << NumArgs
3960              << TheCall->getSourceRange();
3961 
3962   // The alignment must be a constant integer.
3963   Expr *Arg = TheCall->getArg(1);
3964 
3965   // We can't check the value of a dependent argument.
3966   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3967     llvm::APSInt Result;
3968     if (SemaBuiltinConstantArg(TheCall, 1, Result))
3969       return true;
3970 
3971     if (!Result.isPowerOf2())
3972       return Diag(TheCall->getLocStart(),
3973                   diag::err_alignment_not_power_of_two)
3974            << Arg->getSourceRange();
3975   }
3976 
3977   if (NumArgs > 2) {
3978     ExprResult Arg(TheCall->getArg(2));
3979     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3980       Context.getSizeType(), false);
3981     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3982     if (Arg.isInvalid()) return true;
3983     TheCall->setArg(2, Arg.get());
3984   }
3985 
3986   return false;
3987 }
3988 
3989 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
3990   unsigned BuiltinID =
3991       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
3992   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
3993 
3994   unsigned NumArgs = TheCall->getNumArgs();
3995   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
3996   if (NumArgs < NumRequiredArgs) {
3997     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3998            << 0 /* function call */ << NumRequiredArgs << NumArgs
3999            << TheCall->getSourceRange();
4000   }
4001   if (NumArgs >= NumRequiredArgs + 0x100) {
4002     return Diag(TheCall->getLocEnd(),
4003                 diag::err_typecheck_call_too_many_args_at_most)
4004            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4005            << TheCall->getSourceRange();
4006   }
4007   unsigned i = 0;
4008 
4009   // For formatting call, check buffer arg.
4010   if (!IsSizeCall) {
4011     ExprResult Arg(TheCall->getArg(i));
4012     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4013         Context, Context.VoidPtrTy, false);
4014     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4015     if (Arg.isInvalid())
4016       return true;
4017     TheCall->setArg(i, Arg.get());
4018     i++;
4019   }
4020 
4021   // Check string literal arg.
4022   unsigned FormatIdx = i;
4023   {
4024     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4025     if (Arg.isInvalid())
4026       return true;
4027     TheCall->setArg(i, Arg.get());
4028     i++;
4029   }
4030 
4031   // Make sure variadic args are scalar.
4032   unsigned FirstDataArg = i;
4033   while (i < NumArgs) {
4034     ExprResult Arg = DefaultVariadicArgumentPromotion(
4035         TheCall->getArg(i), VariadicFunction, nullptr);
4036     if (Arg.isInvalid())
4037       return true;
4038     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4039     if (ArgSize.getQuantity() >= 0x100) {
4040       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4041              << i << (int)ArgSize.getQuantity() << 0xff
4042              << TheCall->getSourceRange();
4043     }
4044     TheCall->setArg(i, Arg.get());
4045     i++;
4046   }
4047 
4048   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4049   // call to avoid duplicate diagnostics.
4050   if (!IsSizeCall) {
4051     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4052     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4053     bool Success = CheckFormatArguments(
4054         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4055         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4056         CheckedVarArgs);
4057     if (!Success)
4058       return true;
4059   }
4060 
4061   if (IsSizeCall) {
4062     TheCall->setType(Context.getSizeType());
4063   } else {
4064     TheCall->setType(Context.VoidPtrTy);
4065   }
4066   return false;
4067 }
4068 
4069 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4070 /// TheCall is a constant expression.
4071 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4072                                   llvm::APSInt &Result) {
4073   Expr *Arg = TheCall->getArg(ArgNum);
4074   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4075   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4076 
4077   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4078 
4079   if (!Arg->isIntegerConstantExpr(Result, Context))
4080     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4081                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4082 
4083   return false;
4084 }
4085 
4086 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4087 /// TheCall is a constant expression in the range [Low, High].
4088 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4089                                        int Low, int High) {
4090   llvm::APSInt Result;
4091 
4092   // We can't check the value of a dependent argument.
4093   Expr *Arg = TheCall->getArg(ArgNum);
4094   if (Arg->isTypeDependent() || Arg->isValueDependent())
4095     return false;
4096 
4097   // Check constant-ness first.
4098   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4099     return true;
4100 
4101   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4102     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4103       << Low << High << Arg->getSourceRange();
4104 
4105   return false;
4106 }
4107 
4108 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4109 /// TheCall is a constant expression is a multiple of Num..
4110 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4111                                           unsigned Num) {
4112   llvm::APSInt Result;
4113 
4114   // We can't check the value of a dependent argument.
4115   Expr *Arg = TheCall->getArg(ArgNum);
4116   if (Arg->isTypeDependent() || Arg->isValueDependent())
4117     return false;
4118 
4119   // Check constant-ness first.
4120   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4121     return true;
4122 
4123   if (Result.getSExtValue() % Num != 0)
4124     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4125       << Num << Arg->getSourceRange();
4126 
4127   return false;
4128 }
4129 
4130 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4131 /// TheCall is an ARM/AArch64 special register string literal.
4132 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4133                                     int ArgNum, unsigned ExpectedFieldNum,
4134                                     bool AllowName) {
4135   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4136                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4137                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4138                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4139                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4140                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4141   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4142                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4143                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4144                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4145                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4146                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4147   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4148 
4149   // We can't check the value of a dependent argument.
4150   Expr *Arg = TheCall->getArg(ArgNum);
4151   if (Arg->isTypeDependent() || Arg->isValueDependent())
4152     return false;
4153 
4154   // Check if the argument is a string literal.
4155   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4156     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4157            << Arg->getSourceRange();
4158 
4159   // Check the type of special register given.
4160   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4161   SmallVector<StringRef, 6> Fields;
4162   Reg.split(Fields, ":");
4163 
4164   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4165     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4166            << Arg->getSourceRange();
4167 
4168   // If the string is the name of a register then we cannot check that it is
4169   // valid here but if the string is of one the forms described in ACLE then we
4170   // can check that the supplied fields are integers and within the valid
4171   // ranges.
4172   if (Fields.size() > 1) {
4173     bool FiveFields = Fields.size() == 5;
4174 
4175     bool ValidString = true;
4176     if (IsARMBuiltin) {
4177       ValidString &= Fields[0].startswith_lower("cp") ||
4178                      Fields[0].startswith_lower("p");
4179       if (ValidString)
4180         Fields[0] =
4181           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4182 
4183       ValidString &= Fields[2].startswith_lower("c");
4184       if (ValidString)
4185         Fields[2] = Fields[2].drop_front(1);
4186 
4187       if (FiveFields) {
4188         ValidString &= Fields[3].startswith_lower("c");
4189         if (ValidString)
4190           Fields[3] = Fields[3].drop_front(1);
4191       }
4192     }
4193 
4194     SmallVector<int, 5> Ranges;
4195     if (FiveFields)
4196       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4197     else
4198       Ranges.append({15, 7, 15});
4199 
4200     for (unsigned i=0; i<Fields.size(); ++i) {
4201       int IntField;
4202       ValidString &= !Fields[i].getAsInteger(10, IntField);
4203       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4204     }
4205 
4206     if (!ValidString)
4207       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4208              << Arg->getSourceRange();
4209 
4210   } else if (IsAArch64Builtin && Fields.size() == 1) {
4211     // If the register name is one of those that appear in the condition below
4212     // and the special register builtin being used is one of the write builtins,
4213     // then we require that the argument provided for writing to the register
4214     // is an integer constant expression. This is because it will be lowered to
4215     // an MSR (immediate) instruction, so we need to know the immediate at
4216     // compile time.
4217     if (TheCall->getNumArgs() != 2)
4218       return false;
4219 
4220     std::string RegLower = Reg.lower();
4221     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4222         RegLower != "pan" && RegLower != "uao")
4223       return false;
4224 
4225     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4226   }
4227 
4228   return false;
4229 }
4230 
4231 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4232 /// This checks that the target supports __builtin_longjmp and
4233 /// that val is a constant 1.
4234 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4235   if (!Context.getTargetInfo().hasSjLjLowering())
4236     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4237              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4238 
4239   Expr *Arg = TheCall->getArg(1);
4240   llvm::APSInt Result;
4241 
4242   // TODO: This is less than ideal. Overload this to take a value.
4243   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4244     return true;
4245 
4246   if (Result != 1)
4247     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4248              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4249 
4250   return false;
4251 }
4252 
4253 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4254 /// This checks that the target supports __builtin_setjmp.
4255 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4256   if (!Context.getTargetInfo().hasSjLjLowering())
4257     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4258              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4259   return false;
4260 }
4261 
4262 namespace {
4263 class UncoveredArgHandler {
4264   enum { Unknown = -1, AllCovered = -2 };
4265   signed FirstUncoveredArg;
4266   SmallVector<const Expr *, 4> DiagnosticExprs;
4267 
4268 public:
4269   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4270 
4271   bool hasUncoveredArg() const {
4272     return (FirstUncoveredArg >= 0);
4273   }
4274 
4275   unsigned getUncoveredArg() const {
4276     assert(hasUncoveredArg() && "no uncovered argument");
4277     return FirstUncoveredArg;
4278   }
4279 
4280   void setAllCovered() {
4281     // A string has been found with all arguments covered, so clear out
4282     // the diagnostics.
4283     DiagnosticExprs.clear();
4284     FirstUncoveredArg = AllCovered;
4285   }
4286 
4287   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4288     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4289 
4290     // Don't update if a previous string covers all arguments.
4291     if (FirstUncoveredArg == AllCovered)
4292       return;
4293 
4294     // UncoveredArgHandler tracks the highest uncovered argument index
4295     // and with it all the strings that match this index.
4296     if (NewFirstUncoveredArg == FirstUncoveredArg)
4297       DiagnosticExprs.push_back(StrExpr);
4298     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4299       DiagnosticExprs.clear();
4300       DiagnosticExprs.push_back(StrExpr);
4301       FirstUncoveredArg = NewFirstUncoveredArg;
4302     }
4303   }
4304 
4305   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4306 };
4307 
4308 enum StringLiteralCheckType {
4309   SLCT_NotALiteral,
4310   SLCT_UncheckedLiteral,
4311   SLCT_CheckedLiteral
4312 };
4313 } // end anonymous namespace
4314 
4315 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4316                                      BinaryOperatorKind BinOpKind,
4317                                      bool AddendIsRight) {
4318   unsigned BitWidth = Offset.getBitWidth();
4319   unsigned AddendBitWidth = Addend.getBitWidth();
4320   // There might be negative interim results.
4321   if (Addend.isUnsigned()) {
4322     Addend = Addend.zext(++AddendBitWidth);
4323     Addend.setIsSigned(true);
4324   }
4325   // Adjust the bit width of the APSInts.
4326   if (AddendBitWidth > BitWidth) {
4327     Offset = Offset.sext(AddendBitWidth);
4328     BitWidth = AddendBitWidth;
4329   } else if (BitWidth > AddendBitWidth) {
4330     Addend = Addend.sext(BitWidth);
4331   }
4332 
4333   bool Ov = false;
4334   llvm::APSInt ResOffset = Offset;
4335   if (BinOpKind == BO_Add)
4336     ResOffset = Offset.sadd_ov(Addend, Ov);
4337   else {
4338     assert(AddendIsRight && BinOpKind == BO_Sub &&
4339            "operator must be add or sub with addend on the right");
4340     ResOffset = Offset.ssub_ov(Addend, Ov);
4341   }
4342 
4343   // We add an offset to a pointer here so we should support an offset as big as
4344   // possible.
4345   if (Ov) {
4346     assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4347     Offset = Offset.sext(2 * BitWidth);
4348     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4349     return;
4350   }
4351 
4352   Offset = ResOffset;
4353 }
4354 
4355 namespace {
4356 // This is a wrapper class around StringLiteral to support offsetted string
4357 // literals as format strings. It takes the offset into account when returning
4358 // the string and its length or the source locations to display notes correctly.
4359 class FormatStringLiteral {
4360   const StringLiteral *FExpr;
4361   int64_t Offset;
4362 
4363  public:
4364   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4365       : FExpr(fexpr), Offset(Offset) {}
4366 
4367   StringRef getString() const {
4368     return FExpr->getString().drop_front(Offset);
4369   }
4370 
4371   unsigned getByteLength() const {
4372     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4373   }
4374   unsigned getLength() const { return FExpr->getLength() - Offset; }
4375   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4376 
4377   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4378 
4379   QualType getType() const { return FExpr->getType(); }
4380 
4381   bool isAscii() const { return FExpr->isAscii(); }
4382   bool isWide() const { return FExpr->isWide(); }
4383   bool isUTF8() const { return FExpr->isUTF8(); }
4384   bool isUTF16() const { return FExpr->isUTF16(); }
4385   bool isUTF32() const { return FExpr->isUTF32(); }
4386   bool isPascal() const { return FExpr->isPascal(); }
4387 
4388   SourceLocation getLocationOfByte(
4389       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4390       const TargetInfo &Target, unsigned *StartToken = nullptr,
4391       unsigned *StartTokenByteOffset = nullptr) const {
4392     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4393                                     StartToken, StartTokenByteOffset);
4394   }
4395 
4396   SourceLocation getLocStart() const LLVM_READONLY {
4397     return FExpr->getLocStart().getLocWithOffset(Offset);
4398   }
4399   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4400 };
4401 }  // end anonymous namespace
4402 
4403 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4404                               const Expr *OrigFormatExpr,
4405                               ArrayRef<const Expr *> Args,
4406                               bool HasVAListArg, unsigned format_idx,
4407                               unsigned firstDataArg,
4408                               Sema::FormatStringType Type,
4409                               bool inFunctionCall,
4410                               Sema::VariadicCallType CallType,
4411                               llvm::SmallBitVector &CheckedVarArgs,
4412                               UncoveredArgHandler &UncoveredArg);
4413 
4414 // Determine if an expression is a string literal or constant string.
4415 // If this function returns false on the arguments to a function expecting a
4416 // format string, we will usually need to emit a warning.
4417 // True string literals are then checked by CheckFormatString.
4418 static StringLiteralCheckType
4419 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4420                       bool HasVAListArg, unsigned format_idx,
4421                       unsigned firstDataArg, Sema::FormatStringType Type,
4422                       Sema::VariadicCallType CallType, bool InFunctionCall,
4423                       llvm::SmallBitVector &CheckedVarArgs,
4424                       UncoveredArgHandler &UncoveredArg,
4425                       llvm::APSInt Offset) {
4426  tryAgain:
4427   assert(Offset.isSigned() && "invalid offset");
4428 
4429   if (E->isTypeDependent() || E->isValueDependent())
4430     return SLCT_NotALiteral;
4431 
4432   E = E->IgnoreParenCasts();
4433 
4434   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4435     // Technically -Wformat-nonliteral does not warn about this case.
4436     // The behavior of printf and friends in this case is implementation
4437     // dependent.  Ideally if the format string cannot be null then
4438     // it should have a 'nonnull' attribute in the function prototype.
4439     return SLCT_UncheckedLiteral;
4440 
4441   switch (E->getStmtClass()) {
4442   case Stmt::BinaryConditionalOperatorClass:
4443   case Stmt::ConditionalOperatorClass: {
4444     // The expression is a literal if both sub-expressions were, and it was
4445     // completely checked only if both sub-expressions were checked.
4446     const AbstractConditionalOperator *C =
4447         cast<AbstractConditionalOperator>(E);
4448 
4449     // Determine whether it is necessary to check both sub-expressions, for
4450     // example, because the condition expression is a constant that can be
4451     // evaluated at compile time.
4452     bool CheckLeft = true, CheckRight = true;
4453 
4454     bool Cond;
4455     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4456       if (Cond)
4457         CheckRight = false;
4458       else
4459         CheckLeft = false;
4460     }
4461 
4462     // We need to maintain the offsets for the right and the left hand side
4463     // separately to check if every possible indexed expression is a valid
4464     // string literal. They might have different offsets for different string
4465     // literals in the end.
4466     StringLiteralCheckType Left;
4467     if (!CheckLeft)
4468       Left = SLCT_UncheckedLiteral;
4469     else {
4470       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4471                                    HasVAListArg, format_idx, firstDataArg,
4472                                    Type, CallType, InFunctionCall,
4473                                    CheckedVarArgs, UncoveredArg, Offset);
4474       if (Left == SLCT_NotALiteral || !CheckRight) {
4475         return Left;
4476       }
4477     }
4478 
4479     StringLiteralCheckType Right =
4480         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4481                               HasVAListArg, format_idx, firstDataArg,
4482                               Type, CallType, InFunctionCall, CheckedVarArgs,
4483                               UncoveredArg, Offset);
4484 
4485     return (CheckLeft && Left < Right) ? Left : Right;
4486   }
4487 
4488   case Stmt::ImplicitCastExprClass: {
4489     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4490     goto tryAgain;
4491   }
4492 
4493   case Stmt::OpaqueValueExprClass:
4494     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4495       E = src;
4496       goto tryAgain;
4497     }
4498     return SLCT_NotALiteral;
4499 
4500   case Stmt::PredefinedExprClass:
4501     // While __func__, etc., are technically not string literals, they
4502     // cannot contain format specifiers and thus are not a security
4503     // liability.
4504     return SLCT_UncheckedLiteral;
4505 
4506   case Stmt::DeclRefExprClass: {
4507     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4508 
4509     // As an exception, do not flag errors for variables binding to
4510     // const string literals.
4511     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4512       bool isConstant = false;
4513       QualType T = DR->getType();
4514 
4515       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4516         isConstant = AT->getElementType().isConstant(S.Context);
4517       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4518         isConstant = T.isConstant(S.Context) &&
4519                      PT->getPointeeType().isConstant(S.Context);
4520       } else if (T->isObjCObjectPointerType()) {
4521         // In ObjC, there is usually no "const ObjectPointer" type,
4522         // so don't check if the pointee type is constant.
4523         isConstant = T.isConstant(S.Context);
4524       }
4525 
4526       if (isConstant) {
4527         if (const Expr *Init = VD->getAnyInitializer()) {
4528           // Look through initializers like const char c[] = { "foo" }
4529           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4530             if (InitList->isStringLiteralInit())
4531               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4532           }
4533           return checkFormatStringExpr(S, Init, Args,
4534                                        HasVAListArg, format_idx,
4535                                        firstDataArg, Type, CallType,
4536                                        /*InFunctionCall*/ false, CheckedVarArgs,
4537                                        UncoveredArg, Offset);
4538         }
4539       }
4540 
4541       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4542       // special check to see if the format string is a function parameter
4543       // of the function calling the printf function.  If the function
4544       // has an attribute indicating it is a printf-like function, then we
4545       // should suppress warnings concerning non-literals being used in a call
4546       // to a vprintf function.  For example:
4547       //
4548       // void
4549       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4550       //      va_list ap;
4551       //      va_start(ap, fmt);
4552       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4553       //      ...
4554       // }
4555       if (HasVAListArg) {
4556         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4557           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4558             int PVIndex = PV->getFunctionScopeIndex() + 1;
4559             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4560               // adjust for implicit parameter
4561               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4562                 if (MD->isInstance())
4563                   ++PVIndex;
4564               // We also check if the formats are compatible.
4565               // We can't pass a 'scanf' string to a 'printf' function.
4566               if (PVIndex == PVFormat->getFormatIdx() &&
4567                   Type == S.GetFormatStringType(PVFormat))
4568                 return SLCT_UncheckedLiteral;
4569             }
4570           }
4571         }
4572       }
4573     }
4574 
4575     return SLCT_NotALiteral;
4576   }
4577 
4578   case Stmt::CallExprClass:
4579   case Stmt::CXXMemberCallExprClass: {
4580     const CallExpr *CE = cast<CallExpr>(E);
4581     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4582       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4583         unsigned ArgIndex = FA->getFormatIdx();
4584         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4585           if (MD->isInstance())
4586             --ArgIndex;
4587         const Expr *Arg = CE->getArg(ArgIndex - 1);
4588 
4589         return checkFormatStringExpr(S, Arg, Args,
4590                                      HasVAListArg, format_idx, firstDataArg,
4591                                      Type, CallType, InFunctionCall,
4592                                      CheckedVarArgs, UncoveredArg, Offset);
4593       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4594         unsigned BuiltinID = FD->getBuiltinID();
4595         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4596             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4597           const Expr *Arg = CE->getArg(0);
4598           return checkFormatStringExpr(S, Arg, Args,
4599                                        HasVAListArg, format_idx,
4600                                        firstDataArg, Type, CallType,
4601                                        InFunctionCall, CheckedVarArgs,
4602                                        UncoveredArg, Offset);
4603         }
4604       }
4605     }
4606 
4607     return SLCT_NotALiteral;
4608   }
4609   case Stmt::ObjCMessageExprClass: {
4610     const auto *ME = cast<ObjCMessageExpr>(E);
4611     if (const auto *ND = ME->getMethodDecl()) {
4612       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4613         unsigned ArgIndex = FA->getFormatIdx();
4614         const Expr *Arg = ME->getArg(ArgIndex - 1);
4615         return checkFormatStringExpr(
4616             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4617             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4618       }
4619     }
4620 
4621     return SLCT_NotALiteral;
4622   }
4623   case Stmt::ObjCStringLiteralClass:
4624   case Stmt::StringLiteralClass: {
4625     const StringLiteral *StrE = nullptr;
4626 
4627     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4628       StrE = ObjCFExpr->getString();
4629     else
4630       StrE = cast<StringLiteral>(E);
4631 
4632     if (StrE) {
4633       if (Offset.isNegative() || Offset > StrE->getLength()) {
4634         // TODO: It would be better to have an explicit warning for out of
4635         // bounds literals.
4636         return SLCT_NotALiteral;
4637       }
4638       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4639       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4640                         firstDataArg, Type, InFunctionCall, CallType,
4641                         CheckedVarArgs, UncoveredArg);
4642       return SLCT_CheckedLiteral;
4643     }
4644 
4645     return SLCT_NotALiteral;
4646   }
4647   case Stmt::BinaryOperatorClass: {
4648     llvm::APSInt LResult;
4649     llvm::APSInt RResult;
4650 
4651     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4652 
4653     // A string literal + an int offset is still a string literal.
4654     if (BinOp->isAdditiveOp()) {
4655       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4656       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4657 
4658       if (LIsInt != RIsInt) {
4659         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4660 
4661         if (LIsInt) {
4662           if (BinOpKind == BO_Add) {
4663             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4664             E = BinOp->getRHS();
4665             goto tryAgain;
4666           }
4667         } else {
4668           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4669           E = BinOp->getLHS();
4670           goto tryAgain;
4671         }
4672       }
4673     }
4674 
4675     return SLCT_NotALiteral;
4676   }
4677   case Stmt::UnaryOperatorClass: {
4678     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4679     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4680     if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4681       llvm::APSInt IndexResult;
4682       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4683         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4684         E = ASE->getBase();
4685         goto tryAgain;
4686       }
4687     }
4688 
4689     return SLCT_NotALiteral;
4690   }
4691 
4692   default:
4693     return SLCT_NotALiteral;
4694   }
4695 }
4696 
4697 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4698   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4699       .Case("scanf", FST_Scanf)
4700       .Cases("printf", "printf0", FST_Printf)
4701       .Cases("NSString", "CFString", FST_NSString)
4702       .Case("strftime", FST_Strftime)
4703       .Case("strfmon", FST_Strfmon)
4704       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4705       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4706       .Case("os_trace", FST_OSLog)
4707       .Case("os_log", FST_OSLog)
4708       .Default(FST_Unknown);
4709 }
4710 
4711 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4712 /// functions) for correct use of format strings.
4713 /// Returns true if a format string has been fully checked.
4714 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4715                                 ArrayRef<const Expr *> Args,
4716                                 bool IsCXXMember,
4717                                 VariadicCallType CallType,
4718                                 SourceLocation Loc, SourceRange Range,
4719                                 llvm::SmallBitVector &CheckedVarArgs) {
4720   FormatStringInfo FSI;
4721   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4722     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4723                                 FSI.FirstDataArg, GetFormatStringType(Format),
4724                                 CallType, Loc, Range, CheckedVarArgs);
4725   return false;
4726 }
4727 
4728 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4729                                 bool HasVAListArg, unsigned format_idx,
4730                                 unsigned firstDataArg, FormatStringType Type,
4731                                 VariadicCallType CallType,
4732                                 SourceLocation Loc, SourceRange Range,
4733                                 llvm::SmallBitVector &CheckedVarArgs) {
4734   // CHECK: printf/scanf-like function is called with no format string.
4735   if (format_idx >= Args.size()) {
4736     Diag(Loc, diag::warn_missing_format_string) << Range;
4737     return false;
4738   }
4739 
4740   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4741 
4742   // CHECK: format string is not a string literal.
4743   //
4744   // Dynamically generated format strings are difficult to
4745   // automatically vet at compile time.  Requiring that format strings
4746   // are string literals: (1) permits the checking of format strings by
4747   // the compiler and thereby (2) can practically remove the source of
4748   // many format string exploits.
4749 
4750   // Format string can be either ObjC string (e.g. @"%d") or
4751   // C string (e.g. "%d")
4752   // ObjC string uses the same format specifiers as C string, so we can use
4753   // the same format string checking logic for both ObjC and C strings.
4754   UncoveredArgHandler UncoveredArg;
4755   StringLiteralCheckType CT =
4756       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4757                             format_idx, firstDataArg, Type, CallType,
4758                             /*IsFunctionCall*/ true, CheckedVarArgs,
4759                             UncoveredArg,
4760                             /*no string offset*/ llvm::APSInt(64, false) = 0);
4761 
4762   // Generate a diagnostic where an uncovered argument is detected.
4763   if (UncoveredArg.hasUncoveredArg()) {
4764     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4765     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4766     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4767   }
4768 
4769   if (CT != SLCT_NotALiteral)
4770     // Literal format string found, check done!
4771     return CT == SLCT_CheckedLiteral;
4772 
4773   // Strftime is particular as it always uses a single 'time' argument,
4774   // so it is safe to pass a non-literal string.
4775   if (Type == FST_Strftime)
4776     return false;
4777 
4778   // Do not emit diag when the string param is a macro expansion and the
4779   // format is either NSString or CFString. This is a hack to prevent
4780   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4781   // which are usually used in place of NS and CF string literals.
4782   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4783   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4784     return false;
4785 
4786   // If there are no arguments specified, warn with -Wformat-security, otherwise
4787   // warn only with -Wformat-nonliteral.
4788   if (Args.size() == firstDataArg) {
4789     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4790       << OrigFormatExpr->getSourceRange();
4791     switch (Type) {
4792     default:
4793       break;
4794     case FST_Kprintf:
4795     case FST_FreeBSDKPrintf:
4796     case FST_Printf:
4797       Diag(FormatLoc, diag::note_format_security_fixit)
4798         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4799       break;
4800     case FST_NSString:
4801       Diag(FormatLoc, diag::note_format_security_fixit)
4802         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
4803       break;
4804     }
4805   } else {
4806     Diag(FormatLoc, diag::warn_format_nonliteral)
4807       << OrigFormatExpr->getSourceRange();
4808   }
4809   return false;
4810 }
4811 
4812 namespace {
4813 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4814 protected:
4815   Sema &S;
4816   const FormatStringLiteral *FExpr;
4817   const Expr *OrigFormatExpr;
4818   const Sema::FormatStringType FSType;
4819   const unsigned FirstDataArg;
4820   const unsigned NumDataArgs;
4821   const char *Beg; // Start of format string.
4822   const bool HasVAListArg;
4823   ArrayRef<const Expr *> Args;
4824   unsigned FormatIdx;
4825   llvm::SmallBitVector CoveredArgs;
4826   bool usesPositionalArgs;
4827   bool atFirstArg;
4828   bool inFunctionCall;
4829   Sema::VariadicCallType CallType;
4830   llvm::SmallBitVector &CheckedVarArgs;
4831   UncoveredArgHandler &UncoveredArg;
4832 
4833 public:
4834   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
4835                      const Expr *origFormatExpr,
4836                      const Sema::FormatStringType type, unsigned firstDataArg,
4837                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
4838                      ArrayRef<const Expr *> Args, unsigned formatIdx,
4839                      bool inFunctionCall, Sema::VariadicCallType callType,
4840                      llvm::SmallBitVector &CheckedVarArgs,
4841                      UncoveredArgHandler &UncoveredArg)
4842       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4843         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4844         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4845         usesPositionalArgs(false), atFirstArg(true),
4846         inFunctionCall(inFunctionCall), CallType(callType),
4847         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4848     CoveredArgs.resize(numDataArgs);
4849     CoveredArgs.reset();
4850   }
4851 
4852   void DoneProcessing();
4853 
4854   void HandleIncompleteSpecifier(const char *startSpecifier,
4855                                  unsigned specifierLen) override;
4856 
4857   void HandleInvalidLengthModifier(
4858                            const analyze_format_string::FormatSpecifier &FS,
4859                            const analyze_format_string::ConversionSpecifier &CS,
4860                            const char *startSpecifier, unsigned specifierLen,
4861                            unsigned DiagID);
4862 
4863   void HandleNonStandardLengthModifier(
4864                     const analyze_format_string::FormatSpecifier &FS,
4865                     const char *startSpecifier, unsigned specifierLen);
4866 
4867   void HandleNonStandardConversionSpecifier(
4868                     const analyze_format_string::ConversionSpecifier &CS,
4869                     const char *startSpecifier, unsigned specifierLen);
4870 
4871   void HandlePosition(const char *startPos, unsigned posLen) override;
4872 
4873   void HandleInvalidPosition(const char *startSpecifier,
4874                              unsigned specifierLen,
4875                              analyze_format_string::PositionContext p) override;
4876 
4877   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
4878 
4879   void HandleNullChar(const char *nullCharacter) override;
4880 
4881   template <typename Range>
4882   static void
4883   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4884                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4885                        bool IsStringLocation, Range StringRange,
4886                        ArrayRef<FixItHint> Fixit = None);
4887 
4888 protected:
4889   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4890                                         const char *startSpec,
4891                                         unsigned specifierLen,
4892                                         const char *csStart, unsigned csLen);
4893 
4894   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4895                                          const char *startSpec,
4896                                          unsigned specifierLen);
4897 
4898   SourceRange getFormatStringRange();
4899   CharSourceRange getSpecifierRange(const char *startSpecifier,
4900                                     unsigned specifierLen);
4901   SourceLocation getLocationOfByte(const char *x);
4902 
4903   const Expr *getDataArg(unsigned i) const;
4904 
4905   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4906                     const analyze_format_string::ConversionSpecifier &CS,
4907                     const char *startSpecifier, unsigned specifierLen,
4908                     unsigned argIndex);
4909 
4910   template <typename Range>
4911   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4912                             bool IsStringLocation, Range StringRange,
4913                             ArrayRef<FixItHint> Fixit = None);
4914 };
4915 } // end anonymous namespace
4916 
4917 SourceRange CheckFormatHandler::getFormatStringRange() {
4918   return OrigFormatExpr->getSourceRange();
4919 }
4920 
4921 CharSourceRange CheckFormatHandler::
4922 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
4923   SourceLocation Start = getLocationOfByte(startSpecifier);
4924   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
4925 
4926   // Advance the end SourceLocation by one due to half-open ranges.
4927   End = End.getLocWithOffset(1);
4928 
4929   return CharSourceRange::getCharRange(Start, End);
4930 }
4931 
4932 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
4933   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4934                                   S.getLangOpts(), S.Context.getTargetInfo());
4935 }
4936 
4937 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4938                                                    unsigned specifierLen){
4939   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4940                        getLocationOfByte(startSpecifier),
4941                        /*IsStringLocation*/true,
4942                        getSpecifierRange(startSpecifier, specifierLen));
4943 }
4944 
4945 void CheckFormatHandler::HandleInvalidLengthModifier(
4946     const analyze_format_string::FormatSpecifier &FS,
4947     const analyze_format_string::ConversionSpecifier &CS,
4948     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
4949   using namespace analyze_format_string;
4950 
4951   const LengthModifier &LM = FS.getLengthModifier();
4952   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4953 
4954   // See if we know how to fix this length modifier.
4955   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4956   if (FixedLM) {
4957     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4958                          getLocationOfByte(LM.getStart()),
4959                          /*IsStringLocation*/true,
4960                          getSpecifierRange(startSpecifier, specifierLen));
4961 
4962     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4963       << FixedLM->toString()
4964       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4965 
4966   } else {
4967     FixItHint Hint;
4968     if (DiagID == diag::warn_format_nonsensical_length)
4969       Hint = FixItHint::CreateRemoval(LMRange);
4970 
4971     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4972                          getLocationOfByte(LM.getStart()),
4973                          /*IsStringLocation*/true,
4974                          getSpecifierRange(startSpecifier, specifierLen),
4975                          Hint);
4976   }
4977 }
4978 
4979 void CheckFormatHandler::HandleNonStandardLengthModifier(
4980     const analyze_format_string::FormatSpecifier &FS,
4981     const char *startSpecifier, unsigned specifierLen) {
4982   using namespace analyze_format_string;
4983 
4984   const LengthModifier &LM = FS.getLengthModifier();
4985   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4986 
4987   // See if we know how to fix this length modifier.
4988   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4989   if (FixedLM) {
4990     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4991                            << LM.toString() << 0,
4992                          getLocationOfByte(LM.getStart()),
4993                          /*IsStringLocation*/true,
4994                          getSpecifierRange(startSpecifier, specifierLen));
4995 
4996     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4997       << FixedLM->toString()
4998       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4999 
5000   } else {
5001     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5002                            << LM.toString() << 0,
5003                          getLocationOfByte(LM.getStart()),
5004                          /*IsStringLocation*/true,
5005                          getSpecifierRange(startSpecifier, specifierLen));
5006   }
5007 }
5008 
5009 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5010     const analyze_format_string::ConversionSpecifier &CS,
5011     const char *startSpecifier, unsigned specifierLen) {
5012   using namespace analyze_format_string;
5013 
5014   // See if we know how to fix this conversion specifier.
5015   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5016   if (FixedCS) {
5017     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5018                           << CS.toString() << /*conversion specifier*/1,
5019                          getLocationOfByte(CS.getStart()),
5020                          /*IsStringLocation*/true,
5021                          getSpecifierRange(startSpecifier, specifierLen));
5022 
5023     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5024     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5025       << FixedCS->toString()
5026       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5027   } else {
5028     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5029                           << CS.toString() << /*conversion specifier*/1,
5030                          getLocationOfByte(CS.getStart()),
5031                          /*IsStringLocation*/true,
5032                          getSpecifierRange(startSpecifier, specifierLen));
5033   }
5034 }
5035 
5036 void CheckFormatHandler::HandlePosition(const char *startPos,
5037                                         unsigned posLen) {
5038   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5039                                getLocationOfByte(startPos),
5040                                /*IsStringLocation*/true,
5041                                getSpecifierRange(startPos, posLen));
5042 }
5043 
5044 void
5045 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5046                                      analyze_format_string::PositionContext p) {
5047   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5048                          << (unsigned) p,
5049                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5050                        getSpecifierRange(startPos, posLen));
5051 }
5052 
5053 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5054                                             unsigned posLen) {
5055   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5056                                getLocationOfByte(startPos),
5057                                /*IsStringLocation*/true,
5058                                getSpecifierRange(startPos, posLen));
5059 }
5060 
5061 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5062   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5063     // The presence of a null character is likely an error.
5064     EmitFormatDiagnostic(
5065       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5066       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5067       getFormatStringRange());
5068   }
5069 }
5070 
5071 // Note that this may return NULL if there was an error parsing or building
5072 // one of the argument expressions.
5073 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5074   return Args[FirstDataArg + i];
5075 }
5076 
5077 void CheckFormatHandler::DoneProcessing() {
5078   // Does the number of data arguments exceed the number of
5079   // format conversions in the format string?
5080   if (!HasVAListArg) {
5081       // Find any arguments that weren't covered.
5082     CoveredArgs.flip();
5083     signed notCoveredArg = CoveredArgs.find_first();
5084     if (notCoveredArg >= 0) {
5085       assert((unsigned)notCoveredArg < NumDataArgs);
5086       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5087     } else {
5088       UncoveredArg.setAllCovered();
5089     }
5090   }
5091 }
5092 
5093 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5094                                    const Expr *ArgExpr) {
5095   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5096          "Invalid state");
5097 
5098   if (!ArgExpr)
5099     return;
5100 
5101   SourceLocation Loc = ArgExpr->getLocStart();
5102 
5103   if (S.getSourceManager().isInSystemMacro(Loc))
5104     return;
5105 
5106   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5107   for (auto E : DiagnosticExprs)
5108     PDiag << E->getSourceRange();
5109 
5110   CheckFormatHandler::EmitFormatDiagnostic(
5111                                   S, IsFunctionCall, DiagnosticExprs[0],
5112                                   PDiag, Loc, /*IsStringLocation*/false,
5113                                   DiagnosticExprs[0]->getSourceRange());
5114 }
5115 
5116 bool
5117 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5118                                                      SourceLocation Loc,
5119                                                      const char *startSpec,
5120                                                      unsigned specifierLen,
5121                                                      const char *csStart,
5122                                                      unsigned csLen) {
5123   bool keepGoing = true;
5124   if (argIndex < NumDataArgs) {
5125     // Consider the argument coverered, even though the specifier doesn't
5126     // make sense.
5127     CoveredArgs.set(argIndex);
5128   }
5129   else {
5130     // If argIndex exceeds the number of data arguments we
5131     // don't issue a warning because that is just a cascade of warnings (and
5132     // they may have intended '%%' anyway). We don't want to continue processing
5133     // the format string after this point, however, as we will like just get
5134     // gibberish when trying to match arguments.
5135     keepGoing = false;
5136   }
5137 
5138   StringRef Specifier(csStart, csLen);
5139 
5140   // If the specifier in non-printable, it could be the first byte of a UTF-8
5141   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5142   // hex value.
5143   std::string CodePointStr;
5144   if (!llvm::sys::locale::isPrint(*csStart)) {
5145     llvm::UTF32 CodePoint;
5146     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5147     const llvm::UTF8 *E =
5148         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5149     llvm::ConversionResult Result =
5150         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5151 
5152     if (Result != llvm::conversionOK) {
5153       unsigned char FirstChar = *csStart;
5154       CodePoint = (llvm::UTF32)FirstChar;
5155     }
5156 
5157     llvm::raw_string_ostream OS(CodePointStr);
5158     if (CodePoint < 256)
5159       OS << "\\x" << llvm::format("%02x", CodePoint);
5160     else if (CodePoint <= 0xFFFF)
5161       OS << "\\u" << llvm::format("%04x", CodePoint);
5162     else
5163       OS << "\\U" << llvm::format("%08x", CodePoint);
5164     OS.flush();
5165     Specifier = CodePointStr;
5166   }
5167 
5168   EmitFormatDiagnostic(
5169       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5170       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5171 
5172   return keepGoing;
5173 }
5174 
5175 void
5176 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5177                                                       const char *startSpec,
5178                                                       unsigned specifierLen) {
5179   EmitFormatDiagnostic(
5180     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5181     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5182 }
5183 
5184 bool
5185 CheckFormatHandler::CheckNumArgs(
5186   const analyze_format_string::FormatSpecifier &FS,
5187   const analyze_format_string::ConversionSpecifier &CS,
5188   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5189 
5190   if (argIndex >= NumDataArgs) {
5191     PartialDiagnostic PDiag = FS.usesPositionalArg()
5192       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5193            << (argIndex+1) << NumDataArgs)
5194       : S.PDiag(diag::warn_printf_insufficient_data_args);
5195     EmitFormatDiagnostic(
5196       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5197       getSpecifierRange(startSpecifier, specifierLen));
5198 
5199     // Since more arguments than conversion tokens are given, by extension
5200     // all arguments are covered, so mark this as so.
5201     UncoveredArg.setAllCovered();
5202     return false;
5203   }
5204   return true;
5205 }
5206 
5207 template<typename Range>
5208 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5209                                               SourceLocation Loc,
5210                                               bool IsStringLocation,
5211                                               Range StringRange,
5212                                               ArrayRef<FixItHint> FixIt) {
5213   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5214                        Loc, IsStringLocation, StringRange, FixIt);
5215 }
5216 
5217 /// \brief If the format string is not within the funcion call, emit a note
5218 /// so that the function call and string are in diagnostic messages.
5219 ///
5220 /// \param InFunctionCall if true, the format string is within the function
5221 /// call and only one diagnostic message will be produced.  Otherwise, an
5222 /// extra note will be emitted pointing to location of the format string.
5223 ///
5224 /// \param ArgumentExpr the expression that is passed as the format string
5225 /// argument in the function call.  Used for getting locations when two
5226 /// diagnostics are emitted.
5227 ///
5228 /// \param PDiag the callee should already have provided any strings for the
5229 /// diagnostic message.  This function only adds locations and fixits
5230 /// to diagnostics.
5231 ///
5232 /// \param Loc primary location for diagnostic.  If two diagnostics are
5233 /// required, one will be at Loc and a new SourceLocation will be created for
5234 /// the other one.
5235 ///
5236 /// \param IsStringLocation if true, Loc points to the format string should be
5237 /// used for the note.  Otherwise, Loc points to the argument list and will
5238 /// be used with PDiag.
5239 ///
5240 /// \param StringRange some or all of the string to highlight.  This is
5241 /// templated so it can accept either a CharSourceRange or a SourceRange.
5242 ///
5243 /// \param FixIt optional fix it hint for the format string.
5244 template <typename Range>
5245 void CheckFormatHandler::EmitFormatDiagnostic(
5246     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5247     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5248     Range StringRange, ArrayRef<FixItHint> FixIt) {
5249   if (InFunctionCall) {
5250     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5251     D << StringRange;
5252     D << FixIt;
5253   } else {
5254     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5255       << ArgumentExpr->getSourceRange();
5256 
5257     const Sema::SemaDiagnosticBuilder &Note =
5258       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5259              diag::note_format_string_defined);
5260 
5261     Note << StringRange;
5262     Note << FixIt;
5263   }
5264 }
5265 
5266 //===--- CHECK: Printf format string checking ------------------------------===//
5267 
5268 namespace {
5269 class CheckPrintfHandler : public CheckFormatHandler {
5270 public:
5271   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5272                      const Expr *origFormatExpr,
5273                      const Sema::FormatStringType type, unsigned firstDataArg,
5274                      unsigned numDataArgs, bool isObjC, const char *beg,
5275                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5276                      unsigned formatIdx, bool inFunctionCall,
5277                      Sema::VariadicCallType CallType,
5278                      llvm::SmallBitVector &CheckedVarArgs,
5279                      UncoveredArgHandler &UncoveredArg)
5280       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5281                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5282                            inFunctionCall, CallType, CheckedVarArgs,
5283                            UncoveredArg) {}
5284 
5285   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5286 
5287   /// Returns true if '%@' specifiers are allowed in the format string.
5288   bool allowsObjCArg() const {
5289     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5290            FSType == Sema::FST_OSTrace;
5291   }
5292 
5293   bool HandleInvalidPrintfConversionSpecifier(
5294                                       const analyze_printf::PrintfSpecifier &FS,
5295                                       const char *startSpecifier,
5296                                       unsigned specifierLen) override;
5297 
5298   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5299                              const char *startSpecifier,
5300                              unsigned specifierLen) override;
5301   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5302                        const char *StartSpecifier,
5303                        unsigned SpecifierLen,
5304                        const Expr *E);
5305 
5306   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5307                     const char *startSpecifier, unsigned specifierLen);
5308   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5309                            const analyze_printf::OptionalAmount &Amt,
5310                            unsigned type,
5311                            const char *startSpecifier, unsigned specifierLen);
5312   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5313                   const analyze_printf::OptionalFlag &flag,
5314                   const char *startSpecifier, unsigned specifierLen);
5315   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5316                          const analyze_printf::OptionalFlag &ignoredFlag,
5317                          const analyze_printf::OptionalFlag &flag,
5318                          const char *startSpecifier, unsigned specifierLen);
5319   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5320                            const Expr *E);
5321 
5322   void HandleEmptyObjCModifierFlag(const char *startFlag,
5323                                    unsigned flagLen) override;
5324 
5325   void HandleInvalidObjCModifierFlag(const char *startFlag,
5326                                             unsigned flagLen) override;
5327 
5328   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5329                                            const char *flagsEnd,
5330                                            const char *conversionPosition)
5331                                              override;
5332 };
5333 } // end anonymous namespace
5334 
5335 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5336                                       const analyze_printf::PrintfSpecifier &FS,
5337                                       const char *startSpecifier,
5338                                       unsigned specifierLen) {
5339   const analyze_printf::PrintfConversionSpecifier &CS =
5340     FS.getConversionSpecifier();
5341 
5342   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5343                                           getLocationOfByte(CS.getStart()),
5344                                           startSpecifier, specifierLen,
5345                                           CS.getStart(), CS.getLength());
5346 }
5347 
5348 bool CheckPrintfHandler::HandleAmount(
5349                                const analyze_format_string::OptionalAmount &Amt,
5350                                unsigned k, const char *startSpecifier,
5351                                unsigned specifierLen) {
5352   if (Amt.hasDataArgument()) {
5353     if (!HasVAListArg) {
5354       unsigned argIndex = Amt.getArgIndex();
5355       if (argIndex >= NumDataArgs) {
5356         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5357                                << k,
5358                              getLocationOfByte(Amt.getStart()),
5359                              /*IsStringLocation*/true,
5360                              getSpecifierRange(startSpecifier, specifierLen));
5361         // Don't do any more checking.  We will just emit
5362         // spurious errors.
5363         return false;
5364       }
5365 
5366       // Type check the data argument.  It should be an 'int'.
5367       // Although not in conformance with C99, we also allow the argument to be
5368       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5369       // doesn't emit a warning for that case.
5370       CoveredArgs.set(argIndex);
5371       const Expr *Arg = getDataArg(argIndex);
5372       if (!Arg)
5373         return false;
5374 
5375       QualType T = Arg->getType();
5376 
5377       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5378       assert(AT.isValid());
5379 
5380       if (!AT.matchesType(S.Context, T)) {
5381         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5382                                << k << AT.getRepresentativeTypeName(S.Context)
5383                                << T << Arg->getSourceRange(),
5384                              getLocationOfByte(Amt.getStart()),
5385                              /*IsStringLocation*/true,
5386                              getSpecifierRange(startSpecifier, specifierLen));
5387         // Don't do any more checking.  We will just emit
5388         // spurious errors.
5389         return false;
5390       }
5391     }
5392   }
5393   return true;
5394 }
5395 
5396 void CheckPrintfHandler::HandleInvalidAmount(
5397                                       const analyze_printf::PrintfSpecifier &FS,
5398                                       const analyze_printf::OptionalAmount &Amt,
5399                                       unsigned type,
5400                                       const char *startSpecifier,
5401                                       unsigned specifierLen) {
5402   const analyze_printf::PrintfConversionSpecifier &CS =
5403     FS.getConversionSpecifier();
5404 
5405   FixItHint fixit =
5406     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5407       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5408                                  Amt.getConstantLength()))
5409       : FixItHint();
5410 
5411   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5412                          << type << CS.toString(),
5413                        getLocationOfByte(Amt.getStart()),
5414                        /*IsStringLocation*/true,
5415                        getSpecifierRange(startSpecifier, specifierLen),
5416                        fixit);
5417 }
5418 
5419 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5420                                     const analyze_printf::OptionalFlag &flag,
5421                                     const char *startSpecifier,
5422                                     unsigned specifierLen) {
5423   // Warn about pointless flag with a fixit removal.
5424   const analyze_printf::PrintfConversionSpecifier &CS =
5425     FS.getConversionSpecifier();
5426   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5427                          << flag.toString() << CS.toString(),
5428                        getLocationOfByte(flag.getPosition()),
5429                        /*IsStringLocation*/true,
5430                        getSpecifierRange(startSpecifier, specifierLen),
5431                        FixItHint::CreateRemoval(
5432                          getSpecifierRange(flag.getPosition(), 1)));
5433 }
5434 
5435 void CheckPrintfHandler::HandleIgnoredFlag(
5436                                 const analyze_printf::PrintfSpecifier &FS,
5437                                 const analyze_printf::OptionalFlag &ignoredFlag,
5438                                 const analyze_printf::OptionalFlag &flag,
5439                                 const char *startSpecifier,
5440                                 unsigned specifierLen) {
5441   // Warn about ignored flag with a fixit removal.
5442   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5443                          << ignoredFlag.toString() << flag.toString(),
5444                        getLocationOfByte(ignoredFlag.getPosition()),
5445                        /*IsStringLocation*/true,
5446                        getSpecifierRange(startSpecifier, specifierLen),
5447                        FixItHint::CreateRemoval(
5448                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5449 }
5450 
5451 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5452 //                            bool IsStringLocation, Range StringRange,
5453 //                            ArrayRef<FixItHint> Fixit = None);
5454 
5455 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5456                                                      unsigned flagLen) {
5457   // Warn about an empty flag.
5458   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5459                        getLocationOfByte(startFlag),
5460                        /*IsStringLocation*/true,
5461                        getSpecifierRange(startFlag, flagLen));
5462 }
5463 
5464 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5465                                                        unsigned flagLen) {
5466   // Warn about an invalid flag.
5467   auto Range = getSpecifierRange(startFlag, flagLen);
5468   StringRef flag(startFlag, flagLen);
5469   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5470                       getLocationOfByte(startFlag),
5471                       /*IsStringLocation*/true,
5472                       Range, FixItHint::CreateRemoval(Range));
5473 }
5474 
5475 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5476     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5477     // Warn about using '[...]' without a '@' conversion.
5478     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5479     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5480     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5481                          getLocationOfByte(conversionPosition),
5482                          /*IsStringLocation*/true,
5483                          Range, FixItHint::CreateRemoval(Range));
5484 }
5485 
5486 // Determines if the specified is a C++ class or struct containing
5487 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5488 // "c_str()").
5489 template<typename MemberKind>
5490 static llvm::SmallPtrSet<MemberKind*, 1>
5491 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5492   const RecordType *RT = Ty->getAs<RecordType>();
5493   llvm::SmallPtrSet<MemberKind*, 1> Results;
5494 
5495   if (!RT)
5496     return Results;
5497   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5498   if (!RD || !RD->getDefinition())
5499     return Results;
5500 
5501   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5502                  Sema::LookupMemberName);
5503   R.suppressDiagnostics();
5504 
5505   // We just need to include all members of the right kind turned up by the
5506   // filter, at this point.
5507   if (S.LookupQualifiedName(R, RT->getDecl()))
5508     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5509       NamedDecl *decl = (*I)->getUnderlyingDecl();
5510       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5511         Results.insert(FK);
5512     }
5513   return Results;
5514 }
5515 
5516 /// Check if we could call '.c_str()' on an object.
5517 ///
5518 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5519 /// allow the call, or if it would be ambiguous).
5520 bool Sema::hasCStrMethod(const Expr *E) {
5521   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5522   MethodSet Results =
5523       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5524   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5525        MI != ME; ++MI)
5526     if ((*MI)->getMinRequiredArguments() == 0)
5527       return true;
5528   return false;
5529 }
5530 
5531 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5532 // better diagnostic if so. AT is assumed to be valid.
5533 // Returns true when a c_str() conversion method is found.
5534 bool CheckPrintfHandler::checkForCStrMembers(
5535     const analyze_printf::ArgType &AT, const Expr *E) {
5536   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5537 
5538   MethodSet Results =
5539       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5540 
5541   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5542        MI != ME; ++MI) {
5543     const CXXMethodDecl *Method = *MI;
5544     if (Method->getMinRequiredArguments() == 0 &&
5545         AT.matchesType(S.Context, Method->getReturnType())) {
5546       // FIXME: Suggest parens if the expression needs them.
5547       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5548       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5549           << "c_str()"
5550           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5551       return true;
5552     }
5553   }
5554 
5555   return false;
5556 }
5557 
5558 bool
5559 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5560                                             &FS,
5561                                           const char *startSpecifier,
5562                                           unsigned specifierLen) {
5563   using namespace analyze_format_string;
5564   using namespace analyze_printf;
5565   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5566 
5567   if (FS.consumesDataArgument()) {
5568     if (atFirstArg) {
5569         atFirstArg = false;
5570         usesPositionalArgs = FS.usesPositionalArg();
5571     }
5572     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5573       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5574                                         startSpecifier, specifierLen);
5575       return false;
5576     }
5577   }
5578 
5579   // First check if the field width, precision, and conversion specifier
5580   // have matching data arguments.
5581   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5582                     startSpecifier, specifierLen)) {
5583     return false;
5584   }
5585 
5586   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5587                     startSpecifier, specifierLen)) {
5588     return false;
5589   }
5590 
5591   if (!CS.consumesDataArgument()) {
5592     // FIXME: Technically specifying a precision or field width here
5593     // makes no sense.  Worth issuing a warning at some point.
5594     return true;
5595   }
5596 
5597   // Consume the argument.
5598   unsigned argIndex = FS.getArgIndex();
5599   if (argIndex < NumDataArgs) {
5600     // The check to see if the argIndex is valid will come later.
5601     // We set the bit here because we may exit early from this
5602     // function if we encounter some other error.
5603     CoveredArgs.set(argIndex);
5604   }
5605 
5606   // FreeBSD kernel extensions.
5607   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5608       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5609     // We need at least two arguments.
5610     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5611       return false;
5612 
5613     // Claim the second argument.
5614     CoveredArgs.set(argIndex + 1);
5615 
5616     // Type check the first argument (int for %b, pointer for %D)
5617     const Expr *Ex = getDataArg(argIndex);
5618     const analyze_printf::ArgType &AT =
5619       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5620         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5621     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5622       EmitFormatDiagnostic(
5623         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5624         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5625         << false << Ex->getSourceRange(),
5626         Ex->getLocStart(), /*IsStringLocation*/false,
5627         getSpecifierRange(startSpecifier, specifierLen));
5628 
5629     // Type check the second argument (char * for both %b and %D)
5630     Ex = getDataArg(argIndex + 1);
5631     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5632     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5633       EmitFormatDiagnostic(
5634         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5635         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5636         << false << Ex->getSourceRange(),
5637         Ex->getLocStart(), /*IsStringLocation*/false,
5638         getSpecifierRange(startSpecifier, specifierLen));
5639 
5640      return true;
5641   }
5642 
5643   // Check for using an Objective-C specific conversion specifier
5644   // in a non-ObjC literal.
5645   if (!allowsObjCArg() && CS.isObjCArg()) {
5646     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5647                                                   specifierLen);
5648   }
5649 
5650   // %P can only be used with os_log.
5651   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5652     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5653                                                   specifierLen);
5654   }
5655 
5656   // %n is not allowed with os_log.
5657   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5658     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5659                          getLocationOfByte(CS.getStart()),
5660                          /*IsStringLocation*/ false,
5661                          getSpecifierRange(startSpecifier, specifierLen));
5662 
5663     return true;
5664   }
5665 
5666   // Only scalars are allowed for os_trace.
5667   if (FSType == Sema::FST_OSTrace &&
5668       (CS.getKind() == ConversionSpecifier::PArg ||
5669        CS.getKind() == ConversionSpecifier::sArg ||
5670        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5671     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5672                                                   specifierLen);
5673   }
5674 
5675   // Check for use of public/private annotation outside of os_log().
5676   if (FSType != Sema::FST_OSLog) {
5677     if (FS.isPublic().isSet()) {
5678       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5679                                << "public",
5680                            getLocationOfByte(FS.isPublic().getPosition()),
5681                            /*IsStringLocation*/ false,
5682                            getSpecifierRange(startSpecifier, specifierLen));
5683     }
5684     if (FS.isPrivate().isSet()) {
5685       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5686                                << "private",
5687                            getLocationOfByte(FS.isPrivate().getPosition()),
5688                            /*IsStringLocation*/ false,
5689                            getSpecifierRange(startSpecifier, specifierLen));
5690     }
5691   }
5692 
5693   // Check for invalid use of field width
5694   if (!FS.hasValidFieldWidth()) {
5695     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5696         startSpecifier, specifierLen);
5697   }
5698 
5699   // Check for invalid use of precision
5700   if (!FS.hasValidPrecision()) {
5701     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5702         startSpecifier, specifierLen);
5703   }
5704 
5705   // Precision is mandatory for %P specifier.
5706   if (CS.getKind() == ConversionSpecifier::PArg &&
5707       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5708     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5709                          getLocationOfByte(startSpecifier),
5710                          /*IsStringLocation*/ false,
5711                          getSpecifierRange(startSpecifier, specifierLen));
5712   }
5713 
5714   // Check each flag does not conflict with any other component.
5715   if (!FS.hasValidThousandsGroupingPrefix())
5716     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5717   if (!FS.hasValidLeadingZeros())
5718     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5719   if (!FS.hasValidPlusPrefix())
5720     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5721   if (!FS.hasValidSpacePrefix())
5722     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5723   if (!FS.hasValidAlternativeForm())
5724     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5725   if (!FS.hasValidLeftJustified())
5726     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5727 
5728   // Check that flags are not ignored by another flag
5729   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5730     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5731         startSpecifier, specifierLen);
5732   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5733     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5734             startSpecifier, specifierLen);
5735 
5736   // Check the length modifier is valid with the given conversion specifier.
5737   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5738     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5739                                 diag::warn_format_nonsensical_length);
5740   else if (!FS.hasStandardLengthModifier())
5741     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5742   else if (!FS.hasStandardLengthConversionCombination())
5743     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5744                                 diag::warn_format_non_standard_conversion_spec);
5745 
5746   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5747     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5748 
5749   // The remaining checks depend on the data arguments.
5750   if (HasVAListArg)
5751     return true;
5752 
5753   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5754     return false;
5755 
5756   const Expr *Arg = getDataArg(argIndex);
5757   if (!Arg)
5758     return true;
5759 
5760   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5761 }
5762 
5763 static bool requiresParensToAddCast(const Expr *E) {
5764   // FIXME: We should have a general way to reason about operator
5765   // precedence and whether parens are actually needed here.
5766   // Take care of a few common cases where they aren't.
5767   const Expr *Inside = E->IgnoreImpCasts();
5768   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5769     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5770 
5771   switch (Inside->getStmtClass()) {
5772   case Stmt::ArraySubscriptExprClass:
5773   case Stmt::CallExprClass:
5774   case Stmt::CharacterLiteralClass:
5775   case Stmt::CXXBoolLiteralExprClass:
5776   case Stmt::DeclRefExprClass:
5777   case Stmt::FloatingLiteralClass:
5778   case Stmt::IntegerLiteralClass:
5779   case Stmt::MemberExprClass:
5780   case Stmt::ObjCArrayLiteralClass:
5781   case Stmt::ObjCBoolLiteralExprClass:
5782   case Stmt::ObjCBoxedExprClass:
5783   case Stmt::ObjCDictionaryLiteralClass:
5784   case Stmt::ObjCEncodeExprClass:
5785   case Stmt::ObjCIvarRefExprClass:
5786   case Stmt::ObjCMessageExprClass:
5787   case Stmt::ObjCPropertyRefExprClass:
5788   case Stmt::ObjCStringLiteralClass:
5789   case Stmt::ObjCSubscriptRefExprClass:
5790   case Stmt::ParenExprClass:
5791   case Stmt::StringLiteralClass:
5792   case Stmt::UnaryOperatorClass:
5793     return false;
5794   default:
5795     return true;
5796   }
5797 }
5798 
5799 static std::pair<QualType, StringRef>
5800 shouldNotPrintDirectly(const ASTContext &Context,
5801                        QualType IntendedTy,
5802                        const Expr *E) {
5803   // Use a 'while' to peel off layers of typedefs.
5804   QualType TyTy = IntendedTy;
5805   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5806     StringRef Name = UserTy->getDecl()->getName();
5807     QualType CastTy = llvm::StringSwitch<QualType>(Name)
5808       .Case("NSInteger", Context.LongTy)
5809       .Case("NSUInteger", Context.UnsignedLongTy)
5810       .Case("SInt32", Context.IntTy)
5811       .Case("UInt32", Context.UnsignedIntTy)
5812       .Default(QualType());
5813 
5814     if (!CastTy.isNull())
5815       return std::make_pair(CastTy, Name);
5816 
5817     TyTy = UserTy->desugar();
5818   }
5819 
5820   // Strip parens if necessary.
5821   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5822     return shouldNotPrintDirectly(Context,
5823                                   PE->getSubExpr()->getType(),
5824                                   PE->getSubExpr());
5825 
5826   // If this is a conditional expression, then its result type is constructed
5827   // via usual arithmetic conversions and thus there might be no necessary
5828   // typedef sugar there.  Recurse to operands to check for NSInteger &
5829   // Co. usage condition.
5830   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5831     QualType TrueTy, FalseTy;
5832     StringRef TrueName, FalseName;
5833 
5834     std::tie(TrueTy, TrueName) =
5835       shouldNotPrintDirectly(Context,
5836                              CO->getTrueExpr()->getType(),
5837                              CO->getTrueExpr());
5838     std::tie(FalseTy, FalseName) =
5839       shouldNotPrintDirectly(Context,
5840                              CO->getFalseExpr()->getType(),
5841                              CO->getFalseExpr());
5842 
5843     if (TrueTy == FalseTy)
5844       return std::make_pair(TrueTy, TrueName);
5845     else if (TrueTy.isNull())
5846       return std::make_pair(FalseTy, FalseName);
5847     else if (FalseTy.isNull())
5848       return std::make_pair(TrueTy, TrueName);
5849   }
5850 
5851   return std::make_pair(QualType(), StringRef());
5852 }
5853 
5854 bool
5855 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5856                                     const char *StartSpecifier,
5857                                     unsigned SpecifierLen,
5858                                     const Expr *E) {
5859   using namespace analyze_format_string;
5860   using namespace analyze_printf;
5861   // Now type check the data expression that matches the
5862   // format specifier.
5863   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
5864   if (!AT.isValid())
5865     return true;
5866 
5867   QualType ExprTy = E->getType();
5868   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5869     ExprTy = TET->getUnderlyingExpr()->getType();
5870   }
5871 
5872   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5873 
5874   if (match == analyze_printf::ArgType::Match) {
5875     return true;
5876   }
5877 
5878   // Look through argument promotions for our error message's reported type.
5879   // This includes the integral and floating promotions, but excludes array
5880   // and function pointer decay; seeing that an argument intended to be a
5881   // string has type 'char [6]' is probably more confusing than 'char *'.
5882   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5883     if (ICE->getCastKind() == CK_IntegralCast ||
5884         ICE->getCastKind() == CK_FloatingCast) {
5885       E = ICE->getSubExpr();
5886       ExprTy = E->getType();
5887 
5888       // Check if we didn't match because of an implicit cast from a 'char'
5889       // or 'short' to an 'int'.  This is done because printf is a varargs
5890       // function.
5891       if (ICE->getType() == S.Context.IntTy ||
5892           ICE->getType() == S.Context.UnsignedIntTy) {
5893         // All further checking is done on the subexpression.
5894         if (AT.matchesType(S.Context, ExprTy))
5895           return true;
5896       }
5897     }
5898   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5899     // Special case for 'a', which has type 'int' in C.
5900     // Note, however, that we do /not/ want to treat multibyte constants like
5901     // 'MooV' as characters! This form is deprecated but still exists.
5902     if (ExprTy == S.Context.IntTy)
5903       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5904         ExprTy = S.Context.CharTy;
5905   }
5906 
5907   // Look through enums to their underlying type.
5908   bool IsEnum = false;
5909   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5910     ExprTy = EnumTy->getDecl()->getIntegerType();
5911     IsEnum = true;
5912   }
5913 
5914   // %C in an Objective-C context prints a unichar, not a wchar_t.
5915   // If the argument is an integer of some kind, believe the %C and suggest
5916   // a cast instead of changing the conversion specifier.
5917   QualType IntendedTy = ExprTy;
5918   if (isObjCContext() &&
5919       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5920     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5921         !ExprTy->isCharType()) {
5922       // 'unichar' is defined as a typedef of unsigned short, but we should
5923       // prefer using the typedef if it is visible.
5924       IntendedTy = S.Context.UnsignedShortTy;
5925 
5926       // While we are here, check if the value is an IntegerLiteral that happens
5927       // to be within the valid range.
5928       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5929         const llvm::APInt &V = IL->getValue();
5930         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5931           return true;
5932       }
5933 
5934       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5935                           Sema::LookupOrdinaryName);
5936       if (S.LookupName(Result, S.getCurScope())) {
5937         NamedDecl *ND = Result.getFoundDecl();
5938         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5939           if (TD->getUnderlyingType() == IntendedTy)
5940             IntendedTy = S.Context.getTypedefType(TD);
5941       }
5942     }
5943   }
5944 
5945   // Special-case some of Darwin's platform-independence types by suggesting
5946   // casts to primitive types that are known to be large enough.
5947   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
5948   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5949     QualType CastTy;
5950     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5951     if (!CastTy.isNull()) {
5952       IntendedTy = CastTy;
5953       ShouldNotPrintDirectly = true;
5954     }
5955   }
5956 
5957   // We may be able to offer a FixItHint if it is a supported type.
5958   PrintfSpecifier fixedFS = FS;
5959   bool success =
5960       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
5961 
5962   if (success) {
5963     // Get the fix string from the fixed format specifier
5964     SmallString<16> buf;
5965     llvm::raw_svector_ostream os(buf);
5966     fixedFS.toString(os);
5967 
5968     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5969 
5970     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5971       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5972       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5973         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5974       }
5975       // In this case, the specifier is wrong and should be changed to match
5976       // the argument.
5977       EmitFormatDiagnostic(S.PDiag(diag)
5978                                << AT.getRepresentativeTypeName(S.Context)
5979                                << IntendedTy << IsEnum << E->getSourceRange(),
5980                            E->getLocStart(),
5981                            /*IsStringLocation*/ false, SpecRange,
5982                            FixItHint::CreateReplacement(SpecRange, os.str()));
5983     } else {
5984       // The canonical type for formatting this value is different from the
5985       // actual type of the expression. (This occurs, for example, with Darwin's
5986       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5987       // should be printed as 'long' for 64-bit compatibility.)
5988       // Rather than emitting a normal format/argument mismatch, we want to
5989       // add a cast to the recommended type (and correct the format string
5990       // if necessary).
5991       SmallString<16> CastBuf;
5992       llvm::raw_svector_ostream CastFix(CastBuf);
5993       CastFix << "(";
5994       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5995       CastFix << ")";
5996 
5997       SmallVector<FixItHint,4> Hints;
5998       if (!AT.matchesType(S.Context, IntendedTy))
5999         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6000 
6001       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6002         // If there's already a cast present, just replace it.
6003         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6004         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6005 
6006       } else if (!requiresParensToAddCast(E)) {
6007         // If the expression has high enough precedence,
6008         // just write the C-style cast.
6009         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6010                                                    CastFix.str()));
6011       } else {
6012         // Otherwise, add parens around the expression as well as the cast.
6013         CastFix << "(";
6014         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6015                                                    CastFix.str()));
6016 
6017         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6018         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6019       }
6020 
6021       if (ShouldNotPrintDirectly) {
6022         // The expression has a type that should not be printed directly.
6023         // We extract the name from the typedef because we don't want to show
6024         // the underlying type in the diagnostic.
6025         StringRef Name;
6026         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6027           Name = TypedefTy->getDecl()->getName();
6028         else
6029           Name = CastTyName;
6030         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6031                                << Name << IntendedTy << IsEnum
6032                                << E->getSourceRange(),
6033                              E->getLocStart(), /*IsStringLocation=*/false,
6034                              SpecRange, Hints);
6035       } else {
6036         // In this case, the expression could be printed using a different
6037         // specifier, but we've decided that the specifier is probably correct
6038         // and we should cast instead. Just use the normal warning message.
6039         EmitFormatDiagnostic(
6040           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6041             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6042             << E->getSourceRange(),
6043           E->getLocStart(), /*IsStringLocation*/false,
6044           SpecRange, Hints);
6045       }
6046     }
6047   } else {
6048     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6049                                                    SpecifierLen);
6050     // Since the warning for passing non-POD types to variadic functions
6051     // was deferred until now, we emit a warning for non-POD
6052     // arguments here.
6053     switch (S.isValidVarArgType(ExprTy)) {
6054     case Sema::VAK_Valid:
6055     case Sema::VAK_ValidInCXX11: {
6056       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6057       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6058         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6059       }
6060 
6061       EmitFormatDiagnostic(
6062           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6063                         << IsEnum << CSR << E->getSourceRange(),
6064           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6065       break;
6066     }
6067     case Sema::VAK_Undefined:
6068     case Sema::VAK_MSVCUndefined:
6069       EmitFormatDiagnostic(
6070         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6071           << S.getLangOpts().CPlusPlus11
6072           << ExprTy
6073           << CallType
6074           << AT.getRepresentativeTypeName(S.Context)
6075           << CSR
6076           << E->getSourceRange(),
6077         E->getLocStart(), /*IsStringLocation*/false, CSR);
6078       checkForCStrMembers(AT, E);
6079       break;
6080 
6081     case Sema::VAK_Invalid:
6082       if (ExprTy->isObjCObjectType())
6083         EmitFormatDiagnostic(
6084           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6085             << S.getLangOpts().CPlusPlus11
6086             << ExprTy
6087             << CallType
6088             << AT.getRepresentativeTypeName(S.Context)
6089             << CSR
6090             << E->getSourceRange(),
6091           E->getLocStart(), /*IsStringLocation*/false, CSR);
6092       else
6093         // FIXME: If this is an initializer list, suggest removing the braces
6094         // or inserting a cast to the target type.
6095         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6096           << isa<InitListExpr>(E) << ExprTy << CallType
6097           << AT.getRepresentativeTypeName(S.Context)
6098           << E->getSourceRange();
6099       break;
6100     }
6101 
6102     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6103            "format string specifier index out of range");
6104     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6105   }
6106 
6107   return true;
6108 }
6109 
6110 //===--- CHECK: Scanf format string checking ------------------------------===//
6111 
6112 namespace {
6113 class CheckScanfHandler : public CheckFormatHandler {
6114 public:
6115   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6116                     const Expr *origFormatExpr, Sema::FormatStringType type,
6117                     unsigned firstDataArg, unsigned numDataArgs,
6118                     const char *beg, bool hasVAListArg,
6119                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6120                     bool inFunctionCall, Sema::VariadicCallType CallType,
6121                     llvm::SmallBitVector &CheckedVarArgs,
6122                     UncoveredArgHandler &UncoveredArg)
6123       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6124                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6125                            inFunctionCall, CallType, CheckedVarArgs,
6126                            UncoveredArg) {}
6127 
6128   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6129                             const char *startSpecifier,
6130                             unsigned specifierLen) override;
6131 
6132   bool HandleInvalidScanfConversionSpecifier(
6133           const analyze_scanf::ScanfSpecifier &FS,
6134           const char *startSpecifier,
6135           unsigned specifierLen) override;
6136 
6137   void HandleIncompleteScanList(const char *start, const char *end) override;
6138 };
6139 } // end anonymous namespace
6140 
6141 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6142                                                  const char *end) {
6143   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6144                        getLocationOfByte(end), /*IsStringLocation*/true,
6145                        getSpecifierRange(start, end - start));
6146 }
6147 
6148 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6149                                         const analyze_scanf::ScanfSpecifier &FS,
6150                                         const char *startSpecifier,
6151                                         unsigned specifierLen) {
6152 
6153   const analyze_scanf::ScanfConversionSpecifier &CS =
6154     FS.getConversionSpecifier();
6155 
6156   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6157                                           getLocationOfByte(CS.getStart()),
6158                                           startSpecifier, specifierLen,
6159                                           CS.getStart(), CS.getLength());
6160 }
6161 
6162 bool CheckScanfHandler::HandleScanfSpecifier(
6163                                        const analyze_scanf::ScanfSpecifier &FS,
6164                                        const char *startSpecifier,
6165                                        unsigned specifierLen) {
6166   using namespace analyze_scanf;
6167   using namespace analyze_format_string;
6168 
6169   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6170 
6171   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6172   // be used to decide if we are using positional arguments consistently.
6173   if (FS.consumesDataArgument()) {
6174     if (atFirstArg) {
6175       atFirstArg = false;
6176       usesPositionalArgs = FS.usesPositionalArg();
6177     }
6178     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6179       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6180                                         startSpecifier, specifierLen);
6181       return false;
6182     }
6183   }
6184 
6185   // Check if the field with is non-zero.
6186   const OptionalAmount &Amt = FS.getFieldWidth();
6187   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6188     if (Amt.getConstantAmount() == 0) {
6189       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6190                                                    Amt.getConstantLength());
6191       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6192                            getLocationOfByte(Amt.getStart()),
6193                            /*IsStringLocation*/true, R,
6194                            FixItHint::CreateRemoval(R));
6195     }
6196   }
6197 
6198   if (!FS.consumesDataArgument()) {
6199     // FIXME: Technically specifying a precision or field width here
6200     // makes no sense.  Worth issuing a warning at some point.
6201     return true;
6202   }
6203 
6204   // Consume the argument.
6205   unsigned argIndex = FS.getArgIndex();
6206   if (argIndex < NumDataArgs) {
6207       // The check to see if the argIndex is valid will come later.
6208       // We set the bit here because we may exit early from this
6209       // function if we encounter some other error.
6210     CoveredArgs.set(argIndex);
6211   }
6212 
6213   // Check the length modifier is valid with the given conversion specifier.
6214   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6215     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6216                                 diag::warn_format_nonsensical_length);
6217   else if (!FS.hasStandardLengthModifier())
6218     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6219   else if (!FS.hasStandardLengthConversionCombination())
6220     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6221                                 diag::warn_format_non_standard_conversion_spec);
6222 
6223   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6224     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6225 
6226   // The remaining checks depend on the data arguments.
6227   if (HasVAListArg)
6228     return true;
6229 
6230   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6231     return false;
6232 
6233   // Check that the argument type matches the format specifier.
6234   const Expr *Ex = getDataArg(argIndex);
6235   if (!Ex)
6236     return true;
6237 
6238   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6239 
6240   if (!AT.isValid()) {
6241     return true;
6242   }
6243 
6244   analyze_format_string::ArgType::MatchKind match =
6245       AT.matchesType(S.Context, Ex->getType());
6246   if (match == analyze_format_string::ArgType::Match) {
6247     return true;
6248   }
6249 
6250   ScanfSpecifier fixedFS = FS;
6251   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6252                                  S.getLangOpts(), S.Context);
6253 
6254   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6255   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6256     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6257   }
6258 
6259   if (success) {
6260     // Get the fix string from the fixed format specifier.
6261     SmallString<128> buf;
6262     llvm::raw_svector_ostream os(buf);
6263     fixedFS.toString(os);
6264 
6265     EmitFormatDiagnostic(
6266         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6267                       << Ex->getType() << false << Ex->getSourceRange(),
6268         Ex->getLocStart(),
6269         /*IsStringLocation*/ false,
6270         getSpecifierRange(startSpecifier, specifierLen),
6271         FixItHint::CreateReplacement(
6272             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6273   } else {
6274     EmitFormatDiagnostic(S.PDiag(diag)
6275                              << AT.getRepresentativeTypeName(S.Context)
6276                              << Ex->getType() << false << Ex->getSourceRange(),
6277                          Ex->getLocStart(),
6278                          /*IsStringLocation*/ false,
6279                          getSpecifierRange(startSpecifier, specifierLen));
6280   }
6281 
6282   return true;
6283 }
6284 
6285 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6286                               const Expr *OrigFormatExpr,
6287                               ArrayRef<const Expr *> Args,
6288                               bool HasVAListArg, unsigned format_idx,
6289                               unsigned firstDataArg,
6290                               Sema::FormatStringType Type,
6291                               bool inFunctionCall,
6292                               Sema::VariadicCallType CallType,
6293                               llvm::SmallBitVector &CheckedVarArgs,
6294                               UncoveredArgHandler &UncoveredArg) {
6295   // CHECK: is the format string a wide literal?
6296   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6297     CheckFormatHandler::EmitFormatDiagnostic(
6298       S, inFunctionCall, Args[format_idx],
6299       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6300       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6301     return;
6302   }
6303 
6304   // Str - The format string.  NOTE: this is NOT null-terminated!
6305   StringRef StrRef = FExpr->getString();
6306   const char *Str = StrRef.data();
6307   // Account for cases where the string literal is truncated in a declaration.
6308   const ConstantArrayType *T =
6309     S.Context.getAsConstantArrayType(FExpr->getType());
6310   assert(T && "String literal not of constant array type!");
6311   size_t TypeSize = T->getSize().getZExtValue();
6312   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6313   const unsigned numDataArgs = Args.size() - firstDataArg;
6314 
6315   // Emit a warning if the string literal is truncated and does not contain an
6316   // embedded null character.
6317   if (TypeSize <= StrRef.size() &&
6318       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6319     CheckFormatHandler::EmitFormatDiagnostic(
6320         S, inFunctionCall, Args[format_idx],
6321         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6322         FExpr->getLocStart(),
6323         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6324     return;
6325   }
6326 
6327   // CHECK: empty format string?
6328   if (StrLen == 0 && numDataArgs > 0) {
6329     CheckFormatHandler::EmitFormatDiagnostic(
6330       S, inFunctionCall, Args[format_idx],
6331       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6332       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6333     return;
6334   }
6335 
6336   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6337       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6338       Type == Sema::FST_OSTrace) {
6339     CheckPrintfHandler H(
6340         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6341         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6342         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6343         CheckedVarArgs, UncoveredArg);
6344 
6345     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6346                                                   S.getLangOpts(),
6347                                                   S.Context.getTargetInfo(),
6348                                             Type == Sema::FST_FreeBSDKPrintf))
6349       H.DoneProcessing();
6350   } else if (Type == Sema::FST_Scanf) {
6351     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6352                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6353                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6354 
6355     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6356                                                  S.getLangOpts(),
6357                                                  S.Context.getTargetInfo()))
6358       H.DoneProcessing();
6359   } // TODO: handle other formats
6360 }
6361 
6362 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6363   // Str - The format string.  NOTE: this is NOT null-terminated!
6364   StringRef StrRef = FExpr->getString();
6365   const char *Str = StrRef.data();
6366   // Account for cases where the string literal is truncated in a declaration.
6367   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6368   assert(T && "String literal not of constant array type!");
6369   size_t TypeSize = T->getSize().getZExtValue();
6370   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6371   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6372                                                          getLangOpts(),
6373                                                          Context.getTargetInfo());
6374 }
6375 
6376 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6377 
6378 // Returns the related absolute value function that is larger, of 0 if one
6379 // does not exist.
6380 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6381   switch (AbsFunction) {
6382   default:
6383     return 0;
6384 
6385   case Builtin::BI__builtin_abs:
6386     return Builtin::BI__builtin_labs;
6387   case Builtin::BI__builtin_labs:
6388     return Builtin::BI__builtin_llabs;
6389   case Builtin::BI__builtin_llabs:
6390     return 0;
6391 
6392   case Builtin::BI__builtin_fabsf:
6393     return Builtin::BI__builtin_fabs;
6394   case Builtin::BI__builtin_fabs:
6395     return Builtin::BI__builtin_fabsl;
6396   case Builtin::BI__builtin_fabsl:
6397     return 0;
6398 
6399   case Builtin::BI__builtin_cabsf:
6400     return Builtin::BI__builtin_cabs;
6401   case Builtin::BI__builtin_cabs:
6402     return Builtin::BI__builtin_cabsl;
6403   case Builtin::BI__builtin_cabsl:
6404     return 0;
6405 
6406   case Builtin::BIabs:
6407     return Builtin::BIlabs;
6408   case Builtin::BIlabs:
6409     return Builtin::BIllabs;
6410   case Builtin::BIllabs:
6411     return 0;
6412 
6413   case Builtin::BIfabsf:
6414     return Builtin::BIfabs;
6415   case Builtin::BIfabs:
6416     return Builtin::BIfabsl;
6417   case Builtin::BIfabsl:
6418     return 0;
6419 
6420   case Builtin::BIcabsf:
6421    return Builtin::BIcabs;
6422   case Builtin::BIcabs:
6423     return Builtin::BIcabsl;
6424   case Builtin::BIcabsl:
6425     return 0;
6426   }
6427 }
6428 
6429 // Returns the argument type of the absolute value function.
6430 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6431                                              unsigned AbsType) {
6432   if (AbsType == 0)
6433     return QualType();
6434 
6435   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6436   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6437   if (Error != ASTContext::GE_None)
6438     return QualType();
6439 
6440   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6441   if (!FT)
6442     return QualType();
6443 
6444   if (FT->getNumParams() != 1)
6445     return QualType();
6446 
6447   return FT->getParamType(0);
6448 }
6449 
6450 // Returns the best absolute value function, or zero, based on type and
6451 // current absolute value function.
6452 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6453                                    unsigned AbsFunctionKind) {
6454   unsigned BestKind = 0;
6455   uint64_t ArgSize = Context.getTypeSize(ArgType);
6456   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6457        Kind = getLargerAbsoluteValueFunction(Kind)) {
6458     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6459     if (Context.getTypeSize(ParamType) >= ArgSize) {
6460       if (BestKind == 0)
6461         BestKind = Kind;
6462       else if (Context.hasSameType(ParamType, ArgType)) {
6463         BestKind = Kind;
6464         break;
6465       }
6466     }
6467   }
6468   return BestKind;
6469 }
6470 
6471 enum AbsoluteValueKind {
6472   AVK_Integer,
6473   AVK_Floating,
6474   AVK_Complex
6475 };
6476 
6477 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6478   if (T->isIntegralOrEnumerationType())
6479     return AVK_Integer;
6480   if (T->isRealFloatingType())
6481     return AVK_Floating;
6482   if (T->isAnyComplexType())
6483     return AVK_Complex;
6484 
6485   llvm_unreachable("Type not integer, floating, or complex");
6486 }
6487 
6488 // Changes the absolute value function to a different type.  Preserves whether
6489 // the function is a builtin.
6490 static unsigned changeAbsFunction(unsigned AbsKind,
6491                                   AbsoluteValueKind ValueKind) {
6492   switch (ValueKind) {
6493   case AVK_Integer:
6494     switch (AbsKind) {
6495     default:
6496       return 0;
6497     case Builtin::BI__builtin_fabsf:
6498     case Builtin::BI__builtin_fabs:
6499     case Builtin::BI__builtin_fabsl:
6500     case Builtin::BI__builtin_cabsf:
6501     case Builtin::BI__builtin_cabs:
6502     case Builtin::BI__builtin_cabsl:
6503       return Builtin::BI__builtin_abs;
6504     case Builtin::BIfabsf:
6505     case Builtin::BIfabs:
6506     case Builtin::BIfabsl:
6507     case Builtin::BIcabsf:
6508     case Builtin::BIcabs:
6509     case Builtin::BIcabsl:
6510       return Builtin::BIabs;
6511     }
6512   case AVK_Floating:
6513     switch (AbsKind) {
6514     default:
6515       return 0;
6516     case Builtin::BI__builtin_abs:
6517     case Builtin::BI__builtin_labs:
6518     case Builtin::BI__builtin_llabs:
6519     case Builtin::BI__builtin_cabsf:
6520     case Builtin::BI__builtin_cabs:
6521     case Builtin::BI__builtin_cabsl:
6522       return Builtin::BI__builtin_fabsf;
6523     case Builtin::BIabs:
6524     case Builtin::BIlabs:
6525     case Builtin::BIllabs:
6526     case Builtin::BIcabsf:
6527     case Builtin::BIcabs:
6528     case Builtin::BIcabsl:
6529       return Builtin::BIfabsf;
6530     }
6531   case AVK_Complex:
6532     switch (AbsKind) {
6533     default:
6534       return 0;
6535     case Builtin::BI__builtin_abs:
6536     case Builtin::BI__builtin_labs:
6537     case Builtin::BI__builtin_llabs:
6538     case Builtin::BI__builtin_fabsf:
6539     case Builtin::BI__builtin_fabs:
6540     case Builtin::BI__builtin_fabsl:
6541       return Builtin::BI__builtin_cabsf;
6542     case Builtin::BIabs:
6543     case Builtin::BIlabs:
6544     case Builtin::BIllabs:
6545     case Builtin::BIfabsf:
6546     case Builtin::BIfabs:
6547     case Builtin::BIfabsl:
6548       return Builtin::BIcabsf;
6549     }
6550   }
6551   llvm_unreachable("Unable to convert function");
6552 }
6553 
6554 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6555   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6556   if (!FnInfo)
6557     return 0;
6558 
6559   switch (FDecl->getBuiltinID()) {
6560   default:
6561     return 0;
6562   case Builtin::BI__builtin_abs:
6563   case Builtin::BI__builtin_fabs:
6564   case Builtin::BI__builtin_fabsf:
6565   case Builtin::BI__builtin_fabsl:
6566   case Builtin::BI__builtin_labs:
6567   case Builtin::BI__builtin_llabs:
6568   case Builtin::BI__builtin_cabs:
6569   case Builtin::BI__builtin_cabsf:
6570   case Builtin::BI__builtin_cabsl:
6571   case Builtin::BIabs:
6572   case Builtin::BIlabs:
6573   case Builtin::BIllabs:
6574   case Builtin::BIfabs:
6575   case Builtin::BIfabsf:
6576   case Builtin::BIfabsl:
6577   case Builtin::BIcabs:
6578   case Builtin::BIcabsf:
6579   case Builtin::BIcabsl:
6580     return FDecl->getBuiltinID();
6581   }
6582   llvm_unreachable("Unknown Builtin type");
6583 }
6584 
6585 // If the replacement is valid, emit a note with replacement function.
6586 // Additionally, suggest including the proper header if not already included.
6587 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6588                             unsigned AbsKind, QualType ArgType) {
6589   bool EmitHeaderHint = true;
6590   const char *HeaderName = nullptr;
6591   const char *FunctionName = nullptr;
6592   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6593     FunctionName = "std::abs";
6594     if (ArgType->isIntegralOrEnumerationType()) {
6595       HeaderName = "cstdlib";
6596     } else if (ArgType->isRealFloatingType()) {
6597       HeaderName = "cmath";
6598     } else {
6599       llvm_unreachable("Invalid Type");
6600     }
6601 
6602     // Lookup all std::abs
6603     if (NamespaceDecl *Std = S.getStdNamespace()) {
6604       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6605       R.suppressDiagnostics();
6606       S.LookupQualifiedName(R, Std);
6607 
6608       for (const auto *I : R) {
6609         const FunctionDecl *FDecl = nullptr;
6610         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6611           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6612         } else {
6613           FDecl = dyn_cast<FunctionDecl>(I);
6614         }
6615         if (!FDecl)
6616           continue;
6617 
6618         // Found std::abs(), check that they are the right ones.
6619         if (FDecl->getNumParams() != 1)
6620           continue;
6621 
6622         // Check that the parameter type can handle the argument.
6623         QualType ParamType = FDecl->getParamDecl(0)->getType();
6624         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6625             S.Context.getTypeSize(ArgType) <=
6626                 S.Context.getTypeSize(ParamType)) {
6627           // Found a function, don't need the header hint.
6628           EmitHeaderHint = false;
6629           break;
6630         }
6631       }
6632     }
6633   } else {
6634     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6635     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6636 
6637     if (HeaderName) {
6638       DeclarationName DN(&S.Context.Idents.get(FunctionName));
6639       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6640       R.suppressDiagnostics();
6641       S.LookupName(R, S.getCurScope());
6642 
6643       if (R.isSingleResult()) {
6644         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6645         if (FD && FD->getBuiltinID() == AbsKind) {
6646           EmitHeaderHint = false;
6647         } else {
6648           return;
6649         }
6650       } else if (!R.empty()) {
6651         return;
6652       }
6653     }
6654   }
6655 
6656   S.Diag(Loc, diag::note_replace_abs_function)
6657       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6658 
6659   if (!HeaderName)
6660     return;
6661 
6662   if (!EmitHeaderHint)
6663     return;
6664 
6665   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6666                                                     << FunctionName;
6667 }
6668 
6669 template <std::size_t StrLen>
6670 static bool IsStdFunction(const FunctionDecl *FDecl,
6671                           const char (&Str)[StrLen]) {
6672   if (!FDecl)
6673     return false;
6674   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
6675     return false;
6676   if (!FDecl->isInStdNamespace())
6677     return false;
6678 
6679   return true;
6680 }
6681 
6682 // Warn when using the wrong abs() function.
6683 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6684                                       const FunctionDecl *FDecl) {
6685   if (Call->getNumArgs() != 1)
6686     return;
6687 
6688   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6689   bool IsStdAbs = IsStdFunction(FDecl, "abs");
6690   if (AbsKind == 0 && !IsStdAbs)
6691     return;
6692 
6693   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6694   QualType ParamType = Call->getArg(0)->getType();
6695 
6696   // Unsigned types cannot be negative.  Suggest removing the absolute value
6697   // function call.
6698   if (ArgType->isUnsignedIntegerType()) {
6699     const char *FunctionName =
6700         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6701     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6702     Diag(Call->getExprLoc(), diag::note_remove_abs)
6703         << FunctionName
6704         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6705     return;
6706   }
6707 
6708   // Taking the absolute value of a pointer is very suspicious, they probably
6709   // wanted to index into an array, dereference a pointer, call a function, etc.
6710   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6711     unsigned DiagType = 0;
6712     if (ArgType->isFunctionType())
6713       DiagType = 1;
6714     else if (ArgType->isArrayType())
6715       DiagType = 2;
6716 
6717     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6718     return;
6719   }
6720 
6721   // std::abs has overloads which prevent most of the absolute value problems
6722   // from occurring.
6723   if (IsStdAbs)
6724     return;
6725 
6726   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6727   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6728 
6729   // The argument and parameter are the same kind.  Check if they are the right
6730   // size.
6731   if (ArgValueKind == ParamValueKind) {
6732     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6733       return;
6734 
6735     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6736     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6737         << FDecl << ArgType << ParamType;
6738 
6739     if (NewAbsKind == 0)
6740       return;
6741 
6742     emitReplacement(*this, Call->getExprLoc(),
6743                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6744     return;
6745   }
6746 
6747   // ArgValueKind != ParamValueKind
6748   // The wrong type of absolute value function was used.  Attempt to find the
6749   // proper one.
6750   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6751   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6752   if (NewAbsKind == 0)
6753     return;
6754 
6755   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6756       << FDecl << ParamValueKind << ArgValueKind;
6757 
6758   emitReplacement(*this, Call->getExprLoc(),
6759                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6760 }
6761 
6762 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
6763 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6764                                 const FunctionDecl *FDecl) {
6765   if (!Call || !FDecl) return;
6766 
6767   // Ignore template specializations and macros.
6768   if (!ActiveTemplateInstantiations.empty()) return;
6769   if (Call->getExprLoc().isMacroID()) return;
6770 
6771   // Only care about the one template argument, two function parameter std::max
6772   if (Call->getNumArgs() != 2) return;
6773   if (!IsStdFunction(FDecl, "max")) return;
6774   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6775   if (!ArgList) return;
6776   if (ArgList->size() != 1) return;
6777 
6778   // Check that template type argument is unsigned integer.
6779   const auto& TA = ArgList->get(0);
6780   if (TA.getKind() != TemplateArgument::Type) return;
6781   QualType ArgType = TA.getAsType();
6782   if (!ArgType->isUnsignedIntegerType()) return;
6783 
6784   // See if either argument is a literal zero.
6785   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6786     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6787     if (!MTE) return false;
6788     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6789     if (!Num) return false;
6790     if (Num->getValue() != 0) return false;
6791     return true;
6792   };
6793 
6794   const Expr *FirstArg = Call->getArg(0);
6795   const Expr *SecondArg = Call->getArg(1);
6796   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6797   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6798 
6799   // Only warn when exactly one argument is zero.
6800   if (IsFirstArgZero == IsSecondArgZero) return;
6801 
6802   SourceRange FirstRange = FirstArg->getSourceRange();
6803   SourceRange SecondRange = SecondArg->getSourceRange();
6804 
6805   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
6806 
6807   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
6808       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
6809 
6810   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
6811   SourceRange RemovalRange;
6812   if (IsFirstArgZero) {
6813     RemovalRange = SourceRange(FirstRange.getBegin(),
6814                                SecondRange.getBegin().getLocWithOffset(-1));
6815   } else {
6816     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
6817                                SecondRange.getEnd());
6818   }
6819 
6820   Diag(Call->getExprLoc(), diag::note_remove_max_call)
6821         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
6822         << FixItHint::CreateRemoval(RemovalRange);
6823 }
6824 
6825 //===--- CHECK: Standard memory functions ---------------------------------===//
6826 
6827 /// \brief Takes the expression passed to the size_t parameter of functions
6828 /// such as memcmp, strncat, etc and warns if it's a comparison.
6829 ///
6830 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6831 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6832                                            IdentifierInfo *FnName,
6833                                            SourceLocation FnLoc,
6834                                            SourceLocation RParenLoc) {
6835   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6836   if (!Size)
6837     return false;
6838 
6839   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6840   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6841     return false;
6842 
6843   SourceRange SizeRange = Size->getSourceRange();
6844   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6845       << SizeRange << FnName;
6846   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
6847       << FnName << FixItHint::CreateInsertion(
6848                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
6849       << FixItHint::CreateRemoval(RParenLoc);
6850   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
6851       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
6852       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6853                                     ")");
6854 
6855   return true;
6856 }
6857 
6858 /// \brief Determine whether the given type is or contains a dynamic class type
6859 /// (e.g., whether it has a vtable).
6860 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6861                                                      bool &IsContained) {
6862   // Look through array types while ignoring qualifiers.
6863   const Type *Ty = T->getBaseElementTypeUnsafe();
6864   IsContained = false;
6865 
6866   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6867   RD = RD ? RD->getDefinition() : nullptr;
6868   if (!RD || RD->isInvalidDecl())
6869     return nullptr;
6870 
6871   if (RD->isDynamicClass())
6872     return RD;
6873 
6874   // Check all the fields.  If any bases were dynamic, the class is dynamic.
6875   // It's impossible for a class to transitively contain itself by value, so
6876   // infinite recursion is impossible.
6877   for (auto *FD : RD->fields()) {
6878     bool SubContained;
6879     if (const CXXRecordDecl *ContainedRD =
6880             getContainedDynamicClass(FD->getType(), SubContained)) {
6881       IsContained = true;
6882       return ContainedRD;
6883     }
6884   }
6885 
6886   return nullptr;
6887 }
6888 
6889 /// \brief If E is a sizeof expression, returns its argument expression,
6890 /// otherwise returns NULL.
6891 static const Expr *getSizeOfExprArg(const Expr *E) {
6892   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6893       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6894     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6895       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
6896 
6897   return nullptr;
6898 }
6899 
6900 /// \brief If E is a sizeof expression, returns its argument type.
6901 static QualType getSizeOfArgType(const Expr *E) {
6902   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6903       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6904     if (SizeOf->getKind() == clang::UETT_SizeOf)
6905       return SizeOf->getTypeOfArgument();
6906 
6907   return QualType();
6908 }
6909 
6910 /// \brief Check for dangerous or invalid arguments to memset().
6911 ///
6912 /// This issues warnings on known problematic, dangerous or unspecified
6913 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6914 /// function calls.
6915 ///
6916 /// \param Call The call expression to diagnose.
6917 void Sema::CheckMemaccessArguments(const CallExpr *Call,
6918                                    unsigned BId,
6919                                    IdentifierInfo *FnName) {
6920   assert(BId != 0);
6921 
6922   // It is possible to have a non-standard definition of memset.  Validate
6923   // we have enough arguments, and if not, abort further checking.
6924   unsigned ExpectedNumArgs =
6925       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
6926   if (Call->getNumArgs() < ExpectedNumArgs)
6927     return;
6928 
6929   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
6930                       BId == Builtin::BIstrndup ? 1 : 2);
6931   unsigned LenArg =
6932       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
6933   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
6934 
6935   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6936                                      Call->getLocStart(), Call->getRParenLoc()))
6937     return;
6938 
6939   // We have special checking when the length is a sizeof expression.
6940   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6941   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6942   llvm::FoldingSetNodeID SizeOfArgID;
6943 
6944   // Although widely used, 'bzero' is not a standard function. Be more strict
6945   // with the argument types before allowing diagnostics and only allow the
6946   // form bzero(ptr, sizeof(...)).
6947   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6948   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6949     return;
6950 
6951   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6952     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
6953     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
6954 
6955     QualType DestTy = Dest->getType();
6956     QualType PointeeTy;
6957     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
6958       PointeeTy = DestPtrTy->getPointeeType();
6959 
6960       // Never warn about void type pointers. This can be used to suppress
6961       // false positives.
6962       if (PointeeTy->isVoidType())
6963         continue;
6964 
6965       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6966       // actually comparing the expressions for equality. Because computing the
6967       // expression IDs can be expensive, we only do this if the diagnostic is
6968       // enabled.
6969       if (SizeOfArg &&
6970           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6971                            SizeOfArg->getExprLoc())) {
6972         // We only compute IDs for expressions if the warning is enabled, and
6973         // cache the sizeof arg's ID.
6974         if (SizeOfArgID == llvm::FoldingSetNodeID())
6975           SizeOfArg->Profile(SizeOfArgID, Context, true);
6976         llvm::FoldingSetNodeID DestID;
6977         Dest->Profile(DestID, Context, true);
6978         if (DestID == SizeOfArgID) {
6979           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6980           //       over sizeof(src) as well.
6981           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
6982           StringRef ReadableName = FnName->getName();
6983 
6984           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
6985             if (UnaryOp->getOpcode() == UO_AddrOf)
6986               ActionIdx = 1; // If its an address-of operator, just remove it.
6987           if (!PointeeTy->isIncompleteType() &&
6988               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
6989             ActionIdx = 2; // If the pointee's size is sizeof(char),
6990                            // suggest an explicit length.
6991 
6992           // If the function is defined as a builtin macro, do not show macro
6993           // expansion.
6994           SourceLocation SL = SizeOfArg->getExprLoc();
6995           SourceRange DSR = Dest->getSourceRange();
6996           SourceRange SSR = SizeOfArg->getSourceRange();
6997           SourceManager &SM = getSourceManager();
6998 
6999           if (SM.isMacroArgExpansion(SL)) {
7000             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7001             SL = SM.getSpellingLoc(SL);
7002             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7003                              SM.getSpellingLoc(DSR.getEnd()));
7004             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7005                              SM.getSpellingLoc(SSR.getEnd()));
7006           }
7007 
7008           DiagRuntimeBehavior(SL, SizeOfArg,
7009                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7010                                 << ReadableName
7011                                 << PointeeTy
7012                                 << DestTy
7013                                 << DSR
7014                                 << SSR);
7015           DiagRuntimeBehavior(SL, SizeOfArg,
7016                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7017                                 << ActionIdx
7018                                 << SSR);
7019 
7020           break;
7021         }
7022       }
7023 
7024       // Also check for cases where the sizeof argument is the exact same
7025       // type as the memory argument, and where it points to a user-defined
7026       // record type.
7027       if (SizeOfArgTy != QualType()) {
7028         if (PointeeTy->isRecordType() &&
7029             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7030           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7031                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7032                                 << FnName << SizeOfArgTy << ArgIdx
7033                                 << PointeeTy << Dest->getSourceRange()
7034                                 << LenExpr->getSourceRange());
7035           break;
7036         }
7037       }
7038     } else if (DestTy->isArrayType()) {
7039       PointeeTy = DestTy;
7040     }
7041 
7042     if (PointeeTy == QualType())
7043       continue;
7044 
7045     // Always complain about dynamic classes.
7046     bool IsContained;
7047     if (const CXXRecordDecl *ContainedRD =
7048             getContainedDynamicClass(PointeeTy, IsContained)) {
7049 
7050       unsigned OperationType = 0;
7051       // "overwritten" if we're warning about the destination for any call
7052       // but memcmp; otherwise a verb appropriate to the call.
7053       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7054         if (BId == Builtin::BImemcpy)
7055           OperationType = 1;
7056         else if(BId == Builtin::BImemmove)
7057           OperationType = 2;
7058         else if (BId == Builtin::BImemcmp)
7059           OperationType = 3;
7060       }
7061 
7062       DiagRuntimeBehavior(
7063         Dest->getExprLoc(), Dest,
7064         PDiag(diag::warn_dyn_class_memaccess)
7065           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7066           << FnName << IsContained << ContainedRD << OperationType
7067           << Call->getCallee()->getSourceRange());
7068     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7069              BId != Builtin::BImemset)
7070       DiagRuntimeBehavior(
7071         Dest->getExprLoc(), Dest,
7072         PDiag(diag::warn_arc_object_memaccess)
7073           << ArgIdx << FnName << PointeeTy
7074           << Call->getCallee()->getSourceRange());
7075     else
7076       continue;
7077 
7078     DiagRuntimeBehavior(
7079       Dest->getExprLoc(), Dest,
7080       PDiag(diag::note_bad_memaccess_silence)
7081         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7082     break;
7083   }
7084 }
7085 
7086 // A little helper routine: ignore addition and subtraction of integer literals.
7087 // This intentionally does not ignore all integer constant expressions because
7088 // we don't want to remove sizeof().
7089 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7090   Ex = Ex->IgnoreParenCasts();
7091 
7092   for (;;) {
7093     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7094     if (!BO || !BO->isAdditiveOp())
7095       break;
7096 
7097     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7098     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7099 
7100     if (isa<IntegerLiteral>(RHS))
7101       Ex = LHS;
7102     else if (isa<IntegerLiteral>(LHS))
7103       Ex = RHS;
7104     else
7105       break;
7106   }
7107 
7108   return Ex;
7109 }
7110 
7111 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7112                                                       ASTContext &Context) {
7113   // Only handle constant-sized or VLAs, but not flexible members.
7114   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7115     // Only issue the FIXIT for arrays of size > 1.
7116     if (CAT->getSize().getSExtValue() <= 1)
7117       return false;
7118   } else if (!Ty->isVariableArrayType()) {
7119     return false;
7120   }
7121   return true;
7122 }
7123 
7124 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7125 // be the size of the source, instead of the destination.
7126 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7127                                     IdentifierInfo *FnName) {
7128 
7129   // Don't crash if the user has the wrong number of arguments
7130   unsigned NumArgs = Call->getNumArgs();
7131   if ((NumArgs != 3) && (NumArgs != 4))
7132     return;
7133 
7134   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7135   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7136   const Expr *CompareWithSrc = nullptr;
7137 
7138   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7139                                      Call->getLocStart(), Call->getRParenLoc()))
7140     return;
7141 
7142   // Look for 'strlcpy(dst, x, sizeof(x))'
7143   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7144     CompareWithSrc = Ex;
7145   else {
7146     // Look for 'strlcpy(dst, x, strlen(x))'
7147     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7148       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7149           SizeCall->getNumArgs() == 1)
7150         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7151     }
7152   }
7153 
7154   if (!CompareWithSrc)
7155     return;
7156 
7157   // Determine if the argument to sizeof/strlen is equal to the source
7158   // argument.  In principle there's all kinds of things you could do
7159   // here, for instance creating an == expression and evaluating it with
7160   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7161   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7162   if (!SrcArgDRE)
7163     return;
7164 
7165   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7166   if (!CompareWithSrcDRE ||
7167       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7168     return;
7169 
7170   const Expr *OriginalSizeArg = Call->getArg(2);
7171   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7172     << OriginalSizeArg->getSourceRange() << FnName;
7173 
7174   // Output a FIXIT hint if the destination is an array (rather than a
7175   // pointer to an array).  This could be enhanced to handle some
7176   // pointers if we know the actual size, like if DstArg is 'array+2'
7177   // we could say 'sizeof(array)-2'.
7178   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7179   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7180     return;
7181 
7182   SmallString<128> sizeString;
7183   llvm::raw_svector_ostream OS(sizeString);
7184   OS << "sizeof(";
7185   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7186   OS << ")";
7187 
7188   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7189     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7190                                     OS.str());
7191 }
7192 
7193 /// Check if two expressions refer to the same declaration.
7194 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7195   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7196     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7197       return D1->getDecl() == D2->getDecl();
7198   return false;
7199 }
7200 
7201 static const Expr *getStrlenExprArg(const Expr *E) {
7202   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7203     const FunctionDecl *FD = CE->getDirectCallee();
7204     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7205       return nullptr;
7206     return CE->getArg(0)->IgnoreParenCasts();
7207   }
7208   return nullptr;
7209 }
7210 
7211 // Warn on anti-patterns as the 'size' argument to strncat.
7212 // The correct size argument should look like following:
7213 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7214 void Sema::CheckStrncatArguments(const CallExpr *CE,
7215                                  IdentifierInfo *FnName) {
7216   // Don't crash if the user has the wrong number of arguments.
7217   if (CE->getNumArgs() < 3)
7218     return;
7219   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7220   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7221   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7222 
7223   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7224                                      CE->getRParenLoc()))
7225     return;
7226 
7227   // Identify common expressions, which are wrongly used as the size argument
7228   // to strncat and may lead to buffer overflows.
7229   unsigned PatternType = 0;
7230   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7231     // - sizeof(dst)
7232     if (referToTheSameDecl(SizeOfArg, DstArg))
7233       PatternType = 1;
7234     // - sizeof(src)
7235     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7236       PatternType = 2;
7237   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7238     if (BE->getOpcode() == BO_Sub) {
7239       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7240       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7241       // - sizeof(dst) - strlen(dst)
7242       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7243           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7244         PatternType = 1;
7245       // - sizeof(src) - (anything)
7246       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7247         PatternType = 2;
7248     }
7249   }
7250 
7251   if (PatternType == 0)
7252     return;
7253 
7254   // Generate the diagnostic.
7255   SourceLocation SL = LenArg->getLocStart();
7256   SourceRange SR = LenArg->getSourceRange();
7257   SourceManager &SM = getSourceManager();
7258 
7259   // If the function is defined as a builtin macro, do not show macro expansion.
7260   if (SM.isMacroArgExpansion(SL)) {
7261     SL = SM.getSpellingLoc(SL);
7262     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7263                      SM.getSpellingLoc(SR.getEnd()));
7264   }
7265 
7266   // Check if the destination is an array (rather than a pointer to an array).
7267   QualType DstTy = DstArg->getType();
7268   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7269                                                                     Context);
7270   if (!isKnownSizeArray) {
7271     if (PatternType == 1)
7272       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7273     else
7274       Diag(SL, diag::warn_strncat_src_size) << SR;
7275     return;
7276   }
7277 
7278   if (PatternType == 1)
7279     Diag(SL, diag::warn_strncat_large_size) << SR;
7280   else
7281     Diag(SL, diag::warn_strncat_src_size) << SR;
7282 
7283   SmallString<128> sizeString;
7284   llvm::raw_svector_ostream OS(sizeString);
7285   OS << "sizeof(";
7286   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7287   OS << ") - ";
7288   OS << "strlen(";
7289   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7290   OS << ") - 1";
7291 
7292   Diag(SL, diag::note_strncat_wrong_size)
7293     << FixItHint::CreateReplacement(SR, OS.str());
7294 }
7295 
7296 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7297 
7298 static const Expr *EvalVal(const Expr *E,
7299                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7300                            const Decl *ParentDecl);
7301 static const Expr *EvalAddr(const Expr *E,
7302                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7303                             const Decl *ParentDecl);
7304 
7305 /// CheckReturnStackAddr - Check if a return statement returns the address
7306 ///   of a stack variable.
7307 static void
7308 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7309                      SourceLocation ReturnLoc) {
7310 
7311   const Expr *stackE = nullptr;
7312   SmallVector<const DeclRefExpr *, 8> refVars;
7313 
7314   // Perform checking for returned stack addresses, local blocks,
7315   // label addresses or references to temporaries.
7316   if (lhsType->isPointerType() ||
7317       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7318     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7319   } else if (lhsType->isReferenceType()) {
7320     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7321   }
7322 
7323   if (!stackE)
7324     return; // Nothing suspicious was found.
7325 
7326   // Parameters are initalized in the calling scope, so taking the address
7327   // of a parameter reference doesn't need a warning.
7328   for (auto *DRE : refVars)
7329     if (isa<ParmVarDecl>(DRE->getDecl()))
7330       return;
7331 
7332   SourceLocation diagLoc;
7333   SourceRange diagRange;
7334   if (refVars.empty()) {
7335     diagLoc = stackE->getLocStart();
7336     diagRange = stackE->getSourceRange();
7337   } else {
7338     // We followed through a reference variable. 'stackE' contains the
7339     // problematic expression but we will warn at the return statement pointing
7340     // at the reference variable. We will later display the "trail" of
7341     // reference variables using notes.
7342     diagLoc = refVars[0]->getLocStart();
7343     diagRange = refVars[0]->getSourceRange();
7344   }
7345 
7346   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7347     // address of local var
7348     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7349      << DR->getDecl()->getDeclName() << diagRange;
7350   } else if (isa<BlockExpr>(stackE)) { // local block.
7351     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7352   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7353     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7354   } else { // local temporary.
7355     // If there is an LValue->RValue conversion, then the value of the
7356     // reference type is used, not the reference.
7357     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7358       if (ICE->getCastKind() == CK_LValueToRValue) {
7359         return;
7360       }
7361     }
7362     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7363      << lhsType->isReferenceType() << diagRange;
7364   }
7365 
7366   // Display the "trail" of reference variables that we followed until we
7367   // found the problematic expression using notes.
7368   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7369     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7370     // If this var binds to another reference var, show the range of the next
7371     // var, otherwise the var binds to the problematic expression, in which case
7372     // show the range of the expression.
7373     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7374                                     : stackE->getSourceRange();
7375     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7376         << VD->getDeclName() << range;
7377   }
7378 }
7379 
7380 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7381 ///  check if the expression in a return statement evaluates to an address
7382 ///  to a location on the stack, a local block, an address of a label, or a
7383 ///  reference to local temporary. The recursion is used to traverse the
7384 ///  AST of the return expression, with recursion backtracking when we
7385 ///  encounter a subexpression that (1) clearly does not lead to one of the
7386 ///  above problematic expressions (2) is something we cannot determine leads to
7387 ///  a problematic expression based on such local checking.
7388 ///
7389 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7390 ///  the expression that they point to. Such variables are added to the
7391 ///  'refVars' vector so that we know what the reference variable "trail" was.
7392 ///
7393 ///  EvalAddr processes expressions that are pointers that are used as
7394 ///  references (and not L-values).  EvalVal handles all other values.
7395 ///  At the base case of the recursion is a check for the above problematic
7396 ///  expressions.
7397 ///
7398 ///  This implementation handles:
7399 ///
7400 ///   * pointer-to-pointer casts
7401 ///   * implicit conversions from array references to pointers
7402 ///   * taking the address of fields
7403 ///   * arbitrary interplay between "&" and "*" operators
7404 ///   * pointer arithmetic from an address of a stack variable
7405 ///   * taking the address of an array element where the array is on the stack
7406 static const Expr *EvalAddr(const Expr *E,
7407                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7408                             const Decl *ParentDecl) {
7409   if (E->isTypeDependent())
7410     return nullptr;
7411 
7412   // We should only be called for evaluating pointer expressions.
7413   assert((E->getType()->isAnyPointerType() ||
7414           E->getType()->isBlockPointerType() ||
7415           E->getType()->isObjCQualifiedIdType()) &&
7416          "EvalAddr only works on pointers");
7417 
7418   E = E->IgnoreParens();
7419 
7420   // Our "symbolic interpreter" is just a dispatch off the currently
7421   // viewed AST node.  We then recursively traverse the AST by calling
7422   // EvalAddr and EvalVal appropriately.
7423   switch (E->getStmtClass()) {
7424   case Stmt::DeclRefExprClass: {
7425     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7426 
7427     // If we leave the immediate function, the lifetime isn't about to end.
7428     if (DR->refersToEnclosingVariableOrCapture())
7429       return nullptr;
7430 
7431     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7432       // If this is a reference variable, follow through to the expression that
7433       // it points to.
7434       if (V->hasLocalStorage() &&
7435           V->getType()->isReferenceType() && V->hasInit()) {
7436         // Add the reference variable to the "trail".
7437         refVars.push_back(DR);
7438         return EvalAddr(V->getInit(), refVars, ParentDecl);
7439       }
7440 
7441     return nullptr;
7442   }
7443 
7444   case Stmt::UnaryOperatorClass: {
7445     // The only unary operator that make sense to handle here
7446     // is AddrOf.  All others don't make sense as pointers.
7447     const UnaryOperator *U = cast<UnaryOperator>(E);
7448 
7449     if (U->getOpcode() == UO_AddrOf)
7450       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7451     return nullptr;
7452   }
7453 
7454   case Stmt::BinaryOperatorClass: {
7455     // Handle pointer arithmetic.  All other binary operators are not valid
7456     // in this context.
7457     const BinaryOperator *B = cast<BinaryOperator>(E);
7458     BinaryOperatorKind op = B->getOpcode();
7459 
7460     if (op != BO_Add && op != BO_Sub)
7461       return nullptr;
7462 
7463     const Expr *Base = B->getLHS();
7464 
7465     // Determine which argument is the real pointer base.  It could be
7466     // the RHS argument instead of the LHS.
7467     if (!Base->getType()->isPointerType())
7468       Base = B->getRHS();
7469 
7470     assert(Base->getType()->isPointerType());
7471     return EvalAddr(Base, refVars, ParentDecl);
7472   }
7473 
7474   // For conditional operators we need to see if either the LHS or RHS are
7475   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7476   case Stmt::ConditionalOperatorClass: {
7477     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7478 
7479     // Handle the GNU extension for missing LHS.
7480     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7481     if (const Expr *LHSExpr = C->getLHS()) {
7482       // In C++, we can have a throw-expression, which has 'void' type.
7483       if (!LHSExpr->getType()->isVoidType())
7484         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7485           return LHS;
7486     }
7487 
7488     // In C++, we can have a throw-expression, which has 'void' type.
7489     if (C->getRHS()->getType()->isVoidType())
7490       return nullptr;
7491 
7492     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7493   }
7494 
7495   case Stmt::BlockExprClass:
7496     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7497       return E; // local block.
7498     return nullptr;
7499 
7500   case Stmt::AddrLabelExprClass:
7501     return E; // address of label.
7502 
7503   case Stmt::ExprWithCleanupsClass:
7504     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7505                     ParentDecl);
7506 
7507   // For casts, we need to handle conversions from arrays to
7508   // pointer values, and pointer-to-pointer conversions.
7509   case Stmt::ImplicitCastExprClass:
7510   case Stmt::CStyleCastExprClass:
7511   case Stmt::CXXFunctionalCastExprClass:
7512   case Stmt::ObjCBridgedCastExprClass:
7513   case Stmt::CXXStaticCastExprClass:
7514   case Stmt::CXXDynamicCastExprClass:
7515   case Stmt::CXXConstCastExprClass:
7516   case Stmt::CXXReinterpretCastExprClass: {
7517     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7518     switch (cast<CastExpr>(E)->getCastKind()) {
7519     case CK_LValueToRValue:
7520     case CK_NoOp:
7521     case CK_BaseToDerived:
7522     case CK_DerivedToBase:
7523     case CK_UncheckedDerivedToBase:
7524     case CK_Dynamic:
7525     case CK_CPointerToObjCPointerCast:
7526     case CK_BlockPointerToObjCPointerCast:
7527     case CK_AnyPointerToBlockPointerCast:
7528       return EvalAddr(SubExpr, refVars, ParentDecl);
7529 
7530     case CK_ArrayToPointerDecay:
7531       return EvalVal(SubExpr, refVars, ParentDecl);
7532 
7533     case CK_BitCast:
7534       if (SubExpr->getType()->isAnyPointerType() ||
7535           SubExpr->getType()->isBlockPointerType() ||
7536           SubExpr->getType()->isObjCQualifiedIdType())
7537         return EvalAddr(SubExpr, refVars, ParentDecl);
7538       else
7539         return nullptr;
7540 
7541     default:
7542       return nullptr;
7543     }
7544   }
7545 
7546   case Stmt::MaterializeTemporaryExprClass:
7547     if (const Expr *Result =
7548             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7549                      refVars, ParentDecl))
7550       return Result;
7551     return E;
7552 
7553   // Everything else: we simply don't reason about them.
7554   default:
7555     return nullptr;
7556   }
7557 }
7558 
7559 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7560 ///   See the comments for EvalAddr for more details.
7561 static const Expr *EvalVal(const Expr *E,
7562                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7563                            const Decl *ParentDecl) {
7564   do {
7565     // We should only be called for evaluating non-pointer expressions, or
7566     // expressions with a pointer type that are not used as references but
7567     // instead
7568     // are l-values (e.g., DeclRefExpr with a pointer type).
7569 
7570     // Our "symbolic interpreter" is just a dispatch off the currently
7571     // viewed AST node.  We then recursively traverse the AST by calling
7572     // EvalAddr and EvalVal appropriately.
7573 
7574     E = E->IgnoreParens();
7575     switch (E->getStmtClass()) {
7576     case Stmt::ImplicitCastExprClass: {
7577       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7578       if (IE->getValueKind() == VK_LValue) {
7579         E = IE->getSubExpr();
7580         continue;
7581       }
7582       return nullptr;
7583     }
7584 
7585     case Stmt::ExprWithCleanupsClass:
7586       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7587                      ParentDecl);
7588 
7589     case Stmt::DeclRefExprClass: {
7590       // When we hit a DeclRefExpr we are looking at code that refers to a
7591       // variable's name. If it's not a reference variable we check if it has
7592       // local storage within the function, and if so, return the expression.
7593       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7594 
7595       // If we leave the immediate function, the lifetime isn't about to end.
7596       if (DR->refersToEnclosingVariableOrCapture())
7597         return nullptr;
7598 
7599       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7600         // Check if it refers to itself, e.g. "int& i = i;".
7601         if (V == ParentDecl)
7602           return DR;
7603 
7604         if (V->hasLocalStorage()) {
7605           if (!V->getType()->isReferenceType())
7606             return DR;
7607 
7608           // Reference variable, follow through to the expression that
7609           // it points to.
7610           if (V->hasInit()) {
7611             // Add the reference variable to the "trail".
7612             refVars.push_back(DR);
7613             return EvalVal(V->getInit(), refVars, V);
7614           }
7615         }
7616       }
7617 
7618       return nullptr;
7619     }
7620 
7621     case Stmt::UnaryOperatorClass: {
7622       // The only unary operator that make sense to handle here
7623       // is Deref.  All others don't resolve to a "name."  This includes
7624       // handling all sorts of rvalues passed to a unary operator.
7625       const UnaryOperator *U = cast<UnaryOperator>(E);
7626 
7627       if (U->getOpcode() == UO_Deref)
7628         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7629 
7630       return nullptr;
7631     }
7632 
7633     case Stmt::ArraySubscriptExprClass: {
7634       // Array subscripts are potential references to data on the stack.  We
7635       // retrieve the DeclRefExpr* for the array variable if it indeed
7636       // has local storage.
7637       const auto *ASE = cast<ArraySubscriptExpr>(E);
7638       if (ASE->isTypeDependent())
7639         return nullptr;
7640       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7641     }
7642 
7643     case Stmt::OMPArraySectionExprClass: {
7644       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7645                       ParentDecl);
7646     }
7647 
7648     case Stmt::ConditionalOperatorClass: {
7649       // For conditional operators we need to see if either the LHS or RHS are
7650       // non-NULL Expr's.  If one is non-NULL, we return it.
7651       const ConditionalOperator *C = cast<ConditionalOperator>(E);
7652 
7653       // Handle the GNU extension for missing LHS.
7654       if (const Expr *LHSExpr = C->getLHS()) {
7655         // In C++, we can have a throw-expression, which has 'void' type.
7656         if (!LHSExpr->getType()->isVoidType())
7657           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7658             return LHS;
7659       }
7660 
7661       // In C++, we can have a throw-expression, which has 'void' type.
7662       if (C->getRHS()->getType()->isVoidType())
7663         return nullptr;
7664 
7665       return EvalVal(C->getRHS(), refVars, ParentDecl);
7666     }
7667 
7668     // Accesses to members are potential references to data on the stack.
7669     case Stmt::MemberExprClass: {
7670       const MemberExpr *M = cast<MemberExpr>(E);
7671 
7672       // Check for indirect access.  We only want direct field accesses.
7673       if (M->isArrow())
7674         return nullptr;
7675 
7676       // Check whether the member type is itself a reference, in which case
7677       // we're not going to refer to the member, but to what the member refers
7678       // to.
7679       if (M->getMemberDecl()->getType()->isReferenceType())
7680         return nullptr;
7681 
7682       return EvalVal(M->getBase(), refVars, ParentDecl);
7683     }
7684 
7685     case Stmt::MaterializeTemporaryExprClass:
7686       if (const Expr *Result =
7687               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7688                       refVars, ParentDecl))
7689         return Result;
7690       return E;
7691 
7692     default:
7693       // Check that we don't return or take the address of a reference to a
7694       // temporary. This is only useful in C++.
7695       if (!E->isTypeDependent() && E->isRValue())
7696         return E;
7697 
7698       // Everything else: we simply don't reason about them.
7699       return nullptr;
7700     }
7701   } while (true);
7702 }
7703 
7704 void
7705 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7706                          SourceLocation ReturnLoc,
7707                          bool isObjCMethod,
7708                          const AttrVec *Attrs,
7709                          const FunctionDecl *FD) {
7710   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7711 
7712   // Check if the return value is null but should not be.
7713   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7714        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7715       CheckNonNullExpr(*this, RetValExp))
7716     Diag(ReturnLoc, diag::warn_null_ret)
7717       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7718 
7719   // C++11 [basic.stc.dynamic.allocation]p4:
7720   //   If an allocation function declared with a non-throwing
7721   //   exception-specification fails to allocate storage, it shall return
7722   //   a null pointer. Any other allocation function that fails to allocate
7723   //   storage shall indicate failure only by throwing an exception [...]
7724   if (FD) {
7725     OverloadedOperatorKind Op = FD->getOverloadedOperator();
7726     if (Op == OO_New || Op == OO_Array_New) {
7727       const FunctionProtoType *Proto
7728         = FD->getType()->castAs<FunctionProtoType>();
7729       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7730           CheckNonNullExpr(*this, RetValExp))
7731         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7732           << FD << getLangOpts().CPlusPlus11;
7733     }
7734   }
7735 }
7736 
7737 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7738 
7739 /// Check for comparisons of floating point operands using != and ==.
7740 /// Issue a warning if these are no self-comparisons, as they are not likely
7741 /// to do what the programmer intended.
7742 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7743   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7744   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7745 
7746   // Special case: check for x == x (which is OK).
7747   // Do not emit warnings for such cases.
7748   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7749     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7750       if (DRL->getDecl() == DRR->getDecl())
7751         return;
7752 
7753   // Special case: check for comparisons against literals that can be exactly
7754   //  represented by APFloat.  In such cases, do not emit a warning.  This
7755   //  is a heuristic: often comparison against such literals are used to
7756   //  detect if a value in a variable has not changed.  This clearly can
7757   //  lead to false negatives.
7758   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7759     if (FLL->isExact())
7760       return;
7761   } else
7762     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7763       if (FLR->isExact())
7764         return;
7765 
7766   // Check for comparisons with builtin types.
7767   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7768     if (CL->getBuiltinCallee())
7769       return;
7770 
7771   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7772     if (CR->getBuiltinCallee())
7773       return;
7774 
7775   // Emit the diagnostic.
7776   Diag(Loc, diag::warn_floatingpoint_eq)
7777     << LHS->getSourceRange() << RHS->getSourceRange();
7778 }
7779 
7780 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7781 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7782 
7783 namespace {
7784 
7785 /// Structure recording the 'active' range of an integer-valued
7786 /// expression.
7787 struct IntRange {
7788   /// The number of bits active in the int.
7789   unsigned Width;
7790 
7791   /// True if the int is known not to have negative values.
7792   bool NonNegative;
7793 
7794   IntRange(unsigned Width, bool NonNegative)
7795     : Width(Width), NonNegative(NonNegative)
7796   {}
7797 
7798   /// Returns the range of the bool type.
7799   static IntRange forBoolType() {
7800     return IntRange(1, true);
7801   }
7802 
7803   /// Returns the range of an opaque value of the given integral type.
7804   static IntRange forValueOfType(ASTContext &C, QualType T) {
7805     return forValueOfCanonicalType(C,
7806                           T->getCanonicalTypeInternal().getTypePtr());
7807   }
7808 
7809   /// Returns the range of an opaque value of a canonical integral type.
7810   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
7811     assert(T->isCanonicalUnqualified());
7812 
7813     if (const VectorType *VT = dyn_cast<VectorType>(T))
7814       T = VT->getElementType().getTypePtr();
7815     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7816       T = CT->getElementType().getTypePtr();
7817     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7818       T = AT->getValueType().getTypePtr();
7819 
7820     // For enum types, use the known bit width of the enumerators.
7821     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
7822       EnumDecl *Enum = ET->getDecl();
7823       if (!Enum->isCompleteDefinition())
7824         return IntRange(C.getIntWidth(QualType(T, 0)), false);
7825 
7826       unsigned NumPositive = Enum->getNumPositiveBits();
7827       unsigned NumNegative = Enum->getNumNegativeBits();
7828 
7829       if (NumNegative == 0)
7830         return IntRange(NumPositive, true/*NonNegative*/);
7831       else
7832         return IntRange(std::max(NumPositive + 1, NumNegative),
7833                         false/*NonNegative*/);
7834     }
7835 
7836     const BuiltinType *BT = cast<BuiltinType>(T);
7837     assert(BT->isInteger());
7838 
7839     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7840   }
7841 
7842   /// Returns the "target" range of a canonical integral type, i.e.
7843   /// the range of values expressible in the type.
7844   ///
7845   /// This matches forValueOfCanonicalType except that enums have the
7846   /// full range of their type, not the range of their enumerators.
7847   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7848     assert(T->isCanonicalUnqualified());
7849 
7850     if (const VectorType *VT = dyn_cast<VectorType>(T))
7851       T = VT->getElementType().getTypePtr();
7852     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7853       T = CT->getElementType().getTypePtr();
7854     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7855       T = AT->getValueType().getTypePtr();
7856     if (const EnumType *ET = dyn_cast<EnumType>(T))
7857       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
7858 
7859     const BuiltinType *BT = cast<BuiltinType>(T);
7860     assert(BT->isInteger());
7861 
7862     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7863   }
7864 
7865   /// Returns the supremum of two ranges: i.e. their conservative merge.
7866   static IntRange join(IntRange L, IntRange R) {
7867     return IntRange(std::max(L.Width, R.Width),
7868                     L.NonNegative && R.NonNegative);
7869   }
7870 
7871   /// Returns the infinum of two ranges: i.e. their aggressive merge.
7872   static IntRange meet(IntRange L, IntRange R) {
7873     return IntRange(std::min(L.Width, R.Width),
7874                     L.NonNegative || R.NonNegative);
7875   }
7876 };
7877 
7878 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
7879   if (value.isSigned() && value.isNegative())
7880     return IntRange(value.getMinSignedBits(), false);
7881 
7882   if (value.getBitWidth() > MaxWidth)
7883     value = value.trunc(MaxWidth);
7884 
7885   // isNonNegative() just checks the sign bit without considering
7886   // signedness.
7887   return IntRange(value.getActiveBits(), true);
7888 }
7889 
7890 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7891                        unsigned MaxWidth) {
7892   if (result.isInt())
7893     return GetValueRange(C, result.getInt(), MaxWidth);
7894 
7895   if (result.isVector()) {
7896     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7897     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7898       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7899       R = IntRange::join(R, El);
7900     }
7901     return R;
7902   }
7903 
7904   if (result.isComplexInt()) {
7905     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7906     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7907     return IntRange::join(R, I);
7908   }
7909 
7910   // This can happen with lossless casts to intptr_t of "based" lvalues.
7911   // Assume it might use arbitrary bits.
7912   // FIXME: The only reason we need to pass the type in here is to get
7913   // the sign right on this one case.  It would be nice if APValue
7914   // preserved this.
7915   assert(result.isLValue() || result.isAddrLabelDiff());
7916   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
7917 }
7918 
7919 QualType GetExprType(const Expr *E) {
7920   QualType Ty = E->getType();
7921   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7922     Ty = AtomicRHS->getValueType();
7923   return Ty;
7924 }
7925 
7926 /// Pseudo-evaluate the given integer expression, estimating the
7927 /// range of values it might take.
7928 ///
7929 /// \param MaxWidth - the width to which the value will be truncated
7930 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
7931   E = E->IgnoreParens();
7932 
7933   // Try a full evaluation first.
7934   Expr::EvalResult result;
7935   if (E->EvaluateAsRValue(result, C))
7936     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
7937 
7938   // I think we only want to look through implicit casts here; if the
7939   // user has an explicit widening cast, we should treat the value as
7940   // being of the new, wider type.
7941   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
7942     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
7943       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7944 
7945     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
7946 
7947     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7948                          CE->getCastKind() == CK_BooleanToSignedIntegral;
7949 
7950     // Assume that non-integer casts can span the full range of the type.
7951     if (!isIntegerCast)
7952       return OutputTypeRange;
7953 
7954     IntRange SubRange
7955       = GetExprRange(C, CE->getSubExpr(),
7956                      std::min(MaxWidth, OutputTypeRange.Width));
7957 
7958     // Bail out if the subexpr's range is as wide as the cast type.
7959     if (SubRange.Width >= OutputTypeRange.Width)
7960       return OutputTypeRange;
7961 
7962     // Otherwise, we take the smaller width, and we're non-negative if
7963     // either the output type or the subexpr is.
7964     return IntRange(SubRange.Width,
7965                     SubRange.NonNegative || OutputTypeRange.NonNegative);
7966   }
7967 
7968   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
7969     // If we can fold the condition, just take that operand.
7970     bool CondResult;
7971     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7972       return GetExprRange(C, CondResult ? CO->getTrueExpr()
7973                                         : CO->getFalseExpr(),
7974                           MaxWidth);
7975 
7976     // Otherwise, conservatively merge.
7977     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7978     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7979     return IntRange::join(L, R);
7980   }
7981 
7982   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
7983     switch (BO->getOpcode()) {
7984 
7985     // Boolean-valued operations are single-bit and positive.
7986     case BO_LAnd:
7987     case BO_LOr:
7988     case BO_LT:
7989     case BO_GT:
7990     case BO_LE:
7991     case BO_GE:
7992     case BO_EQ:
7993     case BO_NE:
7994       return IntRange::forBoolType();
7995 
7996     // The type of the assignments is the type of the LHS, so the RHS
7997     // is not necessarily the same type.
7998     case BO_MulAssign:
7999     case BO_DivAssign:
8000     case BO_RemAssign:
8001     case BO_AddAssign:
8002     case BO_SubAssign:
8003     case BO_XorAssign:
8004     case BO_OrAssign:
8005       // TODO: bitfields?
8006       return IntRange::forValueOfType(C, GetExprType(E));
8007 
8008     // Simple assignments just pass through the RHS, which will have
8009     // been coerced to the LHS type.
8010     case BO_Assign:
8011       // TODO: bitfields?
8012       return GetExprRange(C, BO->getRHS(), MaxWidth);
8013 
8014     // Operations with opaque sources are black-listed.
8015     case BO_PtrMemD:
8016     case BO_PtrMemI:
8017       return IntRange::forValueOfType(C, GetExprType(E));
8018 
8019     // Bitwise-and uses the *infinum* of the two source ranges.
8020     case BO_And:
8021     case BO_AndAssign:
8022       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8023                             GetExprRange(C, BO->getRHS(), MaxWidth));
8024 
8025     // Left shift gets black-listed based on a judgement call.
8026     case BO_Shl:
8027       // ...except that we want to treat '1 << (blah)' as logically
8028       // positive.  It's an important idiom.
8029       if (IntegerLiteral *I
8030             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8031         if (I->getValue() == 1) {
8032           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8033           return IntRange(R.Width, /*NonNegative*/ true);
8034         }
8035       }
8036       // fallthrough
8037 
8038     case BO_ShlAssign:
8039       return IntRange::forValueOfType(C, GetExprType(E));
8040 
8041     // Right shift by a constant can narrow its left argument.
8042     case BO_Shr:
8043     case BO_ShrAssign: {
8044       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8045 
8046       // If the shift amount is a positive constant, drop the width by
8047       // that much.
8048       llvm::APSInt shift;
8049       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8050           shift.isNonNegative()) {
8051         unsigned zext = shift.getZExtValue();
8052         if (zext >= L.Width)
8053           L.Width = (L.NonNegative ? 0 : 1);
8054         else
8055           L.Width -= zext;
8056       }
8057 
8058       return L;
8059     }
8060 
8061     // Comma acts as its right operand.
8062     case BO_Comma:
8063       return GetExprRange(C, BO->getRHS(), MaxWidth);
8064 
8065     // Black-list pointer subtractions.
8066     case BO_Sub:
8067       if (BO->getLHS()->getType()->isPointerType())
8068         return IntRange::forValueOfType(C, GetExprType(E));
8069       break;
8070 
8071     // The width of a division result is mostly determined by the size
8072     // of the LHS.
8073     case BO_Div: {
8074       // Don't 'pre-truncate' the operands.
8075       unsigned opWidth = C.getIntWidth(GetExprType(E));
8076       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8077 
8078       // If the divisor is constant, use that.
8079       llvm::APSInt divisor;
8080       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8081         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8082         if (log2 >= L.Width)
8083           L.Width = (L.NonNegative ? 0 : 1);
8084         else
8085           L.Width = std::min(L.Width - log2, MaxWidth);
8086         return L;
8087       }
8088 
8089       // Otherwise, just use the LHS's width.
8090       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8091       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8092     }
8093 
8094     // The result of a remainder can't be larger than the result of
8095     // either side.
8096     case BO_Rem: {
8097       // Don't 'pre-truncate' the operands.
8098       unsigned opWidth = C.getIntWidth(GetExprType(E));
8099       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8100       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8101 
8102       IntRange meet = IntRange::meet(L, R);
8103       meet.Width = std::min(meet.Width, MaxWidth);
8104       return meet;
8105     }
8106 
8107     // The default behavior is okay for these.
8108     case BO_Mul:
8109     case BO_Add:
8110     case BO_Xor:
8111     case BO_Or:
8112       break;
8113     }
8114 
8115     // The default case is to treat the operation as if it were closed
8116     // on the narrowest type that encompasses both operands.
8117     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8118     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8119     return IntRange::join(L, R);
8120   }
8121 
8122   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8123     switch (UO->getOpcode()) {
8124     // Boolean-valued operations are white-listed.
8125     case UO_LNot:
8126       return IntRange::forBoolType();
8127 
8128     // Operations with opaque sources are black-listed.
8129     case UO_Deref:
8130     case UO_AddrOf: // should be impossible
8131       return IntRange::forValueOfType(C, GetExprType(E));
8132 
8133     default:
8134       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8135     }
8136   }
8137 
8138   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8139     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8140 
8141   if (const auto *BitField = E->getSourceBitField())
8142     return IntRange(BitField->getBitWidthValue(C),
8143                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8144 
8145   return IntRange::forValueOfType(C, GetExprType(E));
8146 }
8147 
8148 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8149   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8150 }
8151 
8152 /// Checks whether the given value, which currently has the given
8153 /// source semantics, has the same value when coerced through the
8154 /// target semantics.
8155 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8156                           const llvm::fltSemantics &Src,
8157                           const llvm::fltSemantics &Tgt) {
8158   llvm::APFloat truncated = value;
8159 
8160   bool ignored;
8161   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8162   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8163 
8164   return truncated.bitwiseIsEqual(value);
8165 }
8166 
8167 /// Checks whether the given value, which currently has the given
8168 /// source semantics, has the same value when coerced through the
8169 /// target semantics.
8170 ///
8171 /// The value might be a vector of floats (or a complex number).
8172 bool IsSameFloatAfterCast(const APValue &value,
8173                           const llvm::fltSemantics &Src,
8174                           const llvm::fltSemantics &Tgt) {
8175   if (value.isFloat())
8176     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8177 
8178   if (value.isVector()) {
8179     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8180       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8181         return false;
8182     return true;
8183   }
8184 
8185   assert(value.isComplexFloat());
8186   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8187           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8188 }
8189 
8190 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8191 
8192 bool IsZero(Sema &S, Expr *E) {
8193   // Suppress cases where we are comparing against an enum constant.
8194   if (const DeclRefExpr *DR =
8195       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8196     if (isa<EnumConstantDecl>(DR->getDecl()))
8197       return false;
8198 
8199   // Suppress cases where the '0' value is expanded from a macro.
8200   if (E->getLocStart().isMacroID())
8201     return false;
8202 
8203   llvm::APSInt Value;
8204   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8205 }
8206 
8207 bool HasEnumType(Expr *E) {
8208   // Strip off implicit integral promotions.
8209   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8210     if (ICE->getCastKind() != CK_IntegralCast &&
8211         ICE->getCastKind() != CK_NoOp)
8212       break;
8213     E = ICE->getSubExpr();
8214   }
8215 
8216   return E->getType()->isEnumeralType();
8217 }
8218 
8219 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
8220   // Disable warning in template instantiations.
8221   if (!S.ActiveTemplateInstantiations.empty())
8222     return;
8223 
8224   BinaryOperatorKind op = E->getOpcode();
8225   if (E->isValueDependent())
8226     return;
8227 
8228   if (op == BO_LT && IsZero(S, E->getRHS())) {
8229     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8230       << "< 0" << "false" << HasEnumType(E->getLHS())
8231       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8232   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
8233     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8234       << ">= 0" << "true" << HasEnumType(E->getLHS())
8235       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8236   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
8237     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8238       << "0 >" << "false" << HasEnumType(E->getRHS())
8239       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8240   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
8241     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8242       << "0 <=" << "true" << HasEnumType(E->getRHS())
8243       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8244   }
8245 }
8246 
8247 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8248                                   Expr *Other, const llvm::APSInt &Value,
8249                                   bool RhsConstant) {
8250   // Disable warning in template instantiations.
8251   if (!S.ActiveTemplateInstantiations.empty())
8252     return;
8253 
8254   // TODO: Investigate using GetExprRange() to get tighter bounds
8255   // on the bit ranges.
8256   QualType OtherT = Other->getType();
8257   if (const auto *AT = OtherT->getAs<AtomicType>())
8258     OtherT = AT->getValueType();
8259   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8260   unsigned OtherWidth = OtherRange.Width;
8261 
8262   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8263 
8264   // 0 values are handled later by CheckTrivialUnsignedComparison().
8265   if ((Value == 0) && (!OtherIsBooleanType))
8266     return;
8267 
8268   BinaryOperatorKind op = E->getOpcode();
8269   bool IsTrue = true;
8270 
8271   // Used for diagnostic printout.
8272   enum {
8273     LiteralConstant = 0,
8274     CXXBoolLiteralTrue,
8275     CXXBoolLiteralFalse
8276   } LiteralOrBoolConstant = LiteralConstant;
8277 
8278   if (!OtherIsBooleanType) {
8279     QualType ConstantT = Constant->getType();
8280     QualType CommonT = E->getLHS()->getType();
8281 
8282     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8283       return;
8284     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8285            "comparison with non-integer type");
8286 
8287     bool ConstantSigned = ConstantT->isSignedIntegerType();
8288     bool CommonSigned = CommonT->isSignedIntegerType();
8289 
8290     bool EqualityOnly = false;
8291 
8292     if (CommonSigned) {
8293       // The common type is signed, therefore no signed to unsigned conversion.
8294       if (!OtherRange.NonNegative) {
8295         // Check that the constant is representable in type OtherT.
8296         if (ConstantSigned) {
8297           if (OtherWidth >= Value.getMinSignedBits())
8298             return;
8299         } else { // !ConstantSigned
8300           if (OtherWidth >= Value.getActiveBits() + 1)
8301             return;
8302         }
8303       } else { // !OtherSigned
8304                // Check that the constant is representable in type OtherT.
8305         // Negative values are out of range.
8306         if (ConstantSigned) {
8307           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8308             return;
8309         } else { // !ConstantSigned
8310           if (OtherWidth >= Value.getActiveBits())
8311             return;
8312         }
8313       }
8314     } else { // !CommonSigned
8315       if (OtherRange.NonNegative) {
8316         if (OtherWidth >= Value.getActiveBits())
8317           return;
8318       } else { // OtherSigned
8319         assert(!ConstantSigned &&
8320                "Two signed types converted to unsigned types.");
8321         // Check to see if the constant is representable in OtherT.
8322         if (OtherWidth > Value.getActiveBits())
8323           return;
8324         // Check to see if the constant is equivalent to a negative value
8325         // cast to CommonT.
8326         if (S.Context.getIntWidth(ConstantT) ==
8327                 S.Context.getIntWidth(CommonT) &&
8328             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8329           return;
8330         // The constant value rests between values that OtherT can represent
8331         // after conversion.  Relational comparison still works, but equality
8332         // comparisons will be tautological.
8333         EqualityOnly = true;
8334       }
8335     }
8336 
8337     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8338 
8339     if (op == BO_EQ || op == BO_NE) {
8340       IsTrue = op == BO_NE;
8341     } else if (EqualityOnly) {
8342       return;
8343     } else if (RhsConstant) {
8344       if (op == BO_GT || op == BO_GE)
8345         IsTrue = !PositiveConstant;
8346       else // op == BO_LT || op == BO_LE
8347         IsTrue = PositiveConstant;
8348     } else {
8349       if (op == BO_LT || op == BO_LE)
8350         IsTrue = !PositiveConstant;
8351       else // op == BO_GT || op == BO_GE
8352         IsTrue = PositiveConstant;
8353     }
8354   } else {
8355     // Other isKnownToHaveBooleanValue
8356     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8357     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8358     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8359 
8360     static const struct LinkedConditions {
8361       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8362       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8363       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8364       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8365       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8366       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8367 
8368     } TruthTable = {
8369         // Constant on LHS.              | Constant on RHS.              |
8370         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
8371         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8372         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8373         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8374         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8375         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8376         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8377       };
8378 
8379     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8380 
8381     enum ConstantValue ConstVal = Zero;
8382     if (Value.isUnsigned() || Value.isNonNegative()) {
8383       if (Value == 0) {
8384         LiteralOrBoolConstant =
8385             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8386         ConstVal = Zero;
8387       } else if (Value == 1) {
8388         LiteralOrBoolConstant =
8389             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8390         ConstVal = One;
8391       } else {
8392         LiteralOrBoolConstant = LiteralConstant;
8393         ConstVal = GT_One;
8394       }
8395     } else {
8396       ConstVal = LT_Zero;
8397     }
8398 
8399     CompareBoolWithConstantResult CmpRes;
8400 
8401     switch (op) {
8402     case BO_LT:
8403       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8404       break;
8405     case BO_GT:
8406       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8407       break;
8408     case BO_LE:
8409       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8410       break;
8411     case BO_GE:
8412       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8413       break;
8414     case BO_EQ:
8415       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8416       break;
8417     case BO_NE:
8418       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8419       break;
8420     default:
8421       CmpRes = Unkwn;
8422       break;
8423     }
8424 
8425     if (CmpRes == AFals) {
8426       IsTrue = false;
8427     } else if (CmpRes == ATrue) {
8428       IsTrue = true;
8429     } else {
8430       return;
8431     }
8432   }
8433 
8434   // If this is a comparison to an enum constant, include that
8435   // constant in the diagnostic.
8436   const EnumConstantDecl *ED = nullptr;
8437   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8438     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8439 
8440   SmallString<64> PrettySourceValue;
8441   llvm::raw_svector_ostream OS(PrettySourceValue);
8442   if (ED)
8443     OS << '\'' << *ED << "' (" << Value << ")";
8444   else
8445     OS << Value;
8446 
8447   S.DiagRuntimeBehavior(
8448     E->getOperatorLoc(), E,
8449     S.PDiag(diag::warn_out_of_range_compare)
8450         << OS.str() << LiteralOrBoolConstant
8451         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8452         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8453 }
8454 
8455 /// Analyze the operands of the given comparison.  Implements the
8456 /// fallback case from AnalyzeComparison.
8457 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8458   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8459   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8460 }
8461 
8462 /// \brief Implements -Wsign-compare.
8463 ///
8464 /// \param E the binary operator to check for warnings
8465 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8466   // The type the comparison is being performed in.
8467   QualType T = E->getLHS()->getType();
8468 
8469   // Only analyze comparison operators where both sides have been converted to
8470   // the same type.
8471   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8472     return AnalyzeImpConvsInComparison(S, E);
8473 
8474   // Don't analyze value-dependent comparisons directly.
8475   if (E->isValueDependent())
8476     return AnalyzeImpConvsInComparison(S, E);
8477 
8478   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8479   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8480 
8481   bool IsComparisonConstant = false;
8482 
8483   // Check whether an integer constant comparison results in a value
8484   // of 'true' or 'false'.
8485   if (T->isIntegralType(S.Context)) {
8486     llvm::APSInt RHSValue;
8487     bool IsRHSIntegralLiteral =
8488       RHS->isIntegerConstantExpr(RHSValue, S.Context);
8489     llvm::APSInt LHSValue;
8490     bool IsLHSIntegralLiteral =
8491       LHS->isIntegerConstantExpr(LHSValue, S.Context);
8492     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8493         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8494     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8495       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8496     else
8497       IsComparisonConstant =
8498         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8499   } else if (!T->hasUnsignedIntegerRepresentation())
8500       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8501 
8502   // We don't do anything special if this isn't an unsigned integral
8503   // comparison:  we're only interested in integral comparisons, and
8504   // signed comparisons only happen in cases we don't care to warn about.
8505   //
8506   // We also don't care about value-dependent expressions or expressions
8507   // whose result is a constant.
8508   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
8509     return AnalyzeImpConvsInComparison(S, E);
8510 
8511   // Check to see if one of the (unmodified) operands is of different
8512   // signedness.
8513   Expr *signedOperand, *unsignedOperand;
8514   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8515     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8516            "unsigned comparison between two signed integer expressions?");
8517     signedOperand = LHS;
8518     unsignedOperand = RHS;
8519   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8520     signedOperand = RHS;
8521     unsignedOperand = LHS;
8522   } else {
8523     CheckTrivialUnsignedComparison(S, E);
8524     return AnalyzeImpConvsInComparison(S, E);
8525   }
8526 
8527   // Otherwise, calculate the effective range of the signed operand.
8528   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8529 
8530   // Go ahead and analyze implicit conversions in the operands.  Note
8531   // that we skip the implicit conversions on both sides.
8532   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8533   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8534 
8535   // If the signed range is non-negative, -Wsign-compare won't fire,
8536   // but we should still check for comparisons which are always true
8537   // or false.
8538   if (signedRange.NonNegative)
8539     return CheckTrivialUnsignedComparison(S, E);
8540 
8541   // For (in)equality comparisons, if the unsigned operand is a
8542   // constant which cannot collide with a overflowed signed operand,
8543   // then reinterpreting the signed operand as unsigned will not
8544   // change the result of the comparison.
8545   if (E->isEqualityOp()) {
8546     unsigned comparisonWidth = S.Context.getIntWidth(T);
8547     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8548 
8549     // We should never be unable to prove that the unsigned operand is
8550     // non-negative.
8551     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8552 
8553     if (unsignedRange.Width < comparisonWidth)
8554       return;
8555   }
8556 
8557   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8558     S.PDiag(diag::warn_mixed_sign_comparison)
8559       << LHS->getType() << RHS->getType()
8560       << LHS->getSourceRange() << RHS->getSourceRange());
8561 }
8562 
8563 /// Analyzes an attempt to assign the given value to a bitfield.
8564 ///
8565 /// Returns true if there was something fishy about the attempt.
8566 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8567                                SourceLocation InitLoc) {
8568   assert(Bitfield->isBitField());
8569   if (Bitfield->isInvalidDecl())
8570     return false;
8571 
8572   // White-list bool bitfields.
8573   QualType BitfieldType = Bitfield->getType();
8574   if (BitfieldType->isBooleanType())
8575      return false;
8576 
8577   if (BitfieldType->isEnumeralType()) {
8578     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8579     // If the underlying enum type was not explicitly specified as an unsigned
8580     // type and the enum contain only positive values, MSVC++ will cause an
8581     // inconsistency by storing this as a signed type.
8582     if (S.getLangOpts().CPlusPlus11 &&
8583         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8584         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8585         BitfieldEnumDecl->getNumNegativeBits() == 0) {
8586       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8587         << BitfieldEnumDecl->getNameAsString();
8588     }
8589   }
8590 
8591   if (Bitfield->getType()->isBooleanType())
8592     return false;
8593 
8594   // Ignore value- or type-dependent expressions.
8595   if (Bitfield->getBitWidth()->isValueDependent() ||
8596       Bitfield->getBitWidth()->isTypeDependent() ||
8597       Init->isValueDependent() ||
8598       Init->isTypeDependent())
8599     return false;
8600 
8601   Expr *OriginalInit = Init->IgnoreParenImpCasts();
8602 
8603   llvm::APSInt Value;
8604   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
8605     return false;
8606 
8607   unsigned OriginalWidth = Value.getBitWidth();
8608   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8609 
8610   if (!Value.isSigned() || Value.isNegative())
8611     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8612       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8613         OriginalWidth = Value.getMinSignedBits();
8614 
8615   if (OriginalWidth <= FieldWidth)
8616     return false;
8617 
8618   // Compute the value which the bitfield will contain.
8619   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8620   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
8621 
8622   // Check whether the stored value is equal to the original value.
8623   TruncatedValue = TruncatedValue.extend(OriginalWidth);
8624   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8625     return false;
8626 
8627   // Special-case bitfields of width 1: booleans are naturally 0/1, and
8628   // therefore don't strictly fit into a signed bitfield of width 1.
8629   if (FieldWidth == 1 && Value == 1)
8630     return false;
8631 
8632   std::string PrettyValue = Value.toString(10);
8633   std::string PrettyTrunc = TruncatedValue.toString(10);
8634 
8635   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8636     << PrettyValue << PrettyTrunc << OriginalInit->getType()
8637     << Init->getSourceRange();
8638 
8639   return true;
8640 }
8641 
8642 /// Analyze the given simple or compound assignment for warning-worthy
8643 /// operations.
8644 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8645   // Just recurse on the LHS.
8646   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8647 
8648   // We want to recurse on the RHS as normal unless we're assigning to
8649   // a bitfield.
8650   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8651     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8652                                   E->getOperatorLoc())) {
8653       // Recurse, ignoring any implicit conversions on the RHS.
8654       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8655                                         E->getOperatorLoc());
8656     }
8657   }
8658 
8659   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8660 }
8661 
8662 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8663 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8664                      SourceLocation CContext, unsigned diag,
8665                      bool pruneControlFlow = false) {
8666   if (pruneControlFlow) {
8667     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8668                           S.PDiag(diag)
8669                             << SourceType << T << E->getSourceRange()
8670                             << SourceRange(CContext));
8671     return;
8672   }
8673   S.Diag(E->getExprLoc(), diag)
8674     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8675 }
8676 
8677 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8678 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8679                      unsigned diag, bool pruneControlFlow = false) {
8680   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8681 }
8682 
8683 
8684 /// Diagnose an implicit cast from a floating point value to an integer value.
8685 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8686 
8687                              SourceLocation CContext) {
8688   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8689   const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8690 
8691   Expr *InnerE = E->IgnoreParenImpCasts();
8692   // We also want to warn on, e.g., "int i = -1.234"
8693   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8694     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8695       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8696 
8697   const bool IsLiteral =
8698       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8699 
8700   llvm::APFloat Value(0.0);
8701   bool IsConstant =
8702     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8703   if (!IsConstant) {
8704     return DiagnoseImpCast(S, E, T, CContext,
8705                            diag::warn_impcast_float_integer, PruneWarnings);
8706   }
8707 
8708   bool isExact = false;
8709 
8710   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8711                             T->hasUnsignedIntegerRepresentation());
8712   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8713                              &isExact) == llvm::APFloat::opOK &&
8714       isExact) {
8715     if (IsLiteral) return;
8716     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8717                            PruneWarnings);
8718   }
8719 
8720   unsigned DiagID = 0;
8721   if (IsLiteral) {
8722     // Warn on floating point literal to integer.
8723     DiagID = diag::warn_impcast_literal_float_to_integer;
8724   } else if (IntegerValue == 0) {
8725     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
8726       return DiagnoseImpCast(S, E, T, CContext,
8727                              diag::warn_impcast_float_integer, PruneWarnings);
8728     }
8729     // Warn on non-zero to zero conversion.
8730     DiagID = diag::warn_impcast_float_to_integer_zero;
8731   } else {
8732     if (IntegerValue.isUnsigned()) {
8733       if (!IntegerValue.isMaxValue()) {
8734         return DiagnoseImpCast(S, E, T, CContext,
8735                                diag::warn_impcast_float_integer, PruneWarnings);
8736       }
8737     } else {  // IntegerValue.isSigned()
8738       if (!IntegerValue.isMaxSignedValue() &&
8739           !IntegerValue.isMinSignedValue()) {
8740         return DiagnoseImpCast(S, E, T, CContext,
8741                                diag::warn_impcast_float_integer, PruneWarnings);
8742       }
8743     }
8744     // Warn on evaluatable floating point expression to integer conversion.
8745     DiagID = diag::warn_impcast_float_to_integer;
8746   }
8747 
8748   // FIXME: Force the precision of the source value down so we don't print
8749   // digits which are usually useless (we don't really care here if we
8750   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
8751   // would automatically print the shortest representation, but it's a bit
8752   // tricky to implement.
8753   SmallString<16> PrettySourceValue;
8754   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8755   precision = (precision * 59 + 195) / 196;
8756   Value.toString(PrettySourceValue, precision);
8757 
8758   SmallString<16> PrettyTargetValue;
8759   if (IsBool)
8760     PrettyTargetValue = Value.isZero() ? "false" : "true";
8761   else
8762     IntegerValue.toString(PrettyTargetValue);
8763 
8764   if (PruneWarnings) {
8765     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8766                           S.PDiag(DiagID)
8767                               << E->getType() << T.getUnqualifiedType()
8768                               << PrettySourceValue << PrettyTargetValue
8769                               << E->getSourceRange() << SourceRange(CContext));
8770   } else {
8771     S.Diag(E->getExprLoc(), DiagID)
8772         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8773         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8774   }
8775 }
8776 
8777 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8778   if (!Range.Width) return "0";
8779 
8780   llvm::APSInt ValueInRange = Value;
8781   ValueInRange.setIsSigned(!Range.NonNegative);
8782   ValueInRange = ValueInRange.trunc(Range.Width);
8783   return ValueInRange.toString(10);
8784 }
8785 
8786 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
8787   if (!isa<ImplicitCastExpr>(Ex))
8788     return false;
8789 
8790   Expr *InnerE = Ex->IgnoreParenImpCasts();
8791   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8792   const Type *Source =
8793     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8794   if (Target->isDependentType())
8795     return false;
8796 
8797   const BuiltinType *FloatCandidateBT =
8798     dyn_cast<BuiltinType>(ToBool ? Source : Target);
8799   const Type *BoolCandidateType = ToBool ? Target : Source;
8800 
8801   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8802           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8803 }
8804 
8805 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8806                                       SourceLocation CC) {
8807   unsigned NumArgs = TheCall->getNumArgs();
8808   for (unsigned i = 0; i < NumArgs; ++i) {
8809     Expr *CurrA = TheCall->getArg(i);
8810     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8811       continue;
8812 
8813     bool IsSwapped = ((i > 0) &&
8814         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8815     IsSwapped |= ((i < (NumArgs - 1)) &&
8816         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8817     if (IsSwapped) {
8818       // Warn on this floating-point to bool conversion.
8819       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8820                       CurrA->getType(), CC,
8821                       diag::warn_impcast_floating_point_to_bool);
8822     }
8823   }
8824 }
8825 
8826 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
8827   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8828                         E->getExprLoc()))
8829     return;
8830 
8831   // Don't warn on functions which have return type nullptr_t.
8832   if (isa<CallExpr>(E))
8833     return;
8834 
8835   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8836   const Expr::NullPointerConstantKind NullKind =
8837       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8838   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8839     return;
8840 
8841   // Return if target type is a safe conversion.
8842   if (T->isAnyPointerType() || T->isBlockPointerType() ||
8843       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8844     return;
8845 
8846   SourceLocation Loc = E->getSourceRange().getBegin();
8847 
8848   // Venture through the macro stacks to get to the source of macro arguments.
8849   // The new location is a better location than the complete location that was
8850   // passed in.
8851   while (S.SourceMgr.isMacroArgExpansion(Loc))
8852     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8853 
8854   while (S.SourceMgr.isMacroArgExpansion(CC))
8855     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8856 
8857   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
8858   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8859     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8860         Loc, S.SourceMgr, S.getLangOpts());
8861     if (MacroName == "NULL")
8862       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
8863   }
8864 
8865   // Only warn if the null and context location are in the same macro expansion.
8866   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8867     return;
8868 
8869   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8870       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8871       << FixItHint::CreateReplacement(Loc,
8872                                       S.getFixItZeroLiteralForType(T, Loc));
8873 }
8874 
8875 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8876                            ObjCArrayLiteral *ArrayLiteral);
8877 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8878                                 ObjCDictionaryLiteral *DictionaryLiteral);
8879 
8880 /// Check a single element within a collection literal against the
8881 /// target element type.
8882 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8883                                        Expr *Element, unsigned ElementKind) {
8884   // Skip a bitcast to 'id' or qualified 'id'.
8885   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8886     if (ICE->getCastKind() == CK_BitCast &&
8887         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8888       Element = ICE->getSubExpr();
8889   }
8890 
8891   QualType ElementType = Element->getType();
8892   ExprResult ElementResult(Element);
8893   if (ElementType->getAs<ObjCObjectPointerType>() &&
8894       S.CheckSingleAssignmentConstraints(TargetElementType,
8895                                          ElementResult,
8896                                          false, false)
8897         != Sema::Compatible) {
8898     S.Diag(Element->getLocStart(),
8899            diag::warn_objc_collection_literal_element)
8900       << ElementType << ElementKind << TargetElementType
8901       << Element->getSourceRange();
8902   }
8903 
8904   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8905     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8906   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8907     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8908 }
8909 
8910 /// Check an Objective-C array literal being converted to the given
8911 /// target type.
8912 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8913                            ObjCArrayLiteral *ArrayLiteral) {
8914   if (!S.NSArrayDecl)
8915     return;
8916 
8917   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8918   if (!TargetObjCPtr)
8919     return;
8920 
8921   if (TargetObjCPtr->isUnspecialized() ||
8922       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8923         != S.NSArrayDecl->getCanonicalDecl())
8924     return;
8925 
8926   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8927   if (TypeArgs.size() != 1)
8928     return;
8929 
8930   QualType TargetElementType = TypeArgs[0];
8931   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8932     checkObjCCollectionLiteralElement(S, TargetElementType,
8933                                       ArrayLiteral->getElement(I),
8934                                       0);
8935   }
8936 }
8937 
8938 /// Check an Objective-C dictionary literal being converted to the given
8939 /// target type.
8940 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8941                                 ObjCDictionaryLiteral *DictionaryLiteral) {
8942   if (!S.NSDictionaryDecl)
8943     return;
8944 
8945   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8946   if (!TargetObjCPtr)
8947     return;
8948 
8949   if (TargetObjCPtr->isUnspecialized() ||
8950       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8951         != S.NSDictionaryDecl->getCanonicalDecl())
8952     return;
8953 
8954   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8955   if (TypeArgs.size() != 2)
8956     return;
8957 
8958   QualType TargetKeyType = TypeArgs[0];
8959   QualType TargetObjectType = TypeArgs[1];
8960   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8961     auto Element = DictionaryLiteral->getKeyValueElement(I);
8962     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8963     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8964   }
8965 }
8966 
8967 // Helper function to filter out cases for constant width constant conversion.
8968 // Don't warn on char array initialization or for non-decimal values.
8969 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8970                                    SourceLocation CC) {
8971   // If initializing from a constant, and the constant starts with '0',
8972   // then it is a binary, octal, or hexadecimal.  Allow these constants
8973   // to fill all the bits, even if there is a sign change.
8974   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8975     const char FirstLiteralCharacter =
8976         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8977     if (FirstLiteralCharacter == '0')
8978       return false;
8979   }
8980 
8981   // If the CC location points to a '{', and the type is char, then assume
8982   // assume it is an array initialization.
8983   if (CC.isValid() && T->isCharType()) {
8984     const char FirstContextCharacter =
8985         S.getSourceManager().getCharacterData(CC)[0];
8986     if (FirstContextCharacter == '{')
8987       return false;
8988   }
8989 
8990   return true;
8991 }
8992 
8993 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
8994                              SourceLocation CC, bool *ICContext = nullptr) {
8995   if (E->isTypeDependent() || E->isValueDependent()) return;
8996 
8997   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8998   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8999   if (Source == Target) return;
9000   if (Target->isDependentType()) return;
9001 
9002   // If the conversion context location is invalid don't complain. We also
9003   // don't want to emit a warning if the issue occurs from the expansion of
9004   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9005   // delay this check as long as possible. Once we detect we are in that
9006   // scenario, we just return.
9007   if (CC.isInvalid())
9008     return;
9009 
9010   // Diagnose implicit casts to bool.
9011   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9012     if (isa<StringLiteral>(E))
9013       // Warn on string literal to bool.  Checks for string literals in logical
9014       // and expressions, for instance, assert(0 && "error here"), are
9015       // prevented by a check in AnalyzeImplicitConversions().
9016       return DiagnoseImpCast(S, E, T, CC,
9017                              diag::warn_impcast_string_literal_to_bool);
9018     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9019         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9020       // This covers the literal expressions that evaluate to Objective-C
9021       // objects.
9022       return DiagnoseImpCast(S, E, T, CC,
9023                              diag::warn_impcast_objective_c_literal_to_bool);
9024     }
9025     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9026       // Warn on pointer to bool conversion that is always true.
9027       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9028                                      SourceRange(CC));
9029     }
9030   }
9031 
9032   // Check implicit casts from Objective-C collection literals to specialized
9033   // collection types, e.g., NSArray<NSString *> *.
9034   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9035     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9036   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9037     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9038 
9039   // Strip vector types.
9040   if (isa<VectorType>(Source)) {
9041     if (!isa<VectorType>(Target)) {
9042       if (S.SourceMgr.isInSystemMacro(CC))
9043         return;
9044       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9045     }
9046 
9047     // If the vector cast is cast between two vectors of the same size, it is
9048     // a bitcast, not a conversion.
9049     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9050       return;
9051 
9052     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9053     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9054   }
9055   if (auto VecTy = dyn_cast<VectorType>(Target))
9056     Target = VecTy->getElementType().getTypePtr();
9057 
9058   // Strip complex types.
9059   if (isa<ComplexType>(Source)) {
9060     if (!isa<ComplexType>(Target)) {
9061       if (S.SourceMgr.isInSystemMacro(CC))
9062         return;
9063 
9064       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
9065     }
9066 
9067     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9068     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9069   }
9070 
9071   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9072   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9073 
9074   // If the source is floating point...
9075   if (SourceBT && SourceBT->isFloatingPoint()) {
9076     // ...and the target is floating point...
9077     if (TargetBT && TargetBT->isFloatingPoint()) {
9078       // ...then warn if we're dropping FP rank.
9079 
9080       // Builtin FP kinds are ordered by increasing FP rank.
9081       if (SourceBT->getKind() > TargetBT->getKind()) {
9082         // Don't warn about float constants that are precisely
9083         // representable in the target type.
9084         Expr::EvalResult result;
9085         if (E->EvaluateAsRValue(result, S.Context)) {
9086           // Value might be a float, a float vector, or a float complex.
9087           if (IsSameFloatAfterCast(result.Val,
9088                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9089                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9090             return;
9091         }
9092 
9093         if (S.SourceMgr.isInSystemMacro(CC))
9094           return;
9095 
9096         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9097       }
9098       // ... or possibly if we're increasing rank, too
9099       else if (TargetBT->getKind() > SourceBT->getKind()) {
9100         if (S.SourceMgr.isInSystemMacro(CC))
9101           return;
9102 
9103         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9104       }
9105       return;
9106     }
9107 
9108     // If the target is integral, always warn.
9109     if (TargetBT && TargetBT->isInteger()) {
9110       if (S.SourceMgr.isInSystemMacro(CC))
9111         return;
9112 
9113       DiagnoseFloatingImpCast(S, E, T, CC);
9114     }
9115 
9116     // Detect the case where a call result is converted from floating-point to
9117     // to bool, and the final argument to the call is converted from bool, to
9118     // discover this typo:
9119     //
9120     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9121     //
9122     // FIXME: This is an incredibly special case; is there some more general
9123     // way to detect this class of misplaced-parentheses bug?
9124     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9125       // Check last argument of function call to see if it is an
9126       // implicit cast from a type matching the type the result
9127       // is being cast to.
9128       CallExpr *CEx = cast<CallExpr>(E);
9129       if (unsigned NumArgs = CEx->getNumArgs()) {
9130         Expr *LastA = CEx->getArg(NumArgs - 1);
9131         Expr *InnerE = LastA->IgnoreParenImpCasts();
9132         if (isa<ImplicitCastExpr>(LastA) &&
9133             InnerE->getType()->isBooleanType()) {
9134           // Warn on this floating-point to bool conversion
9135           DiagnoseImpCast(S, E, T, CC,
9136                           diag::warn_impcast_floating_point_to_bool);
9137         }
9138       }
9139     }
9140     return;
9141   }
9142 
9143   DiagnoseNullConversion(S, E, T, CC);
9144 
9145   S.DiscardMisalignedMemberAddress(Target, E);
9146 
9147   if (!Source->isIntegerType() || !Target->isIntegerType())
9148     return;
9149 
9150   // TODO: remove this early return once the false positives for constant->bool
9151   // in templates, macros, etc, are reduced or removed.
9152   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9153     return;
9154 
9155   IntRange SourceRange = GetExprRange(S.Context, E);
9156   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9157 
9158   if (SourceRange.Width > TargetRange.Width) {
9159     // If the source is a constant, use a default-on diagnostic.
9160     // TODO: this should happen for bitfield stores, too.
9161     llvm::APSInt Value(32);
9162     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9163       if (S.SourceMgr.isInSystemMacro(CC))
9164         return;
9165 
9166       std::string PrettySourceValue = Value.toString(10);
9167       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9168 
9169       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9170         S.PDiag(diag::warn_impcast_integer_precision_constant)
9171             << PrettySourceValue << PrettyTargetValue
9172             << E->getType() << T << E->getSourceRange()
9173             << clang::SourceRange(CC));
9174       return;
9175     }
9176 
9177     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9178     if (S.SourceMgr.isInSystemMacro(CC))
9179       return;
9180 
9181     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9182       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9183                              /* pruneControlFlow */ true);
9184     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9185   }
9186 
9187   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9188       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9189     // Warn when doing a signed to signed conversion, warn if the positive
9190     // source value is exactly the width of the target type, which will
9191     // cause a negative value to be stored.
9192 
9193     llvm::APSInt Value;
9194     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9195         !S.SourceMgr.isInSystemMacro(CC)) {
9196       if (isSameWidthConstantConversion(S, E, T, CC)) {
9197         std::string PrettySourceValue = Value.toString(10);
9198         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9199 
9200         S.DiagRuntimeBehavior(
9201             E->getExprLoc(), E,
9202             S.PDiag(diag::warn_impcast_integer_precision_constant)
9203                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9204                 << E->getSourceRange() << clang::SourceRange(CC));
9205         return;
9206       }
9207     }
9208 
9209     // Fall through for non-constants to give a sign conversion warning.
9210   }
9211 
9212   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9213       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9214        SourceRange.Width == TargetRange.Width)) {
9215     if (S.SourceMgr.isInSystemMacro(CC))
9216       return;
9217 
9218     unsigned DiagID = diag::warn_impcast_integer_sign;
9219 
9220     // Traditionally, gcc has warned about this under -Wsign-compare.
9221     // We also want to warn about it in -Wconversion.
9222     // So if -Wconversion is off, use a completely identical diagnostic
9223     // in the sign-compare group.
9224     // The conditional-checking code will
9225     if (ICContext) {
9226       DiagID = diag::warn_impcast_integer_sign_conditional;
9227       *ICContext = true;
9228     }
9229 
9230     return DiagnoseImpCast(S, E, T, CC, DiagID);
9231   }
9232 
9233   // Diagnose conversions between different enumeration types.
9234   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9235   // type, to give us better diagnostics.
9236   QualType SourceType = E->getType();
9237   if (!S.getLangOpts().CPlusPlus) {
9238     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9239       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9240         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9241         SourceType = S.Context.getTypeDeclType(Enum);
9242         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9243       }
9244   }
9245 
9246   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9247     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9248       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9249           TargetEnum->getDecl()->hasNameForLinkage() &&
9250           SourceEnum != TargetEnum) {
9251         if (S.SourceMgr.isInSystemMacro(CC))
9252           return;
9253 
9254         return DiagnoseImpCast(S, E, SourceType, T, CC,
9255                                diag::warn_impcast_different_enum_types);
9256       }
9257 }
9258 
9259 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9260                               SourceLocation CC, QualType T);
9261 
9262 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9263                              SourceLocation CC, bool &ICContext) {
9264   E = E->IgnoreParenImpCasts();
9265 
9266   if (isa<ConditionalOperator>(E))
9267     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9268 
9269   AnalyzeImplicitConversions(S, E, CC);
9270   if (E->getType() != T)
9271     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9272 }
9273 
9274 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9275                               SourceLocation CC, QualType T) {
9276   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9277 
9278   bool Suspicious = false;
9279   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9280   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9281 
9282   // If -Wconversion would have warned about either of the candidates
9283   // for a signedness conversion to the context type...
9284   if (!Suspicious) return;
9285 
9286   // ...but it's currently ignored...
9287   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9288     return;
9289 
9290   // ...then check whether it would have warned about either of the
9291   // candidates for a signedness conversion to the condition type.
9292   if (E->getType() == T) return;
9293 
9294   Suspicious = false;
9295   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9296                           E->getType(), CC, &Suspicious);
9297   if (!Suspicious)
9298     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9299                             E->getType(), CC, &Suspicious);
9300 }
9301 
9302 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9303 /// Input argument E is a logical expression.
9304 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9305   if (S.getLangOpts().Bool)
9306     return;
9307   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9308 }
9309 
9310 /// AnalyzeImplicitConversions - Find and report any interesting
9311 /// implicit conversions in the given expression.  There are a couple
9312 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9313 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9314   QualType T = OrigE->getType();
9315   Expr *E = OrigE->IgnoreParenImpCasts();
9316 
9317   if (E->isTypeDependent() || E->isValueDependent())
9318     return;
9319 
9320   // For conditional operators, we analyze the arguments as if they
9321   // were being fed directly into the output.
9322   if (isa<ConditionalOperator>(E)) {
9323     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9324     CheckConditionalOperator(S, CO, CC, T);
9325     return;
9326   }
9327 
9328   // Check implicit argument conversions for function calls.
9329   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9330     CheckImplicitArgumentConversions(S, Call, CC);
9331 
9332   // Go ahead and check any implicit conversions we might have skipped.
9333   // The non-canonical typecheck is just an optimization;
9334   // CheckImplicitConversion will filter out dead implicit conversions.
9335   if (E->getType() != T)
9336     CheckImplicitConversion(S, E, T, CC);
9337 
9338   // Now continue drilling into this expression.
9339 
9340   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9341     // The bound subexpressions in a PseudoObjectExpr are not reachable
9342     // as transitive children.
9343     // FIXME: Use a more uniform representation for this.
9344     for (auto *SE : POE->semantics())
9345       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9346         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9347   }
9348 
9349   // Skip past explicit casts.
9350   if (isa<ExplicitCastExpr>(E)) {
9351     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9352     return AnalyzeImplicitConversions(S, E, CC);
9353   }
9354 
9355   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9356     // Do a somewhat different check with comparison operators.
9357     if (BO->isComparisonOp())
9358       return AnalyzeComparison(S, BO);
9359 
9360     // And with simple assignments.
9361     if (BO->getOpcode() == BO_Assign)
9362       return AnalyzeAssignment(S, BO);
9363   }
9364 
9365   // These break the otherwise-useful invariant below.  Fortunately,
9366   // we don't really need to recurse into them, because any internal
9367   // expressions should have been analyzed already when they were
9368   // built into statements.
9369   if (isa<StmtExpr>(E)) return;
9370 
9371   // Don't descend into unevaluated contexts.
9372   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9373 
9374   // Now just recurse over the expression's children.
9375   CC = E->getExprLoc();
9376   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9377   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9378   for (Stmt *SubStmt : E->children()) {
9379     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9380     if (!ChildExpr)
9381       continue;
9382 
9383     if (IsLogicalAndOperator &&
9384         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9385       // Ignore checking string literals that are in logical and operators.
9386       // This is a common pattern for asserts.
9387       continue;
9388     AnalyzeImplicitConversions(S, ChildExpr, CC);
9389   }
9390 
9391   if (BO && BO->isLogicalOp()) {
9392     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9393     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9394       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9395 
9396     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9397     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9398       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9399   }
9400 
9401   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9402     if (U->getOpcode() == UO_LNot)
9403       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9404 }
9405 
9406 } // end anonymous namespace
9407 
9408 /// Diagnose integer type and any valid implicit convertion to it.
9409 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9410   // Taking into account implicit conversions,
9411   // allow any integer.
9412   if (!E->getType()->isIntegerType()) {
9413     S.Diag(E->getLocStart(),
9414            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9415     return true;
9416   }
9417   // Potentially emit standard warnings for implicit conversions if enabled
9418   // using -Wconversion.
9419   CheckImplicitConversion(S, E, IntT, E->getLocStart());
9420   return false;
9421 }
9422 
9423 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9424 // Returns true when emitting a warning about taking the address of a reference.
9425 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9426                               const PartialDiagnostic &PD) {
9427   E = E->IgnoreParenImpCasts();
9428 
9429   const FunctionDecl *FD = nullptr;
9430 
9431   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9432     if (!DRE->getDecl()->getType()->isReferenceType())
9433       return false;
9434   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9435     if (!M->getMemberDecl()->getType()->isReferenceType())
9436       return false;
9437   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9438     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9439       return false;
9440     FD = Call->getDirectCallee();
9441   } else {
9442     return false;
9443   }
9444 
9445   SemaRef.Diag(E->getExprLoc(), PD);
9446 
9447   // If possible, point to location of function.
9448   if (FD) {
9449     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9450   }
9451 
9452   return true;
9453 }
9454 
9455 // Returns true if the SourceLocation is expanded from any macro body.
9456 // Returns false if the SourceLocation is invalid, is from not in a macro
9457 // expansion, or is from expanded from a top-level macro argument.
9458 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9459   if (Loc.isInvalid())
9460     return false;
9461 
9462   while (Loc.isMacroID()) {
9463     if (SM.isMacroBodyExpansion(Loc))
9464       return true;
9465     Loc = SM.getImmediateMacroCallerLoc(Loc);
9466   }
9467 
9468   return false;
9469 }
9470 
9471 /// \brief Diagnose pointers that are always non-null.
9472 /// \param E the expression containing the pointer
9473 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9474 /// compared to a null pointer
9475 /// \param IsEqual True when the comparison is equal to a null pointer
9476 /// \param Range Extra SourceRange to highlight in the diagnostic
9477 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9478                                         Expr::NullPointerConstantKind NullKind,
9479                                         bool IsEqual, SourceRange Range) {
9480   if (!E)
9481     return;
9482 
9483   // Don't warn inside macros.
9484   if (E->getExprLoc().isMacroID()) {
9485     const SourceManager &SM = getSourceManager();
9486     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9487         IsInAnyMacroBody(SM, Range.getBegin()))
9488       return;
9489   }
9490   E = E->IgnoreImpCasts();
9491 
9492   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9493 
9494   if (isa<CXXThisExpr>(E)) {
9495     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9496                                 : diag::warn_this_bool_conversion;
9497     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9498     return;
9499   }
9500 
9501   bool IsAddressOf = false;
9502 
9503   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9504     if (UO->getOpcode() != UO_AddrOf)
9505       return;
9506     IsAddressOf = true;
9507     E = UO->getSubExpr();
9508   }
9509 
9510   if (IsAddressOf) {
9511     unsigned DiagID = IsCompare
9512                           ? diag::warn_address_of_reference_null_compare
9513                           : diag::warn_address_of_reference_bool_conversion;
9514     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9515                                          << IsEqual;
9516     if (CheckForReference(*this, E, PD)) {
9517       return;
9518     }
9519   }
9520 
9521   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9522     bool IsParam = isa<NonNullAttr>(NonnullAttr);
9523     std::string Str;
9524     llvm::raw_string_ostream S(Str);
9525     E->printPretty(S, nullptr, getPrintingPolicy());
9526     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9527                                 : diag::warn_cast_nonnull_to_bool;
9528     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9529       << E->getSourceRange() << Range << IsEqual;
9530     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9531   };
9532 
9533   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9534   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9535     if (auto *Callee = Call->getDirectCallee()) {
9536       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9537         ComplainAboutNonnullParamOrCall(A);
9538         return;
9539       }
9540     }
9541   }
9542 
9543   // Expect to find a single Decl.  Skip anything more complicated.
9544   ValueDecl *D = nullptr;
9545   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9546     D = R->getDecl();
9547   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9548     D = M->getMemberDecl();
9549   }
9550 
9551   // Weak Decls can be null.
9552   if (!D || D->isWeak())
9553     return;
9554 
9555   // Check for parameter decl with nonnull attribute
9556   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9557     if (getCurFunction() &&
9558         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9559       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9560         ComplainAboutNonnullParamOrCall(A);
9561         return;
9562       }
9563 
9564       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9565         auto ParamIter = llvm::find(FD->parameters(), PV);
9566         assert(ParamIter != FD->param_end());
9567         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9568 
9569         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9570           if (!NonNull->args_size()) {
9571               ComplainAboutNonnullParamOrCall(NonNull);
9572               return;
9573           }
9574 
9575           for (unsigned ArgNo : NonNull->args()) {
9576             if (ArgNo == ParamNo) {
9577               ComplainAboutNonnullParamOrCall(NonNull);
9578               return;
9579             }
9580           }
9581         }
9582       }
9583     }
9584   }
9585 
9586   QualType T = D->getType();
9587   const bool IsArray = T->isArrayType();
9588   const bool IsFunction = T->isFunctionType();
9589 
9590   // Address of function is used to silence the function warning.
9591   if (IsAddressOf && IsFunction) {
9592     return;
9593   }
9594 
9595   // Found nothing.
9596   if (!IsAddressOf && !IsFunction && !IsArray)
9597     return;
9598 
9599   // Pretty print the expression for the diagnostic.
9600   std::string Str;
9601   llvm::raw_string_ostream S(Str);
9602   E->printPretty(S, nullptr, getPrintingPolicy());
9603 
9604   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9605                               : diag::warn_impcast_pointer_to_bool;
9606   enum {
9607     AddressOf,
9608     FunctionPointer,
9609     ArrayPointer
9610   } DiagType;
9611   if (IsAddressOf)
9612     DiagType = AddressOf;
9613   else if (IsFunction)
9614     DiagType = FunctionPointer;
9615   else if (IsArray)
9616     DiagType = ArrayPointer;
9617   else
9618     llvm_unreachable("Could not determine diagnostic.");
9619   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9620                                 << Range << IsEqual;
9621 
9622   if (!IsFunction)
9623     return;
9624 
9625   // Suggest '&' to silence the function warning.
9626   Diag(E->getExprLoc(), diag::note_function_warning_silence)
9627       << FixItHint::CreateInsertion(E->getLocStart(), "&");
9628 
9629   // Check to see if '()' fixit should be emitted.
9630   QualType ReturnType;
9631   UnresolvedSet<4> NonTemplateOverloads;
9632   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9633   if (ReturnType.isNull())
9634     return;
9635 
9636   if (IsCompare) {
9637     // There are two cases here.  If there is null constant, the only suggest
9638     // for a pointer return type.  If the null is 0, then suggest if the return
9639     // type is a pointer or an integer type.
9640     if (!ReturnType->isPointerType()) {
9641       if (NullKind == Expr::NPCK_ZeroExpression ||
9642           NullKind == Expr::NPCK_ZeroLiteral) {
9643         if (!ReturnType->isIntegerType())
9644           return;
9645       } else {
9646         return;
9647       }
9648     }
9649   } else { // !IsCompare
9650     // For function to bool, only suggest if the function pointer has bool
9651     // return type.
9652     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9653       return;
9654   }
9655   Diag(E->getExprLoc(), diag::note_function_to_function_call)
9656       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9657 }
9658 
9659 /// Diagnoses "dangerous" implicit conversions within the given
9660 /// expression (which is a full expression).  Implements -Wconversion
9661 /// and -Wsign-compare.
9662 ///
9663 /// \param CC the "context" location of the implicit conversion, i.e.
9664 ///   the most location of the syntactic entity requiring the implicit
9665 ///   conversion
9666 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9667   // Don't diagnose in unevaluated contexts.
9668   if (isUnevaluatedContext())
9669     return;
9670 
9671   // Don't diagnose for value- or type-dependent expressions.
9672   if (E->isTypeDependent() || E->isValueDependent())
9673     return;
9674 
9675   // Check for array bounds violations in cases where the check isn't triggered
9676   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9677   // ArraySubscriptExpr is on the RHS of a variable initialization.
9678   CheckArrayAccess(E);
9679 
9680   // This is not the right CC for (e.g.) a variable initialization.
9681   AnalyzeImplicitConversions(*this, E, CC);
9682 }
9683 
9684 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9685 /// Input argument E is a logical expression.
9686 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9687   ::CheckBoolLikeConversion(*this, E, CC);
9688 }
9689 
9690 /// Diagnose when expression is an integer constant expression and its evaluation
9691 /// results in integer overflow
9692 void Sema::CheckForIntOverflow (Expr *E) {
9693   // Use a work list to deal with nested struct initializers.
9694   SmallVector<Expr *, 2> Exprs(1, E);
9695 
9696   do {
9697     Expr *E = Exprs.pop_back_val();
9698 
9699     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9700       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9701       continue;
9702     }
9703 
9704     if (auto InitList = dyn_cast<InitListExpr>(E))
9705       Exprs.append(InitList->inits().begin(), InitList->inits().end());
9706   } while (!Exprs.empty());
9707 }
9708 
9709 namespace {
9710 /// \brief Visitor for expressions which looks for unsequenced operations on the
9711 /// same object.
9712 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9713   typedef EvaluatedExprVisitor<SequenceChecker> Base;
9714 
9715   /// \brief A tree of sequenced regions within an expression. Two regions are
9716   /// unsequenced if one is an ancestor or a descendent of the other. When we
9717   /// finish processing an expression with sequencing, such as a comma
9718   /// expression, we fold its tree nodes into its parent, since they are
9719   /// unsequenced with respect to nodes we will visit later.
9720   class SequenceTree {
9721     struct Value {
9722       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9723       unsigned Parent : 31;
9724       unsigned Merged : 1;
9725     };
9726     SmallVector<Value, 8> Values;
9727 
9728   public:
9729     /// \brief A region within an expression which may be sequenced with respect
9730     /// to some other region.
9731     class Seq {
9732       explicit Seq(unsigned N) : Index(N) {}
9733       unsigned Index;
9734       friend class SequenceTree;
9735     public:
9736       Seq() : Index(0) {}
9737     };
9738 
9739     SequenceTree() { Values.push_back(Value(0)); }
9740     Seq root() const { return Seq(0); }
9741 
9742     /// \brief Create a new sequence of operations, which is an unsequenced
9743     /// subset of \p Parent. This sequence of operations is sequenced with
9744     /// respect to other children of \p Parent.
9745     Seq allocate(Seq Parent) {
9746       Values.push_back(Value(Parent.Index));
9747       return Seq(Values.size() - 1);
9748     }
9749 
9750     /// \brief Merge a sequence of operations into its parent.
9751     void merge(Seq S) {
9752       Values[S.Index].Merged = true;
9753     }
9754 
9755     /// \brief Determine whether two operations are unsequenced. This operation
9756     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9757     /// should have been merged into its parent as appropriate.
9758     bool isUnsequenced(Seq Cur, Seq Old) {
9759       unsigned C = representative(Cur.Index);
9760       unsigned Target = representative(Old.Index);
9761       while (C >= Target) {
9762         if (C == Target)
9763           return true;
9764         C = Values[C].Parent;
9765       }
9766       return false;
9767     }
9768 
9769   private:
9770     /// \brief Pick a representative for a sequence.
9771     unsigned representative(unsigned K) {
9772       if (Values[K].Merged)
9773         // Perform path compression as we go.
9774         return Values[K].Parent = representative(Values[K].Parent);
9775       return K;
9776     }
9777   };
9778 
9779   /// An object for which we can track unsequenced uses.
9780   typedef NamedDecl *Object;
9781 
9782   /// Different flavors of object usage which we track. We only track the
9783   /// least-sequenced usage of each kind.
9784   enum UsageKind {
9785     /// A read of an object. Multiple unsequenced reads are OK.
9786     UK_Use,
9787     /// A modification of an object which is sequenced before the value
9788     /// computation of the expression, such as ++n in C++.
9789     UK_ModAsValue,
9790     /// A modification of an object which is not sequenced before the value
9791     /// computation of the expression, such as n++.
9792     UK_ModAsSideEffect,
9793 
9794     UK_Count = UK_ModAsSideEffect + 1
9795   };
9796 
9797   struct Usage {
9798     Usage() : Use(nullptr), Seq() {}
9799     Expr *Use;
9800     SequenceTree::Seq Seq;
9801   };
9802 
9803   struct UsageInfo {
9804     UsageInfo() : Diagnosed(false) {}
9805     Usage Uses[UK_Count];
9806     /// Have we issued a diagnostic for this variable already?
9807     bool Diagnosed;
9808   };
9809   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9810 
9811   Sema &SemaRef;
9812   /// Sequenced regions within the expression.
9813   SequenceTree Tree;
9814   /// Declaration modifications and references which we have seen.
9815   UsageInfoMap UsageMap;
9816   /// The region we are currently within.
9817   SequenceTree::Seq Region;
9818   /// Filled in with declarations which were modified as a side-effect
9819   /// (that is, post-increment operations).
9820   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
9821   /// Expressions to check later. We defer checking these to reduce
9822   /// stack usage.
9823   SmallVectorImpl<Expr *> &WorkList;
9824 
9825   /// RAII object wrapping the visitation of a sequenced subexpression of an
9826   /// expression. At the end of this process, the side-effects of the evaluation
9827   /// become sequenced with respect to the value computation of the result, so
9828   /// we downgrade any UK_ModAsSideEffect within the evaluation to
9829   /// UK_ModAsValue.
9830   struct SequencedSubexpression {
9831     SequencedSubexpression(SequenceChecker &Self)
9832       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9833       Self.ModAsSideEffect = &ModAsSideEffect;
9834     }
9835     ~SequencedSubexpression() {
9836       for (auto &M : llvm::reverse(ModAsSideEffect)) {
9837         UsageInfo &U = Self.UsageMap[M.first];
9838         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
9839         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9840         SideEffectUsage = M.second;
9841       }
9842       Self.ModAsSideEffect = OldModAsSideEffect;
9843     }
9844 
9845     SequenceChecker &Self;
9846     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9847     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
9848   };
9849 
9850   /// RAII object wrapping the visitation of a subexpression which we might
9851   /// choose to evaluate as a constant. If any subexpression is evaluated and
9852   /// found to be non-constant, this allows us to suppress the evaluation of
9853   /// the outer expression.
9854   class EvaluationTracker {
9855   public:
9856     EvaluationTracker(SequenceChecker &Self)
9857         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9858       Self.EvalTracker = this;
9859     }
9860     ~EvaluationTracker() {
9861       Self.EvalTracker = Prev;
9862       if (Prev)
9863         Prev->EvalOK &= EvalOK;
9864     }
9865 
9866     bool evaluate(const Expr *E, bool &Result) {
9867       if (!EvalOK || E->isValueDependent())
9868         return false;
9869       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9870       return EvalOK;
9871     }
9872 
9873   private:
9874     SequenceChecker &Self;
9875     EvaluationTracker *Prev;
9876     bool EvalOK;
9877   } *EvalTracker;
9878 
9879   /// \brief Find the object which is produced by the specified expression,
9880   /// if any.
9881   Object getObject(Expr *E, bool Mod) const {
9882     E = E->IgnoreParenCasts();
9883     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9884       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9885         return getObject(UO->getSubExpr(), Mod);
9886     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9887       if (BO->getOpcode() == BO_Comma)
9888         return getObject(BO->getRHS(), Mod);
9889       if (Mod && BO->isAssignmentOp())
9890         return getObject(BO->getLHS(), Mod);
9891     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9892       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9893       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9894         return ME->getMemberDecl();
9895     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9896       // FIXME: If this is a reference, map through to its value.
9897       return DRE->getDecl();
9898     return nullptr;
9899   }
9900 
9901   /// \brief Note that an object was modified or used by an expression.
9902   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9903     Usage &U = UI.Uses[UK];
9904     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9905       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9906         ModAsSideEffect->push_back(std::make_pair(O, U));
9907       U.Use = Ref;
9908       U.Seq = Region;
9909     }
9910   }
9911   /// \brief Check whether a modification or use conflicts with a prior usage.
9912   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9913                   bool IsModMod) {
9914     if (UI.Diagnosed)
9915       return;
9916 
9917     const Usage &U = UI.Uses[OtherKind];
9918     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9919       return;
9920 
9921     Expr *Mod = U.Use;
9922     Expr *ModOrUse = Ref;
9923     if (OtherKind == UK_Use)
9924       std::swap(Mod, ModOrUse);
9925 
9926     SemaRef.Diag(Mod->getExprLoc(),
9927                  IsModMod ? diag::warn_unsequenced_mod_mod
9928                           : diag::warn_unsequenced_mod_use)
9929       << O << SourceRange(ModOrUse->getExprLoc());
9930     UI.Diagnosed = true;
9931   }
9932 
9933   void notePreUse(Object O, Expr *Use) {
9934     UsageInfo &U = UsageMap[O];
9935     // Uses conflict with other modifications.
9936     checkUsage(O, U, Use, UK_ModAsValue, false);
9937   }
9938   void notePostUse(Object O, Expr *Use) {
9939     UsageInfo &U = UsageMap[O];
9940     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9941     addUsage(U, O, Use, UK_Use);
9942   }
9943 
9944   void notePreMod(Object O, Expr *Mod) {
9945     UsageInfo &U = UsageMap[O];
9946     // Modifications conflict with other modifications and with uses.
9947     checkUsage(O, U, Mod, UK_ModAsValue, true);
9948     checkUsage(O, U, Mod, UK_Use, false);
9949   }
9950   void notePostMod(Object O, Expr *Use, UsageKind UK) {
9951     UsageInfo &U = UsageMap[O];
9952     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9953     addUsage(U, O, Use, UK);
9954   }
9955 
9956 public:
9957   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
9958       : Base(S.Context), SemaRef(S), Region(Tree.root()),
9959         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
9960     Visit(E);
9961   }
9962 
9963   void VisitStmt(Stmt *S) {
9964     // Skip all statements which aren't expressions for now.
9965   }
9966 
9967   void VisitExpr(Expr *E) {
9968     // By default, just recurse to evaluated subexpressions.
9969     Base::VisitStmt(E);
9970   }
9971 
9972   void VisitCastExpr(CastExpr *E) {
9973     Object O = Object();
9974     if (E->getCastKind() == CK_LValueToRValue)
9975       O = getObject(E->getSubExpr(), false);
9976 
9977     if (O)
9978       notePreUse(O, E);
9979     VisitExpr(E);
9980     if (O)
9981       notePostUse(O, E);
9982   }
9983 
9984   void VisitBinComma(BinaryOperator *BO) {
9985     // C++11 [expr.comma]p1:
9986     //   Every value computation and side effect associated with the left
9987     //   expression is sequenced before every value computation and side
9988     //   effect associated with the right expression.
9989     SequenceTree::Seq LHS = Tree.allocate(Region);
9990     SequenceTree::Seq RHS = Tree.allocate(Region);
9991     SequenceTree::Seq OldRegion = Region;
9992 
9993     {
9994       SequencedSubexpression SeqLHS(*this);
9995       Region = LHS;
9996       Visit(BO->getLHS());
9997     }
9998 
9999     Region = RHS;
10000     Visit(BO->getRHS());
10001 
10002     Region = OldRegion;
10003 
10004     // Forget that LHS and RHS are sequenced. They are both unsequenced
10005     // with respect to other stuff.
10006     Tree.merge(LHS);
10007     Tree.merge(RHS);
10008   }
10009 
10010   void VisitBinAssign(BinaryOperator *BO) {
10011     // The modification is sequenced after the value computation of the LHS
10012     // and RHS, so check it before inspecting the operands and update the
10013     // map afterwards.
10014     Object O = getObject(BO->getLHS(), true);
10015     if (!O)
10016       return VisitExpr(BO);
10017 
10018     notePreMod(O, BO);
10019 
10020     // C++11 [expr.ass]p7:
10021     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10022     //   only once.
10023     //
10024     // Therefore, for a compound assignment operator, O is considered used
10025     // everywhere except within the evaluation of E1 itself.
10026     if (isa<CompoundAssignOperator>(BO))
10027       notePreUse(O, BO);
10028 
10029     Visit(BO->getLHS());
10030 
10031     if (isa<CompoundAssignOperator>(BO))
10032       notePostUse(O, BO);
10033 
10034     Visit(BO->getRHS());
10035 
10036     // C++11 [expr.ass]p1:
10037     //   the assignment is sequenced [...] before the value computation of the
10038     //   assignment expression.
10039     // C11 6.5.16/3 has no such rule.
10040     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10041                                                        : UK_ModAsSideEffect);
10042   }
10043 
10044   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10045     VisitBinAssign(CAO);
10046   }
10047 
10048   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10049   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10050   void VisitUnaryPreIncDec(UnaryOperator *UO) {
10051     Object O = getObject(UO->getSubExpr(), true);
10052     if (!O)
10053       return VisitExpr(UO);
10054 
10055     notePreMod(O, UO);
10056     Visit(UO->getSubExpr());
10057     // C++11 [expr.pre.incr]p1:
10058     //   the expression ++x is equivalent to x+=1
10059     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10060                                                        : UK_ModAsSideEffect);
10061   }
10062 
10063   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10064   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10065   void VisitUnaryPostIncDec(UnaryOperator *UO) {
10066     Object O = getObject(UO->getSubExpr(), true);
10067     if (!O)
10068       return VisitExpr(UO);
10069 
10070     notePreMod(O, UO);
10071     Visit(UO->getSubExpr());
10072     notePostMod(O, UO, UK_ModAsSideEffect);
10073   }
10074 
10075   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10076   void VisitBinLOr(BinaryOperator *BO) {
10077     // The side-effects of the LHS of an '&&' are sequenced before the
10078     // value computation of the RHS, and hence before the value computation
10079     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10080     // as if they were unconditionally sequenced.
10081     EvaluationTracker Eval(*this);
10082     {
10083       SequencedSubexpression Sequenced(*this);
10084       Visit(BO->getLHS());
10085     }
10086 
10087     bool Result;
10088     if (Eval.evaluate(BO->getLHS(), Result)) {
10089       if (!Result)
10090         Visit(BO->getRHS());
10091     } else {
10092       // Check for unsequenced operations in the RHS, treating it as an
10093       // entirely separate evaluation.
10094       //
10095       // FIXME: If there are operations in the RHS which are unsequenced
10096       // with respect to operations outside the RHS, and those operations
10097       // are unconditionally evaluated, diagnose them.
10098       WorkList.push_back(BO->getRHS());
10099     }
10100   }
10101   void VisitBinLAnd(BinaryOperator *BO) {
10102     EvaluationTracker Eval(*this);
10103     {
10104       SequencedSubexpression Sequenced(*this);
10105       Visit(BO->getLHS());
10106     }
10107 
10108     bool Result;
10109     if (Eval.evaluate(BO->getLHS(), Result)) {
10110       if (Result)
10111         Visit(BO->getRHS());
10112     } else {
10113       WorkList.push_back(BO->getRHS());
10114     }
10115   }
10116 
10117   // Only visit the condition, unless we can be sure which subexpression will
10118   // be chosen.
10119   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10120     EvaluationTracker Eval(*this);
10121     {
10122       SequencedSubexpression Sequenced(*this);
10123       Visit(CO->getCond());
10124     }
10125 
10126     bool Result;
10127     if (Eval.evaluate(CO->getCond(), Result))
10128       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10129     else {
10130       WorkList.push_back(CO->getTrueExpr());
10131       WorkList.push_back(CO->getFalseExpr());
10132     }
10133   }
10134 
10135   void VisitCallExpr(CallExpr *CE) {
10136     // C++11 [intro.execution]p15:
10137     //   When calling a function [...], every value computation and side effect
10138     //   associated with any argument expression, or with the postfix expression
10139     //   designating the called function, is sequenced before execution of every
10140     //   expression or statement in the body of the function [and thus before
10141     //   the value computation of its result].
10142     SequencedSubexpression Sequenced(*this);
10143     Base::VisitCallExpr(CE);
10144 
10145     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10146   }
10147 
10148   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10149     // This is a call, so all subexpressions are sequenced before the result.
10150     SequencedSubexpression Sequenced(*this);
10151 
10152     if (!CCE->isListInitialization())
10153       return VisitExpr(CCE);
10154 
10155     // In C++11, list initializations are sequenced.
10156     SmallVector<SequenceTree::Seq, 32> Elts;
10157     SequenceTree::Seq Parent = Region;
10158     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10159                                         E = CCE->arg_end();
10160          I != E; ++I) {
10161       Region = Tree.allocate(Parent);
10162       Elts.push_back(Region);
10163       Visit(*I);
10164     }
10165 
10166     // Forget that the initializers are sequenced.
10167     Region = Parent;
10168     for (unsigned I = 0; I < Elts.size(); ++I)
10169       Tree.merge(Elts[I]);
10170   }
10171 
10172   void VisitInitListExpr(InitListExpr *ILE) {
10173     if (!SemaRef.getLangOpts().CPlusPlus11)
10174       return VisitExpr(ILE);
10175 
10176     // In C++11, list initializations are sequenced.
10177     SmallVector<SequenceTree::Seq, 32> Elts;
10178     SequenceTree::Seq Parent = Region;
10179     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10180       Expr *E = ILE->getInit(I);
10181       if (!E) continue;
10182       Region = Tree.allocate(Parent);
10183       Elts.push_back(Region);
10184       Visit(E);
10185     }
10186 
10187     // Forget that the initializers are sequenced.
10188     Region = Parent;
10189     for (unsigned I = 0; I < Elts.size(); ++I)
10190       Tree.merge(Elts[I]);
10191   }
10192 };
10193 } // end anonymous namespace
10194 
10195 void Sema::CheckUnsequencedOperations(Expr *E) {
10196   SmallVector<Expr *, 8> WorkList;
10197   WorkList.push_back(E);
10198   while (!WorkList.empty()) {
10199     Expr *Item = WorkList.pop_back_val();
10200     SequenceChecker(*this, Item, WorkList);
10201   }
10202 }
10203 
10204 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10205                               bool IsConstexpr) {
10206   CheckImplicitConversions(E, CheckLoc);
10207   if (!E->isInstantiationDependent())
10208     CheckUnsequencedOperations(E);
10209   if (!IsConstexpr && !E->isValueDependent())
10210     CheckForIntOverflow(E);
10211   DiagnoseMisalignedMembers();
10212 }
10213 
10214 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10215                                        FieldDecl *BitField,
10216                                        Expr *Init) {
10217   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10218 }
10219 
10220 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10221                                          SourceLocation Loc) {
10222   if (!PType->isVariablyModifiedType())
10223     return;
10224   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10225     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10226     return;
10227   }
10228   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10229     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10230     return;
10231   }
10232   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10233     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10234     return;
10235   }
10236 
10237   const ArrayType *AT = S.Context.getAsArrayType(PType);
10238   if (!AT)
10239     return;
10240 
10241   if (AT->getSizeModifier() != ArrayType::Star) {
10242     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10243     return;
10244   }
10245 
10246   S.Diag(Loc, diag::err_array_star_in_function_definition);
10247 }
10248 
10249 /// CheckParmsForFunctionDef - Check that the parameters of the given
10250 /// function are appropriate for the definition of a function. This
10251 /// takes care of any checks that cannot be performed on the
10252 /// declaration itself, e.g., that the types of each of the function
10253 /// parameters are complete.
10254 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10255                                     bool CheckParameterNames) {
10256   bool HasInvalidParm = false;
10257   for (ParmVarDecl *Param : Parameters) {
10258     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10259     // function declarator that is part of a function definition of
10260     // that function shall not have incomplete type.
10261     //
10262     // This is also C++ [dcl.fct]p6.
10263     if (!Param->isInvalidDecl() &&
10264         RequireCompleteType(Param->getLocation(), Param->getType(),
10265                             diag::err_typecheck_decl_incomplete_type)) {
10266       Param->setInvalidDecl();
10267       HasInvalidParm = true;
10268     }
10269 
10270     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10271     // declaration of each parameter shall include an identifier.
10272     if (CheckParameterNames &&
10273         Param->getIdentifier() == nullptr &&
10274         !Param->isImplicit() &&
10275         !getLangOpts().CPlusPlus)
10276       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10277 
10278     // C99 6.7.5.3p12:
10279     //   If the function declarator is not part of a definition of that
10280     //   function, parameters may have incomplete type and may use the [*]
10281     //   notation in their sequences of declarator specifiers to specify
10282     //   variable length array types.
10283     QualType PType = Param->getOriginalType();
10284     // FIXME: This diagnostic should point the '[*]' if source-location
10285     // information is added for it.
10286     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10287 
10288     // MSVC destroys objects passed by value in the callee.  Therefore a
10289     // function definition which takes such a parameter must be able to call the
10290     // object's destructor.  However, we don't perform any direct access check
10291     // on the dtor.
10292     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10293                                        .getCXXABI()
10294                                        .areArgsDestroyedLeftToRightInCallee()) {
10295       if (!Param->isInvalidDecl()) {
10296         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10297           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10298           if (!ClassDecl->isInvalidDecl() &&
10299               !ClassDecl->hasIrrelevantDestructor() &&
10300               !ClassDecl->isDependentContext()) {
10301             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10302             MarkFunctionReferenced(Param->getLocation(), Destructor);
10303             DiagnoseUseOfDecl(Destructor, Param->getLocation());
10304           }
10305         }
10306       }
10307     }
10308 
10309     // Parameters with the pass_object_size attribute only need to be marked
10310     // constant at function definitions. Because we lack information about
10311     // whether we're on a declaration or definition when we're instantiating the
10312     // attribute, we need to check for constness here.
10313     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10314       if (!Param->getType().isConstQualified())
10315         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10316             << Attr->getSpelling() << 1;
10317   }
10318 
10319   return HasInvalidParm;
10320 }
10321 
10322 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10323 /// or MemberExpr.
10324 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10325                               ASTContext &Context) {
10326   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10327     return Context.getDeclAlign(DRE->getDecl());
10328 
10329   if (const auto *ME = dyn_cast<MemberExpr>(E))
10330     return Context.getDeclAlign(ME->getMemberDecl());
10331 
10332   return TypeAlign;
10333 }
10334 
10335 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10336 /// pointer cast increases the alignment requirements.
10337 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10338   // This is actually a lot of work to potentially be doing on every
10339   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10340   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10341     return;
10342 
10343   // Ignore dependent types.
10344   if (T->isDependentType() || Op->getType()->isDependentType())
10345     return;
10346 
10347   // Require that the destination be a pointer type.
10348   const PointerType *DestPtr = T->getAs<PointerType>();
10349   if (!DestPtr) return;
10350 
10351   // If the destination has alignment 1, we're done.
10352   QualType DestPointee = DestPtr->getPointeeType();
10353   if (DestPointee->isIncompleteType()) return;
10354   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10355   if (DestAlign.isOne()) return;
10356 
10357   // Require that the source be a pointer type.
10358   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10359   if (!SrcPtr) return;
10360   QualType SrcPointee = SrcPtr->getPointeeType();
10361 
10362   // Whitelist casts from cv void*.  We already implicitly
10363   // whitelisted casts to cv void*, since they have alignment 1.
10364   // Also whitelist casts involving incomplete types, which implicitly
10365   // includes 'void'.
10366   if (SrcPointee->isIncompleteType()) return;
10367 
10368   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10369 
10370   if (auto *CE = dyn_cast<CastExpr>(Op)) {
10371     if (CE->getCastKind() == CK_ArrayToPointerDecay)
10372       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10373   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10374     if (UO->getOpcode() == UO_AddrOf)
10375       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10376   }
10377 
10378   if (SrcAlign >= DestAlign) return;
10379 
10380   Diag(TRange.getBegin(), diag::warn_cast_align)
10381     << Op->getType() << T
10382     << static_cast<unsigned>(SrcAlign.getQuantity())
10383     << static_cast<unsigned>(DestAlign.getQuantity())
10384     << TRange << Op->getSourceRange();
10385 }
10386 
10387 /// \brief Check whether this array fits the idiom of a size-one tail padded
10388 /// array member of a struct.
10389 ///
10390 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10391 /// commonly used to emulate flexible arrays in C89 code.
10392 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10393                                     const NamedDecl *ND) {
10394   if (Size != 1 || !ND) return false;
10395 
10396   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10397   if (!FD) return false;
10398 
10399   // Don't consider sizes resulting from macro expansions or template argument
10400   // substitution to form C89 tail-padded arrays.
10401 
10402   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10403   while (TInfo) {
10404     TypeLoc TL = TInfo->getTypeLoc();
10405     // Look through typedefs.
10406     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10407       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10408       TInfo = TDL->getTypeSourceInfo();
10409       continue;
10410     }
10411     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10412       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10413       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10414         return false;
10415     }
10416     break;
10417   }
10418 
10419   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10420   if (!RD) return false;
10421   if (RD->isUnion()) return false;
10422   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10423     if (!CRD->isStandardLayout()) return false;
10424   }
10425 
10426   // See if this is the last field decl in the record.
10427   const Decl *D = FD;
10428   while ((D = D->getNextDeclInContext()))
10429     if (isa<FieldDecl>(D))
10430       return false;
10431   return true;
10432 }
10433 
10434 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10435                             const ArraySubscriptExpr *ASE,
10436                             bool AllowOnePastEnd, bool IndexNegated) {
10437   IndexExpr = IndexExpr->IgnoreParenImpCasts();
10438   if (IndexExpr->isValueDependent())
10439     return;
10440 
10441   const Type *EffectiveType =
10442       BaseExpr->getType()->getPointeeOrArrayElementType();
10443   BaseExpr = BaseExpr->IgnoreParenCasts();
10444   const ConstantArrayType *ArrayTy =
10445     Context.getAsConstantArrayType(BaseExpr->getType());
10446   if (!ArrayTy)
10447     return;
10448 
10449   llvm::APSInt index;
10450   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10451     return;
10452   if (IndexNegated)
10453     index = -index;
10454 
10455   const NamedDecl *ND = nullptr;
10456   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10457     ND = dyn_cast<NamedDecl>(DRE->getDecl());
10458   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10459     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10460 
10461   if (index.isUnsigned() || !index.isNegative()) {
10462     llvm::APInt size = ArrayTy->getSize();
10463     if (!size.isStrictlyPositive())
10464       return;
10465 
10466     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10467     if (BaseType != EffectiveType) {
10468       // Make sure we're comparing apples to apples when comparing index to size
10469       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10470       uint64_t array_typesize = Context.getTypeSize(BaseType);
10471       // Handle ptrarith_typesize being zero, such as when casting to void*
10472       if (!ptrarith_typesize) ptrarith_typesize = 1;
10473       if (ptrarith_typesize != array_typesize) {
10474         // There's a cast to a different size type involved
10475         uint64_t ratio = array_typesize / ptrarith_typesize;
10476         // TODO: Be smarter about handling cases where array_typesize is not a
10477         // multiple of ptrarith_typesize
10478         if (ptrarith_typesize * ratio == array_typesize)
10479           size *= llvm::APInt(size.getBitWidth(), ratio);
10480       }
10481     }
10482 
10483     if (size.getBitWidth() > index.getBitWidth())
10484       index = index.zext(size.getBitWidth());
10485     else if (size.getBitWidth() < index.getBitWidth())
10486       size = size.zext(index.getBitWidth());
10487 
10488     // For array subscripting the index must be less than size, but for pointer
10489     // arithmetic also allow the index (offset) to be equal to size since
10490     // computing the next address after the end of the array is legal and
10491     // commonly done e.g. in C++ iterators and range-based for loops.
10492     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10493       return;
10494 
10495     // Also don't warn for arrays of size 1 which are members of some
10496     // structure. These are often used to approximate flexible arrays in C89
10497     // code.
10498     if (IsTailPaddedMemberArray(*this, size, ND))
10499       return;
10500 
10501     // Suppress the warning if the subscript expression (as identified by the
10502     // ']' location) and the index expression are both from macro expansions
10503     // within a system header.
10504     if (ASE) {
10505       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10506           ASE->getRBracketLoc());
10507       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10508         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10509             IndexExpr->getLocStart());
10510         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10511           return;
10512       }
10513     }
10514 
10515     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10516     if (ASE)
10517       DiagID = diag::warn_array_index_exceeds_bounds;
10518 
10519     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10520                         PDiag(DiagID) << index.toString(10, true)
10521                           << size.toString(10, true)
10522                           << (unsigned)size.getLimitedValue(~0U)
10523                           << IndexExpr->getSourceRange());
10524   } else {
10525     unsigned DiagID = diag::warn_array_index_precedes_bounds;
10526     if (!ASE) {
10527       DiagID = diag::warn_ptr_arith_precedes_bounds;
10528       if (index.isNegative()) index = -index;
10529     }
10530 
10531     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10532                         PDiag(DiagID) << index.toString(10, true)
10533                           << IndexExpr->getSourceRange());
10534   }
10535 
10536   if (!ND) {
10537     // Try harder to find a NamedDecl to point at in the note.
10538     while (const ArraySubscriptExpr *ASE =
10539            dyn_cast<ArraySubscriptExpr>(BaseExpr))
10540       BaseExpr = ASE->getBase()->IgnoreParenCasts();
10541     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10542       ND = dyn_cast<NamedDecl>(DRE->getDecl());
10543     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10544       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10545   }
10546 
10547   if (ND)
10548     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10549                         PDiag(diag::note_array_index_out_of_bounds)
10550                           << ND->getDeclName());
10551 }
10552 
10553 void Sema::CheckArrayAccess(const Expr *expr) {
10554   int AllowOnePastEnd = 0;
10555   while (expr) {
10556     expr = expr->IgnoreParenImpCasts();
10557     switch (expr->getStmtClass()) {
10558       case Stmt::ArraySubscriptExprClass: {
10559         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10560         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
10561                          AllowOnePastEnd > 0);
10562         return;
10563       }
10564       case Stmt::OMPArraySectionExprClass: {
10565         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10566         if (ASE->getLowerBound())
10567           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10568                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
10569         return;
10570       }
10571       case Stmt::UnaryOperatorClass: {
10572         // Only unwrap the * and & unary operators
10573         const UnaryOperator *UO = cast<UnaryOperator>(expr);
10574         expr = UO->getSubExpr();
10575         switch (UO->getOpcode()) {
10576           case UO_AddrOf:
10577             AllowOnePastEnd++;
10578             break;
10579           case UO_Deref:
10580             AllowOnePastEnd--;
10581             break;
10582           default:
10583             return;
10584         }
10585         break;
10586       }
10587       case Stmt::ConditionalOperatorClass: {
10588         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10589         if (const Expr *lhs = cond->getLHS())
10590           CheckArrayAccess(lhs);
10591         if (const Expr *rhs = cond->getRHS())
10592           CheckArrayAccess(rhs);
10593         return;
10594       }
10595       default:
10596         return;
10597     }
10598   }
10599 }
10600 
10601 //===--- CHECK: Objective-C retain cycles ----------------------------------//
10602 
10603 namespace {
10604   struct RetainCycleOwner {
10605     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
10606     VarDecl *Variable;
10607     SourceRange Range;
10608     SourceLocation Loc;
10609     bool Indirect;
10610 
10611     void setLocsFrom(Expr *e) {
10612       Loc = e->getExprLoc();
10613       Range = e->getSourceRange();
10614     }
10615   };
10616 } // end anonymous namespace
10617 
10618 /// Consider whether capturing the given variable can possibly lead to
10619 /// a retain cycle.
10620 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
10621   // In ARC, it's captured strongly iff the variable has __strong
10622   // lifetime.  In MRR, it's captured strongly if the variable is
10623   // __block and has an appropriate type.
10624   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10625     return false;
10626 
10627   owner.Variable = var;
10628   if (ref)
10629     owner.setLocsFrom(ref);
10630   return true;
10631 }
10632 
10633 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
10634   while (true) {
10635     e = e->IgnoreParens();
10636     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10637       switch (cast->getCastKind()) {
10638       case CK_BitCast:
10639       case CK_LValueBitCast:
10640       case CK_LValueToRValue:
10641       case CK_ARCReclaimReturnedObject:
10642         e = cast->getSubExpr();
10643         continue;
10644 
10645       default:
10646         return false;
10647       }
10648     }
10649 
10650     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10651       ObjCIvarDecl *ivar = ref->getDecl();
10652       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10653         return false;
10654 
10655       // Try to find a retain cycle in the base.
10656       if (!findRetainCycleOwner(S, ref->getBase(), owner))
10657         return false;
10658 
10659       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10660       owner.Indirect = true;
10661       return true;
10662     }
10663 
10664     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10665       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10666       if (!var) return false;
10667       return considerVariable(var, ref, owner);
10668     }
10669 
10670     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10671       if (member->isArrow()) return false;
10672 
10673       // Don't count this as an indirect ownership.
10674       e = member->getBase();
10675       continue;
10676     }
10677 
10678     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10679       // Only pay attention to pseudo-objects on property references.
10680       ObjCPropertyRefExpr *pre
10681         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10682                                               ->IgnoreParens());
10683       if (!pre) return false;
10684       if (pre->isImplicitProperty()) return false;
10685       ObjCPropertyDecl *property = pre->getExplicitProperty();
10686       if (!property->isRetaining() &&
10687           !(property->getPropertyIvarDecl() &&
10688             property->getPropertyIvarDecl()->getType()
10689               .getObjCLifetime() == Qualifiers::OCL_Strong))
10690           return false;
10691 
10692       owner.Indirect = true;
10693       if (pre->isSuperReceiver()) {
10694         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10695         if (!owner.Variable)
10696           return false;
10697         owner.Loc = pre->getLocation();
10698         owner.Range = pre->getSourceRange();
10699         return true;
10700       }
10701       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10702                               ->getSourceExpr());
10703       continue;
10704     }
10705 
10706     // Array ivars?
10707 
10708     return false;
10709   }
10710 }
10711 
10712 namespace {
10713   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10714     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10715       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10716         Context(Context), Variable(variable), Capturer(nullptr),
10717         VarWillBeReased(false) {}
10718     ASTContext &Context;
10719     VarDecl *Variable;
10720     Expr *Capturer;
10721     bool VarWillBeReased;
10722 
10723     void VisitDeclRefExpr(DeclRefExpr *ref) {
10724       if (ref->getDecl() == Variable && !Capturer)
10725         Capturer = ref;
10726     }
10727 
10728     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10729       if (Capturer) return;
10730       Visit(ref->getBase());
10731       if (Capturer && ref->isFreeIvar())
10732         Capturer = ref;
10733     }
10734 
10735     void VisitBlockExpr(BlockExpr *block) {
10736       // Look inside nested blocks
10737       if (block->getBlockDecl()->capturesVariable(Variable))
10738         Visit(block->getBlockDecl()->getBody());
10739     }
10740 
10741     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10742       if (Capturer) return;
10743       if (OVE->getSourceExpr())
10744         Visit(OVE->getSourceExpr());
10745     }
10746     void VisitBinaryOperator(BinaryOperator *BinOp) {
10747       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10748         return;
10749       Expr *LHS = BinOp->getLHS();
10750       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10751         if (DRE->getDecl() != Variable)
10752           return;
10753         if (Expr *RHS = BinOp->getRHS()) {
10754           RHS = RHS->IgnoreParenCasts();
10755           llvm::APSInt Value;
10756           VarWillBeReased =
10757             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10758         }
10759       }
10760     }
10761   };
10762 } // end anonymous namespace
10763 
10764 /// Check whether the given argument is a block which captures a
10765 /// variable.
10766 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10767   assert(owner.Variable && owner.Loc.isValid());
10768 
10769   e = e->IgnoreParenCasts();
10770 
10771   // Look through [^{...} copy] and Block_copy(^{...}).
10772   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10773     Selector Cmd = ME->getSelector();
10774     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10775       e = ME->getInstanceReceiver();
10776       if (!e)
10777         return nullptr;
10778       e = e->IgnoreParenCasts();
10779     }
10780   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10781     if (CE->getNumArgs() == 1) {
10782       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
10783       if (Fn) {
10784         const IdentifierInfo *FnI = Fn->getIdentifier();
10785         if (FnI && FnI->isStr("_Block_copy")) {
10786           e = CE->getArg(0)->IgnoreParenCasts();
10787         }
10788       }
10789     }
10790   }
10791 
10792   BlockExpr *block = dyn_cast<BlockExpr>(e);
10793   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
10794     return nullptr;
10795 
10796   FindCaptureVisitor visitor(S.Context, owner.Variable);
10797   visitor.Visit(block->getBlockDecl()->getBody());
10798   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
10799 }
10800 
10801 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10802                                 RetainCycleOwner &owner) {
10803   assert(capturer);
10804   assert(owner.Variable && owner.Loc.isValid());
10805 
10806   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10807     << owner.Variable << capturer->getSourceRange();
10808   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10809     << owner.Indirect << owner.Range;
10810 }
10811 
10812 /// Check for a keyword selector that starts with the word 'add' or
10813 /// 'set'.
10814 static bool isSetterLikeSelector(Selector sel) {
10815   if (sel.isUnarySelector()) return false;
10816 
10817   StringRef str = sel.getNameForSlot(0);
10818   while (!str.empty() && str.front() == '_') str = str.substr(1);
10819   if (str.startswith("set"))
10820     str = str.substr(3);
10821   else if (str.startswith("add")) {
10822     // Specially whitelist 'addOperationWithBlock:'.
10823     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10824       return false;
10825     str = str.substr(3);
10826   }
10827   else
10828     return false;
10829 
10830   if (str.empty()) return true;
10831   return !isLowercase(str.front());
10832 }
10833 
10834 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10835                                                     ObjCMessageExpr *Message) {
10836   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10837                                                 Message->getReceiverInterface(),
10838                                                 NSAPI::ClassId_NSMutableArray);
10839   if (!IsMutableArray) {
10840     return None;
10841   }
10842 
10843   Selector Sel = Message->getSelector();
10844 
10845   Optional<NSAPI::NSArrayMethodKind> MKOpt =
10846     S.NSAPIObj->getNSArrayMethodKind(Sel);
10847   if (!MKOpt) {
10848     return None;
10849   }
10850 
10851   NSAPI::NSArrayMethodKind MK = *MKOpt;
10852 
10853   switch (MK) {
10854     case NSAPI::NSMutableArr_addObject:
10855     case NSAPI::NSMutableArr_insertObjectAtIndex:
10856     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10857       return 0;
10858     case NSAPI::NSMutableArr_replaceObjectAtIndex:
10859       return 1;
10860 
10861     default:
10862       return None;
10863   }
10864 
10865   return None;
10866 }
10867 
10868 static
10869 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10870                                                   ObjCMessageExpr *Message) {
10871   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10872                                             Message->getReceiverInterface(),
10873                                             NSAPI::ClassId_NSMutableDictionary);
10874   if (!IsMutableDictionary) {
10875     return None;
10876   }
10877 
10878   Selector Sel = Message->getSelector();
10879 
10880   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10881     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10882   if (!MKOpt) {
10883     return None;
10884   }
10885 
10886   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10887 
10888   switch (MK) {
10889     case NSAPI::NSMutableDict_setObjectForKey:
10890     case NSAPI::NSMutableDict_setValueForKey:
10891     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10892       return 0;
10893 
10894     default:
10895       return None;
10896   }
10897 
10898   return None;
10899 }
10900 
10901 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
10902   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10903                                                 Message->getReceiverInterface(),
10904                                                 NSAPI::ClassId_NSMutableSet);
10905 
10906   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10907                                             Message->getReceiverInterface(),
10908                                             NSAPI::ClassId_NSMutableOrderedSet);
10909   if (!IsMutableSet && !IsMutableOrderedSet) {
10910     return None;
10911   }
10912 
10913   Selector Sel = Message->getSelector();
10914 
10915   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10916   if (!MKOpt) {
10917     return None;
10918   }
10919 
10920   NSAPI::NSSetMethodKind MK = *MKOpt;
10921 
10922   switch (MK) {
10923     case NSAPI::NSMutableSet_addObject:
10924     case NSAPI::NSOrderedSet_setObjectAtIndex:
10925     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10926     case NSAPI::NSOrderedSet_insertObjectAtIndex:
10927       return 0;
10928     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10929       return 1;
10930   }
10931 
10932   return None;
10933 }
10934 
10935 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10936   if (!Message->isInstanceMessage()) {
10937     return;
10938   }
10939 
10940   Optional<int> ArgOpt;
10941 
10942   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10943       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10944       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10945     return;
10946   }
10947 
10948   int ArgIndex = *ArgOpt;
10949 
10950   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10951   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10952     Arg = OE->getSourceExpr()->IgnoreImpCasts();
10953   }
10954 
10955   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10956     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10957       if (ArgRE->isObjCSelfExpr()) {
10958         Diag(Message->getSourceRange().getBegin(),
10959              diag::warn_objc_circular_container)
10960           << ArgRE->getDecl()->getName() << StringRef("super");
10961       }
10962     }
10963   } else {
10964     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10965 
10966     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10967       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10968     }
10969 
10970     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10971       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10972         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10973           ValueDecl *Decl = ReceiverRE->getDecl();
10974           Diag(Message->getSourceRange().getBegin(),
10975                diag::warn_objc_circular_container)
10976             << Decl->getName() << Decl->getName();
10977           if (!ArgRE->isObjCSelfExpr()) {
10978             Diag(Decl->getLocation(),
10979                  diag::note_objc_circular_container_declared_here)
10980               << Decl->getName();
10981           }
10982         }
10983       }
10984     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10985       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10986         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10987           ObjCIvarDecl *Decl = IvarRE->getDecl();
10988           Diag(Message->getSourceRange().getBegin(),
10989                diag::warn_objc_circular_container)
10990             << Decl->getName() << Decl->getName();
10991           Diag(Decl->getLocation(),
10992                diag::note_objc_circular_container_declared_here)
10993             << Decl->getName();
10994         }
10995       }
10996     }
10997   }
10998 }
10999 
11000 /// Check a message send to see if it's likely to cause a retain cycle.
11001 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11002   // Only check instance methods whose selector looks like a setter.
11003   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11004     return;
11005 
11006   // Try to find a variable that the receiver is strongly owned by.
11007   RetainCycleOwner owner;
11008   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11009     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11010       return;
11011   } else {
11012     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11013     owner.Variable = getCurMethodDecl()->getSelfDecl();
11014     owner.Loc = msg->getSuperLoc();
11015     owner.Range = msg->getSuperLoc();
11016   }
11017 
11018   // Check whether the receiver is captured by any of the arguments.
11019   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11020     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11021       return diagnoseRetainCycle(*this, capturer, owner);
11022 }
11023 
11024 /// Check a property assign to see if it's likely to cause a retain cycle.
11025 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11026   RetainCycleOwner owner;
11027   if (!findRetainCycleOwner(*this, receiver, owner))
11028     return;
11029 
11030   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11031     diagnoseRetainCycle(*this, capturer, owner);
11032 }
11033 
11034 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11035   RetainCycleOwner Owner;
11036   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11037     return;
11038 
11039   // Because we don't have an expression for the variable, we have to set the
11040   // location explicitly here.
11041   Owner.Loc = Var->getLocation();
11042   Owner.Range = Var->getSourceRange();
11043 
11044   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11045     diagnoseRetainCycle(*this, Capturer, Owner);
11046 }
11047 
11048 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11049                                      Expr *RHS, bool isProperty) {
11050   // Check if RHS is an Objective-C object literal, which also can get
11051   // immediately zapped in a weak reference.  Note that we explicitly
11052   // allow ObjCStringLiterals, since those are designed to never really die.
11053   RHS = RHS->IgnoreParenImpCasts();
11054 
11055   // This enum needs to match with the 'select' in
11056   // warn_objc_arc_literal_assign (off-by-1).
11057   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11058   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11059     return false;
11060 
11061   S.Diag(Loc, diag::warn_arc_literal_assign)
11062     << (unsigned) Kind
11063     << (isProperty ? 0 : 1)
11064     << RHS->getSourceRange();
11065 
11066   return true;
11067 }
11068 
11069 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11070                                     Qualifiers::ObjCLifetime LT,
11071                                     Expr *RHS, bool isProperty) {
11072   // Strip off any implicit cast added to get to the one ARC-specific.
11073   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11074     if (cast->getCastKind() == CK_ARCConsumeObject) {
11075       S.Diag(Loc, diag::warn_arc_retained_assign)
11076         << (LT == Qualifiers::OCL_ExplicitNone)
11077         << (isProperty ? 0 : 1)
11078         << RHS->getSourceRange();
11079       return true;
11080     }
11081     RHS = cast->getSubExpr();
11082   }
11083 
11084   if (LT == Qualifiers::OCL_Weak &&
11085       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11086     return true;
11087 
11088   return false;
11089 }
11090 
11091 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11092                               QualType LHS, Expr *RHS) {
11093   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11094 
11095   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11096     return false;
11097 
11098   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11099     return true;
11100 
11101   return false;
11102 }
11103 
11104 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11105                               Expr *LHS, Expr *RHS) {
11106   QualType LHSType;
11107   // PropertyRef on LHS type need be directly obtained from
11108   // its declaration as it has a PseudoType.
11109   ObjCPropertyRefExpr *PRE
11110     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11111   if (PRE && !PRE->isImplicitProperty()) {
11112     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11113     if (PD)
11114       LHSType = PD->getType();
11115   }
11116 
11117   if (LHSType.isNull())
11118     LHSType = LHS->getType();
11119 
11120   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11121 
11122   if (LT == Qualifiers::OCL_Weak) {
11123     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11124       getCurFunction()->markSafeWeakUse(LHS);
11125   }
11126 
11127   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11128     return;
11129 
11130   // FIXME. Check for other life times.
11131   if (LT != Qualifiers::OCL_None)
11132     return;
11133 
11134   if (PRE) {
11135     if (PRE->isImplicitProperty())
11136       return;
11137     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11138     if (!PD)
11139       return;
11140 
11141     unsigned Attributes = PD->getPropertyAttributes();
11142     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11143       // when 'assign' attribute was not explicitly specified
11144       // by user, ignore it and rely on property type itself
11145       // for lifetime info.
11146       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11147       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11148           LHSType->isObjCRetainableType())
11149         return;
11150 
11151       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11152         if (cast->getCastKind() == CK_ARCConsumeObject) {
11153           Diag(Loc, diag::warn_arc_retained_property_assign)
11154           << RHS->getSourceRange();
11155           return;
11156         }
11157         RHS = cast->getSubExpr();
11158       }
11159     }
11160     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11161       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11162         return;
11163     }
11164   }
11165 }
11166 
11167 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11168 
11169 namespace {
11170 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11171                                  SourceLocation StmtLoc,
11172                                  const NullStmt *Body) {
11173   // Do not warn if the body is a macro that expands to nothing, e.g:
11174   //
11175   // #define CALL(x)
11176   // if (condition)
11177   //   CALL(0);
11178   //
11179   if (Body->hasLeadingEmptyMacro())
11180     return false;
11181 
11182   // Get line numbers of statement and body.
11183   bool StmtLineInvalid;
11184   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11185                                                       &StmtLineInvalid);
11186   if (StmtLineInvalid)
11187     return false;
11188 
11189   bool BodyLineInvalid;
11190   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11191                                                       &BodyLineInvalid);
11192   if (BodyLineInvalid)
11193     return false;
11194 
11195   // Warn if null statement and body are on the same line.
11196   if (StmtLine != BodyLine)
11197     return false;
11198 
11199   return true;
11200 }
11201 } // end anonymous namespace
11202 
11203 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11204                                  const Stmt *Body,
11205                                  unsigned DiagID) {
11206   // Since this is a syntactic check, don't emit diagnostic for template
11207   // instantiations, this just adds noise.
11208   if (CurrentInstantiationScope)
11209     return;
11210 
11211   // The body should be a null statement.
11212   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11213   if (!NBody)
11214     return;
11215 
11216   // Do the usual checks.
11217   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11218     return;
11219 
11220   Diag(NBody->getSemiLoc(), DiagID);
11221   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11222 }
11223 
11224 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11225                                  const Stmt *PossibleBody) {
11226   assert(!CurrentInstantiationScope); // Ensured by caller
11227 
11228   SourceLocation StmtLoc;
11229   const Stmt *Body;
11230   unsigned DiagID;
11231   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11232     StmtLoc = FS->getRParenLoc();
11233     Body = FS->getBody();
11234     DiagID = diag::warn_empty_for_body;
11235   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11236     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11237     Body = WS->getBody();
11238     DiagID = diag::warn_empty_while_body;
11239   } else
11240     return; // Neither `for' nor `while'.
11241 
11242   // The body should be a null statement.
11243   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11244   if (!NBody)
11245     return;
11246 
11247   // Skip expensive checks if diagnostic is disabled.
11248   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11249     return;
11250 
11251   // Do the usual checks.
11252   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11253     return;
11254 
11255   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11256   // noise level low, emit diagnostics only if for/while is followed by a
11257   // CompoundStmt, e.g.:
11258   //    for (int i = 0; i < n; i++);
11259   //    {
11260   //      a(i);
11261   //    }
11262   // or if for/while is followed by a statement with more indentation
11263   // than for/while itself:
11264   //    for (int i = 0; i < n; i++);
11265   //      a(i);
11266   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11267   if (!ProbableTypo) {
11268     bool BodyColInvalid;
11269     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11270                              PossibleBody->getLocStart(),
11271                              &BodyColInvalid);
11272     if (BodyColInvalid)
11273       return;
11274 
11275     bool StmtColInvalid;
11276     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11277                              S->getLocStart(),
11278                              &StmtColInvalid);
11279     if (StmtColInvalid)
11280       return;
11281 
11282     if (BodyCol > StmtCol)
11283       ProbableTypo = true;
11284   }
11285 
11286   if (ProbableTypo) {
11287     Diag(NBody->getSemiLoc(), DiagID);
11288     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11289   }
11290 }
11291 
11292 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11293 
11294 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11295 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11296                              SourceLocation OpLoc) {
11297   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11298     return;
11299 
11300   if (!ActiveTemplateInstantiations.empty())
11301     return;
11302 
11303   // Strip parens and casts away.
11304   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11305   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11306 
11307   // Check for a call expression
11308   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11309   if (!CE || CE->getNumArgs() != 1)
11310     return;
11311 
11312   // Check for a call to std::move
11313   const FunctionDecl *FD = CE->getDirectCallee();
11314   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11315       !FD->getIdentifier()->isStr("move"))
11316     return;
11317 
11318   // Get argument from std::move
11319   RHSExpr = CE->getArg(0);
11320 
11321   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11322   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11323 
11324   // Two DeclRefExpr's, check that the decls are the same.
11325   if (LHSDeclRef && RHSDeclRef) {
11326     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11327       return;
11328     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11329         RHSDeclRef->getDecl()->getCanonicalDecl())
11330       return;
11331 
11332     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11333                                         << LHSExpr->getSourceRange()
11334                                         << RHSExpr->getSourceRange();
11335     return;
11336   }
11337 
11338   // Member variables require a different approach to check for self moves.
11339   // MemberExpr's are the same if every nested MemberExpr refers to the same
11340   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11341   // the base Expr's are CXXThisExpr's.
11342   const Expr *LHSBase = LHSExpr;
11343   const Expr *RHSBase = RHSExpr;
11344   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11345   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11346   if (!LHSME || !RHSME)
11347     return;
11348 
11349   while (LHSME && RHSME) {
11350     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11351         RHSME->getMemberDecl()->getCanonicalDecl())
11352       return;
11353 
11354     LHSBase = LHSME->getBase();
11355     RHSBase = RHSME->getBase();
11356     LHSME = dyn_cast<MemberExpr>(LHSBase);
11357     RHSME = dyn_cast<MemberExpr>(RHSBase);
11358   }
11359 
11360   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11361   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11362   if (LHSDeclRef && RHSDeclRef) {
11363     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11364       return;
11365     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11366         RHSDeclRef->getDecl()->getCanonicalDecl())
11367       return;
11368 
11369     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11370                                         << LHSExpr->getSourceRange()
11371                                         << RHSExpr->getSourceRange();
11372     return;
11373   }
11374 
11375   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11376     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11377                                         << LHSExpr->getSourceRange()
11378                                         << RHSExpr->getSourceRange();
11379 }
11380 
11381 //===--- Layout compatibility ----------------------------------------------//
11382 
11383 namespace {
11384 
11385 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11386 
11387 /// \brief Check if two enumeration types are layout-compatible.
11388 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11389   // C++11 [dcl.enum] p8:
11390   // Two enumeration types are layout-compatible if they have the same
11391   // underlying type.
11392   return ED1->isComplete() && ED2->isComplete() &&
11393          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11394 }
11395 
11396 /// \brief Check if two fields are layout-compatible.
11397 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11398   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11399     return false;
11400 
11401   if (Field1->isBitField() != Field2->isBitField())
11402     return false;
11403 
11404   if (Field1->isBitField()) {
11405     // Make sure that the bit-fields are the same length.
11406     unsigned Bits1 = Field1->getBitWidthValue(C);
11407     unsigned Bits2 = Field2->getBitWidthValue(C);
11408 
11409     if (Bits1 != Bits2)
11410       return false;
11411   }
11412 
11413   return true;
11414 }
11415 
11416 /// \brief Check if two standard-layout structs are layout-compatible.
11417 /// (C++11 [class.mem] p17)
11418 bool isLayoutCompatibleStruct(ASTContext &C,
11419                               RecordDecl *RD1,
11420                               RecordDecl *RD2) {
11421   // If both records are C++ classes, check that base classes match.
11422   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11423     // If one of records is a CXXRecordDecl we are in C++ mode,
11424     // thus the other one is a CXXRecordDecl, too.
11425     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11426     // Check number of base classes.
11427     if (D1CXX->getNumBases() != D2CXX->getNumBases())
11428       return false;
11429 
11430     // Check the base classes.
11431     for (CXXRecordDecl::base_class_const_iterator
11432                Base1 = D1CXX->bases_begin(),
11433            BaseEnd1 = D1CXX->bases_end(),
11434               Base2 = D2CXX->bases_begin();
11435          Base1 != BaseEnd1;
11436          ++Base1, ++Base2) {
11437       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11438         return false;
11439     }
11440   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11441     // If only RD2 is a C++ class, it should have zero base classes.
11442     if (D2CXX->getNumBases() > 0)
11443       return false;
11444   }
11445 
11446   // Check the fields.
11447   RecordDecl::field_iterator Field2 = RD2->field_begin(),
11448                              Field2End = RD2->field_end(),
11449                              Field1 = RD1->field_begin(),
11450                              Field1End = RD1->field_end();
11451   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11452     if (!isLayoutCompatible(C, *Field1, *Field2))
11453       return false;
11454   }
11455   if (Field1 != Field1End || Field2 != Field2End)
11456     return false;
11457 
11458   return true;
11459 }
11460 
11461 /// \brief Check if two standard-layout unions are layout-compatible.
11462 /// (C++11 [class.mem] p18)
11463 bool isLayoutCompatibleUnion(ASTContext &C,
11464                              RecordDecl *RD1,
11465                              RecordDecl *RD2) {
11466   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11467   for (auto *Field2 : RD2->fields())
11468     UnmatchedFields.insert(Field2);
11469 
11470   for (auto *Field1 : RD1->fields()) {
11471     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11472         I = UnmatchedFields.begin(),
11473         E = UnmatchedFields.end();
11474 
11475     for ( ; I != E; ++I) {
11476       if (isLayoutCompatible(C, Field1, *I)) {
11477         bool Result = UnmatchedFields.erase(*I);
11478         (void) Result;
11479         assert(Result);
11480         break;
11481       }
11482     }
11483     if (I == E)
11484       return false;
11485   }
11486 
11487   return UnmatchedFields.empty();
11488 }
11489 
11490 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11491   if (RD1->isUnion() != RD2->isUnion())
11492     return false;
11493 
11494   if (RD1->isUnion())
11495     return isLayoutCompatibleUnion(C, RD1, RD2);
11496   else
11497     return isLayoutCompatibleStruct(C, RD1, RD2);
11498 }
11499 
11500 /// \brief Check if two types are layout-compatible in C++11 sense.
11501 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11502   if (T1.isNull() || T2.isNull())
11503     return false;
11504 
11505   // C++11 [basic.types] p11:
11506   // If two types T1 and T2 are the same type, then T1 and T2 are
11507   // layout-compatible types.
11508   if (C.hasSameType(T1, T2))
11509     return true;
11510 
11511   T1 = T1.getCanonicalType().getUnqualifiedType();
11512   T2 = T2.getCanonicalType().getUnqualifiedType();
11513 
11514   const Type::TypeClass TC1 = T1->getTypeClass();
11515   const Type::TypeClass TC2 = T2->getTypeClass();
11516 
11517   if (TC1 != TC2)
11518     return false;
11519 
11520   if (TC1 == Type::Enum) {
11521     return isLayoutCompatible(C,
11522                               cast<EnumType>(T1)->getDecl(),
11523                               cast<EnumType>(T2)->getDecl());
11524   } else if (TC1 == Type::Record) {
11525     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11526       return false;
11527 
11528     return isLayoutCompatible(C,
11529                               cast<RecordType>(T1)->getDecl(),
11530                               cast<RecordType>(T2)->getDecl());
11531   }
11532 
11533   return false;
11534 }
11535 } // end anonymous namespace
11536 
11537 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11538 
11539 namespace {
11540 /// \brief Given a type tag expression find the type tag itself.
11541 ///
11542 /// \param TypeExpr Type tag expression, as it appears in user's code.
11543 ///
11544 /// \param VD Declaration of an identifier that appears in a type tag.
11545 ///
11546 /// \param MagicValue Type tag magic value.
11547 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11548                      const ValueDecl **VD, uint64_t *MagicValue) {
11549   while(true) {
11550     if (!TypeExpr)
11551       return false;
11552 
11553     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11554 
11555     switch (TypeExpr->getStmtClass()) {
11556     case Stmt::UnaryOperatorClass: {
11557       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11558       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11559         TypeExpr = UO->getSubExpr();
11560         continue;
11561       }
11562       return false;
11563     }
11564 
11565     case Stmt::DeclRefExprClass: {
11566       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11567       *VD = DRE->getDecl();
11568       return true;
11569     }
11570 
11571     case Stmt::IntegerLiteralClass: {
11572       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11573       llvm::APInt MagicValueAPInt = IL->getValue();
11574       if (MagicValueAPInt.getActiveBits() <= 64) {
11575         *MagicValue = MagicValueAPInt.getZExtValue();
11576         return true;
11577       } else
11578         return false;
11579     }
11580 
11581     case Stmt::BinaryConditionalOperatorClass:
11582     case Stmt::ConditionalOperatorClass: {
11583       const AbstractConditionalOperator *ACO =
11584           cast<AbstractConditionalOperator>(TypeExpr);
11585       bool Result;
11586       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11587         if (Result)
11588           TypeExpr = ACO->getTrueExpr();
11589         else
11590           TypeExpr = ACO->getFalseExpr();
11591         continue;
11592       }
11593       return false;
11594     }
11595 
11596     case Stmt::BinaryOperatorClass: {
11597       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11598       if (BO->getOpcode() == BO_Comma) {
11599         TypeExpr = BO->getRHS();
11600         continue;
11601       }
11602       return false;
11603     }
11604 
11605     default:
11606       return false;
11607     }
11608   }
11609 }
11610 
11611 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
11612 ///
11613 /// \param TypeExpr Expression that specifies a type tag.
11614 ///
11615 /// \param MagicValues Registered magic values.
11616 ///
11617 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11618 ///        kind.
11619 ///
11620 /// \param TypeInfo Information about the corresponding C type.
11621 ///
11622 /// \returns true if the corresponding C type was found.
11623 bool GetMatchingCType(
11624         const IdentifierInfo *ArgumentKind,
11625         const Expr *TypeExpr, const ASTContext &Ctx,
11626         const llvm::DenseMap<Sema::TypeTagMagicValue,
11627                              Sema::TypeTagData> *MagicValues,
11628         bool &FoundWrongKind,
11629         Sema::TypeTagData &TypeInfo) {
11630   FoundWrongKind = false;
11631 
11632   // Variable declaration that has type_tag_for_datatype attribute.
11633   const ValueDecl *VD = nullptr;
11634 
11635   uint64_t MagicValue;
11636 
11637   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11638     return false;
11639 
11640   if (VD) {
11641     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11642       if (I->getArgumentKind() != ArgumentKind) {
11643         FoundWrongKind = true;
11644         return false;
11645       }
11646       TypeInfo.Type = I->getMatchingCType();
11647       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11648       TypeInfo.MustBeNull = I->getMustBeNull();
11649       return true;
11650     }
11651     return false;
11652   }
11653 
11654   if (!MagicValues)
11655     return false;
11656 
11657   llvm::DenseMap<Sema::TypeTagMagicValue,
11658                  Sema::TypeTagData>::const_iterator I =
11659       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11660   if (I == MagicValues->end())
11661     return false;
11662 
11663   TypeInfo = I->second;
11664   return true;
11665 }
11666 } // end anonymous namespace
11667 
11668 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11669                                       uint64_t MagicValue, QualType Type,
11670                                       bool LayoutCompatible,
11671                                       bool MustBeNull) {
11672   if (!TypeTagForDatatypeMagicValues)
11673     TypeTagForDatatypeMagicValues.reset(
11674         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11675 
11676   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11677   (*TypeTagForDatatypeMagicValues)[Magic] =
11678       TypeTagData(Type, LayoutCompatible, MustBeNull);
11679 }
11680 
11681 namespace {
11682 bool IsSameCharType(QualType T1, QualType T2) {
11683   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11684   if (!BT1)
11685     return false;
11686 
11687   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11688   if (!BT2)
11689     return false;
11690 
11691   BuiltinType::Kind T1Kind = BT1->getKind();
11692   BuiltinType::Kind T2Kind = BT2->getKind();
11693 
11694   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
11695          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
11696          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11697          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11698 }
11699 } // end anonymous namespace
11700 
11701 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11702                                     const Expr * const *ExprArgs) {
11703   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11704   bool IsPointerAttr = Attr->getIsPointer();
11705 
11706   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11707   bool FoundWrongKind;
11708   TypeTagData TypeInfo;
11709   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11710                         TypeTagForDatatypeMagicValues.get(),
11711                         FoundWrongKind, TypeInfo)) {
11712     if (FoundWrongKind)
11713       Diag(TypeTagExpr->getExprLoc(),
11714            diag::warn_type_tag_for_datatype_wrong_kind)
11715         << TypeTagExpr->getSourceRange();
11716     return;
11717   }
11718 
11719   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11720   if (IsPointerAttr) {
11721     // Skip implicit cast of pointer to `void *' (as a function argument).
11722     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11723       if (ICE->getType()->isVoidPointerType() &&
11724           ICE->getCastKind() == CK_BitCast)
11725         ArgumentExpr = ICE->getSubExpr();
11726   }
11727   QualType ArgumentType = ArgumentExpr->getType();
11728 
11729   // Passing a `void*' pointer shouldn't trigger a warning.
11730   if (IsPointerAttr && ArgumentType->isVoidPointerType())
11731     return;
11732 
11733   if (TypeInfo.MustBeNull) {
11734     // Type tag with matching void type requires a null pointer.
11735     if (!ArgumentExpr->isNullPointerConstant(Context,
11736                                              Expr::NPC_ValueDependentIsNotNull)) {
11737       Diag(ArgumentExpr->getExprLoc(),
11738            diag::warn_type_safety_null_pointer_required)
11739           << ArgumentKind->getName()
11740           << ArgumentExpr->getSourceRange()
11741           << TypeTagExpr->getSourceRange();
11742     }
11743     return;
11744   }
11745 
11746   QualType RequiredType = TypeInfo.Type;
11747   if (IsPointerAttr)
11748     RequiredType = Context.getPointerType(RequiredType);
11749 
11750   bool mismatch = false;
11751   if (!TypeInfo.LayoutCompatible) {
11752     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11753 
11754     // C++11 [basic.fundamental] p1:
11755     // Plain char, signed char, and unsigned char are three distinct types.
11756     //
11757     // But we treat plain `char' as equivalent to `signed char' or `unsigned
11758     // char' depending on the current char signedness mode.
11759     if (mismatch)
11760       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11761                                            RequiredType->getPointeeType())) ||
11762           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11763         mismatch = false;
11764   } else
11765     if (IsPointerAttr)
11766       mismatch = !isLayoutCompatible(Context,
11767                                      ArgumentType->getPointeeType(),
11768                                      RequiredType->getPointeeType());
11769     else
11770       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11771 
11772   if (mismatch)
11773     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
11774         << ArgumentType << ArgumentKind
11775         << TypeInfo.LayoutCompatible << RequiredType
11776         << ArgumentExpr->getSourceRange()
11777         << TypeTagExpr->getSourceRange();
11778 }
11779 
11780 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11781                                          CharUnits Alignment) {
11782   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11783 }
11784 
11785 void Sema::DiagnoseMisalignedMembers() {
11786   for (MisalignedMember &m : MisalignedMembers) {
11787     const NamedDecl *ND = m.RD;
11788     if (ND->getName().empty()) {
11789       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11790         ND = TD;
11791     }
11792     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11793         << m.MD << ND << m.E->getSourceRange();
11794   }
11795   MisalignedMembers.clear();
11796 }
11797 
11798 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11799   E = E->IgnoreParens();
11800   if (!T->isPointerType() && !T->isIntegerType())
11801     return;
11802   if (isa<UnaryOperator>(E) &&
11803       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11804     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11805     if (isa<MemberExpr>(Op)) {
11806       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11807                           MisalignedMember(Op));
11808       if (MA != MisalignedMembers.end() &&
11809           (T->isIntegerType() ||
11810            (T->isPointerType() &&
11811             Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
11812         MisalignedMembers.erase(MA);
11813     }
11814   }
11815 }
11816 
11817 void Sema::RefersToMemberWithReducedAlignment(
11818     Expr *E,
11819     std::function<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action) {
11820   const auto *ME = dyn_cast<MemberExpr>(E);
11821   if (!ME)
11822     return;
11823 
11824   // For a chain of MemberExpr like "a.b.c.d" this list
11825   // will keep FieldDecl's like [d, c, b].
11826   SmallVector<FieldDecl *, 4> ReverseMemberChain;
11827   const MemberExpr *TopME = nullptr;
11828   bool AnyIsPacked = false;
11829   do {
11830     QualType BaseType = ME->getBase()->getType();
11831     if (ME->isArrow())
11832       BaseType = BaseType->getPointeeType();
11833     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11834 
11835     ValueDecl *MD = ME->getMemberDecl();
11836     auto *FD = dyn_cast<FieldDecl>(MD);
11837     // We do not care about non-data members.
11838     if (!FD || FD->isInvalidDecl())
11839       return;
11840 
11841     AnyIsPacked =
11842         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11843     ReverseMemberChain.push_back(FD);
11844 
11845     TopME = ME;
11846     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11847   } while (ME);
11848   assert(TopME && "We did not compute a topmost MemberExpr!");
11849 
11850   // Not the scope of this diagnostic.
11851   if (!AnyIsPacked)
11852     return;
11853 
11854   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11855   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11856   // TODO: The innermost base of the member expression may be too complicated.
11857   // For now, just disregard these cases. This is left for future
11858   // improvement.
11859   if (!DRE && !isa<CXXThisExpr>(TopBase))
11860       return;
11861 
11862   // Alignment expected by the whole expression.
11863   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11864 
11865   // No need to do anything else with this case.
11866   if (ExpectedAlignment.isOne())
11867     return;
11868 
11869   // Synthesize offset of the whole access.
11870   CharUnits Offset;
11871   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11872        I++) {
11873     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11874   }
11875 
11876   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11877   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11878       ReverseMemberChain.back()->getParent()->getTypeForDecl());
11879 
11880   // The base expression of the innermost MemberExpr may give
11881   // stronger guarantees than the class containing the member.
11882   if (DRE && !TopME->isArrow()) {
11883     const ValueDecl *VD = DRE->getDecl();
11884     if (!VD->getType()->isReferenceType())
11885       CompleteObjectAlignment =
11886           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11887   }
11888 
11889   // Check if the synthesized offset fulfills the alignment.
11890   if (Offset % ExpectedAlignment != 0 ||
11891       // It may fulfill the offset it but the effective alignment may still be
11892       // lower than the expected expression alignment.
11893       CompleteObjectAlignment < ExpectedAlignment) {
11894     // If this happens, we want to determine a sensible culprit of this.
11895     // Intuitively, watching the chain of member expressions from right to
11896     // left, we start with the required alignment (as required by the field
11897     // type) but some packed attribute in that chain has reduced the alignment.
11898     // It may happen that another packed structure increases it again. But if
11899     // we are here such increase has not been enough. So pointing the first
11900     // FieldDecl that either is packed or else its RecordDecl is,
11901     // seems reasonable.
11902     FieldDecl *FD = nullptr;
11903     CharUnits Alignment;
11904     for (FieldDecl *FDI : ReverseMemberChain) {
11905       if (FDI->hasAttr<PackedAttr>() ||
11906           FDI->getParent()->hasAttr<PackedAttr>()) {
11907         FD = FDI;
11908         Alignment = std::min(
11909             Context.getTypeAlignInChars(FD->getType()),
11910             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11911         break;
11912       }
11913     }
11914     assert(FD && "We did not find a packed FieldDecl!");
11915     Action(E, FD->getParent(), FD, Alignment);
11916   }
11917 }
11918 
11919 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11920   using namespace std::placeholders;
11921   RefersToMemberWithReducedAlignment(
11922       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11923                      _2, _3, _4));
11924 }
11925 
11926